main.go 17 KB

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