main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "math"
  9. "mime/multipart"
  10. "net/http"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "github.com/FossoresLP/go-uuid-v4"
  17. )
  18. func check(e error) {
  19. if e != nil {
  20. panic(e)
  21. }
  22. }
  23. //ArOZ PHP-Golang Bridge
  24. //The following sections remap the PHP functions to golang for the ease of development
  25. func file_exists(filepath string) bool {
  26. if _, err := os.Stat(filepath); !os.IsNotExist(err) {
  27. return true
  28. }
  29. return false
  30. }
  31. func mkdir(filepath string) {
  32. os.MkdirAll(filepath, os.ModePerm)
  33. }
  34. func file_put_contents(file string, data string) bool {
  35. f, err := os.Create(file)
  36. check(err)
  37. _, err = f.WriteString(data)
  38. defer f.Close()
  39. if err != nil {
  40. return false
  41. }
  42. return true
  43. }
  44. func file_get_contents(file string) string {
  45. b, err := ioutil.ReadFile(file)
  46. check(err)
  47. return string(b)
  48. }
  49. func strtolower(word string) string {
  50. return strings.ToLower(word)
  51. }
  52. func strtoupper(word string) string {
  53. return strings.ToUpper(word)
  54. }
  55. func trim(word string) string {
  56. return strings.Trim(word, " ")
  57. }
  58. func strlen(word string) int {
  59. return len(word)
  60. }
  61. func count(array []string) int {
  62. return len(array)
  63. }
  64. func explode(key string, word string) []string {
  65. return strings.Split(word, key)
  66. }
  67. func implode(key string, array []string) string {
  68. return strings.Join(array[:], key)
  69. }
  70. func str_replace(target string, result string, word string) string {
  71. return strings.Replace(word, target, result, -1)
  72. }
  73. func in_array(a string, list []string) bool {
  74. for _, b := range list {
  75. if b == a {
  76. return true
  77. }
  78. }
  79. return false
  80. }
  81. func strpos(word string, target string) int {
  82. return strings.Index(word, target)
  83. }
  84. func dirname(filepath string) string {
  85. return path.Dir(filepath)
  86. }
  87. func basename(filepath string) string {
  88. return path.Base(filepath)
  89. }
  90. //End of mapping functions
  91. //Utilities functions
  92. func genUUIDv4() string {
  93. uuid, err := uuid.NewString()
  94. check(err)
  95. return uuid
  96. }
  97. func padZeros(thisInt string, maxval int) string {
  98. targetLength := len(strconv.Itoa(maxval))
  99. result := thisInt
  100. if len(thisInt) < targetLength {
  101. padzeros := targetLength - len(thisInt)
  102. for i := 0; i < padzeros; i++ {
  103. result = "0" + result
  104. }
  105. }
  106. return result
  107. }
  108. type clusterConfig struct {
  109. Prefix string `json: "prefix"`
  110. Port string `json: "port`
  111. }
  112. //End of utilities functions
  113. func init() {
  114. //Check if the required directory exists. If not, create it.
  115. if !file_exists("chunks/") {
  116. mkdir("chunks/")
  117. }
  118. if !file_exists("uploads/") {
  119. mkdir("uploads/")
  120. }
  121. if !file_exists("index/") {
  122. mkdir("index/")
  123. }
  124. if !file_exists("tmp/") {
  125. mkdir("tmp/")
  126. }
  127. if !file_exists("remoteDisks.config") {
  128. file_put_contents("remoteDisks.config", "")
  129. }
  130. }
  131. func main() {
  132. //arozdfs implementation in Golang
  133. //Refer to the help section for the usable commands and parameters
  134. if len(os.Args) == 1 {
  135. fmt.Println("ERROR. Undefined function group or operations. Type 'arozdfs help' for usage instructions. ")
  136. return
  137. }
  138. //For each argument, start the processing
  139. switch functgroup := os.Args[1]; functgroup {
  140. case "help":
  141. showHelp()
  142. case "slice":
  143. startSlicingProc()
  144. case "upload":
  145. startUploadProc()
  146. case "download":
  147. startDownloadProc()
  148. case "open":
  149. openChunkedFile()
  150. case "debug":
  151. fmt.Println(padZeros("1", 32)) //Debug function. Change this line for unit testing
  152. default:
  153. showNotFound()
  154. }
  155. /*
  156. //Examples for using the Go-PHP bridge functions
  157. file_put_contents("Hello World.txt", "This is the content of the file.")
  158. fmt.Println(file_get_contents("Hello World.txt"))
  159. array := explode(",", "Apple,Orange,Pizza")
  160. fmt.Println(array)
  161. newstring := implode(",", array)
  162. fmt.Println(newstring)
  163. fmt.Println(in_array("Pizza", array))
  164. fmt.Println(strpos(newstring, "Pizza"))
  165. fmt.Println(strtoupper("hello world"))
  166. fmt.Println(str_replace("Pizza", "Ramen", newstring))
  167. */
  168. }
  169. func startDownloadProc() {
  170. }
  171. func startSlicingProc() {
  172. infile := ""
  173. slice := 64 //Default 64MB per file chunk
  174. fileUUID := genUUIDv4()
  175. storepath := fileUUID + "/"
  176. for i, arg := range os.Args {
  177. if strpos(arg, "-") == 0 {
  178. //This is a parameter defining keyword
  179. if arg == "-infile" {
  180. infile = os.Args[i+1]
  181. } else if arg == "-storepath" {
  182. storepath = os.Args[i+1]
  183. //Check if the storepath is end with /. if not, append it into the pathname
  184. if storepath[len(storepath)-1:] != "/" {
  185. storepath = storepath + "/"
  186. }
  187. } else if arg == "-slice" {
  188. sliceSize, err := strconv.Atoi(os.Args[i+1])
  189. check(err)
  190. slice = sliceSize
  191. }
  192. }
  193. }
  194. if slice <= 0 {
  195. fmt.Println("ERROR. slice size cannot be smaller or equal to 0")
  196. os.Exit(0)
  197. }
  198. if storepath != "" && infile != "" {
  199. fmt.Println(storepath + " " + infile + " " + strconv.Itoa(slice) + " " + fileUUID)
  200. splitFileChunks(infile, "chunks/"+storepath, fileUUID, slice)
  201. fmt.Println(fileUUID)
  202. } else {
  203. fmt.Println("ERROR. Undefined storepath or infile.")
  204. }
  205. }
  206. func splitFileChunks(rawfile string, outputdir string, outfilename string, chunksize int) bool {
  207. if !file_exists(outputdir) {
  208. mkdir(outputdir)
  209. }
  210. fileToBeChunked := rawfile
  211. file, err := os.Open(fileToBeChunked)
  212. if err != nil {
  213. return false
  214. }
  215. defer file.Close()
  216. fileInfo, _ := file.Stat()
  217. var fileSize int64 = fileInfo.Size()
  218. var fileChunk = float64(chunksize * 1024 * 1024) // chunksize in MB
  219. // calculate total number of parts the file will be chunked into
  220. totalPartsNum := uint64(math.Ceil(float64(fileSize) / float64(fileChunk)))
  221. fmt.Printf("Splitting to %d pieces.\n", totalPartsNum)
  222. for i := uint64(0); i < totalPartsNum; i++ {
  223. partSize := int(math.Min(fileChunk, float64(fileSize-int64(i*uint64(fileChunk)))))
  224. partBuffer := make([]byte, partSize)
  225. file.Read(partBuffer)
  226. // write to disk
  227. fileName := outputdir + outfilename + "_" + padZeros(strconv.FormatUint(i, 10), int(totalPartsNum))
  228. _, err := os.Create(fileName)
  229. if err != nil {
  230. return false
  231. }
  232. // write/save buffer to disk
  233. ioutil.WriteFile(fileName, partBuffer, os.ModeAppend)
  234. fmt.Println("Split to : ", fileName)
  235. }
  236. return true
  237. }
  238. func openChunkedFile() {
  239. storepath := "tmp/"
  240. uuid := ""
  241. outfile := ""
  242. removeAfterMerge := 0
  243. for i, arg := range os.Args {
  244. if strpos(arg, "-") == 0 {
  245. //This is a parameter defining keyword
  246. if arg == "-uuid" {
  247. uuid = os.Args[i+1]
  248. } else if arg == "-storepath" {
  249. storepath = os.Args[i+1]
  250. //Check if the storepath is end with /. if not, append it into the pathname
  251. if storepath[len(storepath)-1:] != "/" {
  252. storepath = storepath + "/"
  253. }
  254. } else if arg == "-outfile" {
  255. outfile = os.Args[i+1]
  256. } else if arg == "-c" {
  257. //Remove the file chunks after the merging process
  258. removeAfterMerge = 1
  259. }
  260. }
  261. }
  262. if storepath != "" && uuid != "" && outfile != "" {
  263. fmt.Println(storepath + " " + uuid + " " + outfile)
  264. if joinFileChunks(storepath+uuid, outfile) {
  265. //Do checksum here
  266. //Remove all files if -c is used
  267. if removeAfterMerge == 1 {
  268. matches, _ := filepath.Glob(storepath + uuid + "_*")
  269. for j := 0; j < len(matches); j++ {
  270. os.Remove(matches[j])
  271. }
  272. }
  273. } else {
  274. fmt.Println("ERROR. Unable to merge file chunks.")
  275. }
  276. } else {
  277. fmt.Println("ERROR. Undefined storepath, outfile or uuid.")
  278. }
  279. }
  280. func joinFileChunks(fileuuid string, outfilename string) bool {
  281. matches, _ := filepath.Glob(fileuuid + "_*")
  282. if len(matches) == 0 {
  283. fmt.Println("ERROR. No filechunk file for this uuid.")
  284. return false
  285. }
  286. outfile, err := os.Create(outfilename)
  287. if err != nil {
  288. return false
  289. }
  290. //For each file chunk, merge them into the output file
  291. for j := 0; j < len(matches); j++ {
  292. b, _ := ioutil.ReadFile(matches[j])
  293. outfile.Write(b)
  294. }
  295. return true
  296. }
  297. func startUploadProc() {
  298. push := "remoteDisks.config"
  299. storepath := "tmp/"
  300. uuid := ""
  301. vdir := ""
  302. for i, arg := range os.Args {
  303. if strpos(arg, "-") == 0 {
  304. //This is a parameter defining keyword
  305. if arg == "-uuid" {
  306. uuid = os.Args[i+1]
  307. } else if arg == "-storepath" {
  308. storepath = os.Args[i+1]
  309. //Check if the storepath is end with /. if not, append it into the pathname
  310. if storepath[len(storepath)-1:] != "/" {
  311. storepath = storepath + "/"
  312. }
  313. } else if arg == "-vdir" {
  314. vdir = os.Args[i+1]
  315. } else if arg == "-push" {
  316. //Remove the file chunks after the merging process
  317. push = os.Args[i+1]
  318. }
  319. }
  320. }
  321. //Check if the input data are valid
  322. if uuid == "" || vdir == "" {
  323. fmt.Println("ERROR. Undefined uuid or vdir.")
  324. os.Exit(0)
  325. }
  326. if !file_exists("clusterSetting.config") {
  327. fmt.Println("ERROR. clusterSetting configuration not found")
  328. os.Exit(0)
  329. }
  330. if file_exists("index/" + vdir + string(".index")) {
  331. fmt.Println("ERROR. Given file already exists in vdir. Please use remove before uploading a new file on the same vdir location.")
  332. os.Exit(0)
  333. }
  334. //Starting the uuid to ip conversion process
  335. var ipList []string
  336. //Read cluster setting from clusterSetting.config
  337. jsonFile, _ := os.Open("clusterSetting.config")
  338. byteValue, _ := ioutil.ReadAll(jsonFile)
  339. var config clusterConfig
  340. var uuiddata []string
  341. json.Unmarshal(byteValue, &config)
  342. //Read cluster uuid list from remoteDisks.config
  343. if file_exists(push) {
  344. clusteruuids := file_get_contents(push)
  345. if trim(clusteruuids) == "" {
  346. fmt.Println("ERROR. remoteDisks not found or it is empty! ")
  347. os.Exit(0)
  348. }
  349. clusteruuids = trim(strings.Trim(clusteruuids, "\n"))
  350. uuiddata = explode("\n", clusteruuids)
  351. //Generate iplist and ready for posting file chunks
  352. for i := 0; i < len(uuiddata); i++ {
  353. thisip := resolveUUID(uuiddata[i])
  354. clusterConfig := ":" + string(config.Port) + "/" + string(config.Prefix) + "/"
  355. fullip := "http://" + thisip + clusterConfig
  356. ipList = append(ipList, fullip)
  357. }
  358. } else {
  359. fmt.Println("ERROR. remoteDisks not found or it is empty! ")
  360. os.Exit(0)
  361. }
  362. fmt.Println(ipList)
  363. //Ready to push. Create index file.
  364. file_put_contents("index/"+vdir+string(".index"), "")
  365. fileList, _ := filepath.Glob(storepath + uuid + "_*")
  366. var pushResultTarget []string
  367. var pushResultFilename []string
  368. var failed []string
  369. var failedTarget []string
  370. for i := 0; i < len(fileList); i++ {
  371. uploadIP := (ipList[i%len(ipList)])
  372. r := pushFileChunk(uuid, uploadIP, fileList[i])
  373. if trim(r) == "DONE" {
  374. //This upload process is doing fine. Append to the result list
  375. pushResultTarget = append(pushResultTarget, uuiddata[i%len(ipList)])
  376. pushResultFilename = append(pushResultFilename, filepath.Base(fileList[i]))
  377. fmt.Println("[OK] " + fileList[i] + " uploaded.")
  378. } else {
  379. failed = append(failed, fileList[i])
  380. failedTarget = append(failedTarget, uuid)
  381. }
  382. }
  383. for j := 0; j < len(pushResultTarget); j++ {
  384. f, _ := os.OpenFile("index/"+vdir+string(".index"), os.O_APPEND|os.O_WRONLY, 0600)
  385. defer f.Close()
  386. f.WriteString(pushResultFilename[j])
  387. f.WriteString(",")
  388. f.WriteString(pushResultTarget[j])
  389. f.WriteString("\n")
  390. }
  391. fmt.Println("[OK] All chunks uploaded.")
  392. }
  393. func pushFileChunk(uuid string, targetEndpoint string, filename string) string {
  394. response := string(SendPostRequest(targetEndpoint+"SystemAOB/functions/arozdfs/upload.php", filename, "file"))
  395. return response
  396. }
  397. func resolveUUID(uuid string) string {
  398. tmp := []byte(uuid)
  399. uuid = string(bytes.Trim(tmp, "\xef\xbb\xbf"))
  400. uuid = strings.Trim(strings.Trim(uuid, "\n"), "\r")
  401. if file_exists("../cluster/mappers/") {
  402. if file_exists("../cluster/mappers/" + uuid + ".inf") {
  403. return file_get_contents("../cluster/mappers/" + uuid + ".inf")
  404. } else {
  405. fmt.Println("ERROR. UUID not found. Please perform a scan first before using arozdfs functions")
  406. }
  407. } else {
  408. fmt.Println("ERROR. Unable to resolve UUID to IP: cluster services not found. Continuing with UUID as IP address.")
  409. }
  410. return uuid
  411. }
  412. func SendPostRequest(url string, filename string, fieldname string) []byte {
  413. file, err := os.Open(filename)
  414. if err != nil {
  415. panic(err)
  416. }
  417. defer file.Close()
  418. body := &bytes.Buffer{}
  419. writer := multipart.NewWriter(body)
  420. part, err := writer.CreateFormFile(fieldname, filepath.Base(file.Name()))
  421. if err != nil {
  422. panic(err)
  423. }
  424. io.Copy(part, file)
  425. writer.Close()
  426. request, err := http.NewRequest("POST", url, body)
  427. if err != nil {
  428. panic(err)
  429. }
  430. request.Header.Add("Content-Type", writer.FormDataContentType())
  431. client := &http.Client{}
  432. response, err := client.Do(request)
  433. if err != nil {
  434. panic(err)
  435. }
  436. defer response.Body.Close()
  437. content, err := ioutil.ReadAll(response.Body)
  438. if err != nil {
  439. panic(err)
  440. }
  441. return content
  442. }
  443. func showHelp() {
  444. fmt.Println(`[arozdfs - Distributed File Storage Management Tool for ArOZ Online Cloud System]
  445. This is a command line tool build for the ArOZ Online distributed cloud platform file chunking and redundant data storage.
  446. Please refer to the ArOZ Online Documentaion for more information.
  447. `)
  448. fmt.Println(`Supported commands:
  449. help --> show all the help information
  450. [Uploading to arozdfs commands]
  451. slice
  452. -infile <filename> --> declare the input file
  453. -slice <filesize> --> declare the slicing filesize
  454. -storepath <pathname> (Optional) --> Relative path for storing the sliced chunk files, default ./{file-uuid}
  455. upload
  456. -push <remoteDisks.config> --> push to a list of clusters and sync file index to other clusters
  457. -storepath <pathname> --> The location where the file chunks are stored
  458. -uuid <file uuid> --> uuid of the file to be uploaded
  459. -vdir <file.index> --> where the file.index should be stored. (Use for file / folder navigation)
  460. [Download from arozdfs commands]
  461. download
  462. -vdir <file.index> --> file.index location
  463. -storepath <tmp directory> (Optional) --> define a special directory for caching the downloaded data chunks, default ./tmp
  464. open
  465. -storepath <tmp directory> --> the file chunks tmp folder, default ./tmp
  466. -uuid <file uuid> --> the uuid which the file is stored
  467. -outfile <filename> --> filepath for the exported and merged file
  468. -c --> remove all stored file chunks after merging the file chunks.
  469. [File Operations]
  470. remove <file.index> --> remove all chunks related to thie file index
  471. rename <file.index> <newfile.index> --> rename all records related to this file
  472. move <filepath/file.index> <newpath/file.index> --> move the file to a new path in index directory
  473. [System checking commands]
  474. checkfile <file.index> --> check if a file contains all chunks which has at least two copies of each chunks
  475. rebuild --> Check all files on the system and fix all chunks which has corrupted
  476. migrate <remoteDisks.config> --> Move all chunks from this host to other servers in the list.`)
  477. }
  478. func showNotFound() {
  479. fmt.Println("ERROR. Command not found for function group: " + os.Args[1])
  480. }