main.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "math"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "github.com/FossoresLP/go-uuid-v4"
  12. )
  13. func check(e error) {
  14. if e != nil {
  15. panic(e)
  16. }
  17. }
  18. //ArOZ PHP-Golang Bridge
  19. //The following sections remap the PHP functions to golang for the ease of development
  20. func file_exists(filepath string) bool {
  21. if _, err := os.Stat(filepath); !os.IsNotExist(err) {
  22. return true
  23. }
  24. return false
  25. }
  26. func mkdir(filepath string) {
  27. os.MkdirAll(filepath, os.ModePerm)
  28. }
  29. func file_put_contents(file string, data string) bool {
  30. f, err := os.Create(file)
  31. check(err)
  32. _, err = f.WriteString(data)
  33. defer f.Close()
  34. if err != nil {
  35. return false
  36. }
  37. return true
  38. }
  39. func file_get_contents(file string) string {
  40. b, err := ioutil.ReadFile(file)
  41. check(err)
  42. return string(b)
  43. }
  44. func strtolower(word string) string {
  45. return strings.ToLower(word)
  46. }
  47. func strtoupper(word string) string {
  48. return strings.ToUpper(word)
  49. }
  50. func trim(word string) string {
  51. return strings.Trim(word, " ")
  52. }
  53. func strlen(word string) int {
  54. return len(word)
  55. }
  56. func count(array []string) int {
  57. return len(array)
  58. }
  59. func explode(key string, word string) []string {
  60. return strings.Split(word, key)
  61. }
  62. func implode(key string, array []string) string {
  63. return strings.Join(array[:], key)
  64. }
  65. func str_replace(target string, result string, word string) string {
  66. return strings.Replace(word, target, result, -1)
  67. }
  68. func in_array(a string, list []string) bool {
  69. for _, b := range list {
  70. if b == a {
  71. return true
  72. }
  73. }
  74. return false
  75. }
  76. func strpos(word string, target string) int {
  77. return strings.Index(word, target)
  78. }
  79. func dirname(filepath string) string {
  80. return path.Dir(filepath)
  81. }
  82. func basename(filepath string) string {
  83. return path.Base(filepath)
  84. }
  85. //End of mapping functions
  86. //Utilities functions
  87. func genUUIDv4() string {
  88. uuid, err := uuid.NewString()
  89. check(err)
  90. return uuid
  91. }
  92. func padZeros(thisInt string, maxval int) string {
  93. targetLength := len(strconv.Itoa(maxval))
  94. result := thisInt
  95. if len(thisInt) < targetLength {
  96. padzeros := targetLength - len(thisInt)
  97. for i := 0; i < padzeros; i++ {
  98. result = "0" + result
  99. }
  100. }
  101. return result
  102. }
  103. //End of utilities functions
  104. func init() {
  105. //Check if the required directory exists. If not, create it.
  106. if !file_exists("setting.config") {
  107. setting, err := os.Create("setting.config")
  108. check(err)
  109. defer setting.Close()
  110. setting.WriteString("")
  111. setting.Sync()
  112. }
  113. if !file_exists("chunks/") {
  114. mkdir("chunks/")
  115. }
  116. if !file_exists("uploads/") {
  117. mkdir("uploads/")
  118. }
  119. if !file_exists("index/") {
  120. mkdir("index/")
  121. }
  122. }
  123. func main() {
  124. //arozdfs implementation in Golang
  125. /*
  126. Supported commands:
  127. help --> show all the help information
  128. [Uploading to arozdfs commands]
  129. slice
  130. -infile <filename> --> declare the input file
  131. -storepath <pathname> --> Relative path from the arozdfs root
  132. -slice <filesize> --> declare the slicing filesize
  133. upload
  134. -push <clusterlist.config> --> push to a list of clusters and sync file index to other clusters
  135. [Download from arozdfs commands]
  136. download
  137. -outfile <file.index> --> rebuild a file from cluster storage to local drive
  138. open
  139. -storepath <local path> --> the file chunks tmp folder
  140. -uuid <file uuid> --> the uuid which the file is stored
  141. -outfile <filename> --> filepath for the exported and merged file
  142. [File Operations]
  143. remove <file.index> --> remove all chunks related to thie file index
  144. rename <file.index> <newfile.index> --> rename all records related to this file
  145. move <filepath/file.index> <newpath/file.index> --> move the file to a new path in index directory
  146. [System checking commands]
  147. checkfile <file.index> --> check if a file contains all chunks which has at least two copies of each chunks
  148. rebuild --> Check all files on the system and fix all chunks which has corrupted
  149. migrate <host-uuid>
  150. */
  151. //For each argument, start the processing
  152. switch functgroup := os.Args[1]; functgroup {
  153. case "help":
  154. showHelp()
  155. case "slice":
  156. startSlicingProc()
  157. case "upload":
  158. startUploadProc()
  159. case "download":
  160. startDownloadProc()
  161. case "open":
  162. openChunkedFile()
  163. case "debug":
  164. fmt.Println(padZeros("1", 32)) //Debug function. Change this line for unit testing
  165. default:
  166. showNotFound()
  167. }
  168. /*
  169. //Examples for using the Go-PHP bridge functions
  170. file_put_contents("Hello World.txt", "This is the content of the file.")
  171. fmt.Println(file_get_contents("Hello World.txt"))
  172. array := explode(",", "Apple,Orange,Pizza")
  173. fmt.Println(array)
  174. newstring := implode(",", array)
  175. fmt.Println(newstring)
  176. fmt.Println(in_array("Pizza", array))
  177. fmt.Println(strpos(newstring, "Pizza"))
  178. fmt.Println(strtoupper("hello world"))
  179. fmt.Println(str_replace("Pizza", "Ramen", newstring))
  180. */
  181. }
  182. func startDownloadProc() {
  183. }
  184. func startSlicingProc() {
  185. storepath := ""
  186. infile := ""
  187. slice := 64 //Default 64MB per file chunk
  188. fileUUID := genUUIDv4()
  189. for i, arg := range os.Args {
  190. if strpos(arg, "-") == 0 {
  191. //This is a parameter defining keyword
  192. if arg == "-infile" {
  193. infile = os.Args[i+1]
  194. } else if arg == "-storepath" {
  195. storepath = os.Args[i+1]
  196. } else if arg == "-slice" {
  197. sliceSize, err := strconv.Atoi(os.Args[i+1])
  198. check(err)
  199. slice = sliceSize
  200. }
  201. }
  202. }
  203. if storepath != "" && infile != "" {
  204. fmt.Println(storepath + " " + infile + " " + strconv.Itoa(slice) + " " + fileUUID)
  205. splitFileChunks(infile, "chunks/"+storepath+"/", fileUUID, slice)
  206. } else {
  207. fmt.Println("ERROR. Undefined storepath or infile.")
  208. }
  209. }
  210. func splitFileChunks(rawfile string, outputdir string, outfilename string, chunksize int) bool {
  211. if !file_exists(outputdir) {
  212. mkdir(outputdir)
  213. }
  214. fileToBeChunked := rawfile
  215. file, err := os.Open(fileToBeChunked)
  216. if err != nil {
  217. return false
  218. }
  219. defer file.Close()
  220. fileInfo, _ := file.Stat()
  221. var fileSize int64 = fileInfo.Size()
  222. var fileChunk = float64(chunksize * 1000 * 1000) // chunksize in MB
  223. // calculate total number of parts the file will be chunked into
  224. totalPartsNum := uint64(math.Ceil(float64(fileSize) / float64(fileChunk)))
  225. fmt.Printf("Splitting to %d pieces.\n", totalPartsNum)
  226. for i := uint64(0); i < totalPartsNum; i++ {
  227. partSize := int(math.Min(fileChunk, float64(fileSize-int64(i*uint64(fileChunk)))))
  228. partBuffer := make([]byte, partSize)
  229. file.Read(partBuffer)
  230. // write to disk
  231. fileName := outputdir + outfilename + "_" + padZeros(strconv.FormatUint(i, 10), int(totalPartsNum))
  232. _, err := os.Create(fileName)
  233. if err != nil {
  234. return false
  235. }
  236. // write/save buffer to disk
  237. ioutil.WriteFile(fileName, partBuffer, os.ModeAppend)
  238. fmt.Println("Split to : ", fileName)
  239. }
  240. return true
  241. }
  242. func openChunkedFile() {
  243. storepath := ""
  244. uuid := ""
  245. outfile := ""
  246. for i, arg := range os.Args {
  247. if strpos(arg, "-") == 0 {
  248. //This is a parameter defining keyword
  249. if arg == "-uuid" {
  250. uuid = os.Args[i+1]
  251. } else if arg == "-storepath" {
  252. storepath = os.Args[i+1]
  253. } else if arg == "-outfile" {
  254. outfile = os.Args[i+1]
  255. }
  256. }
  257. }
  258. if storepath != "" && uuid != "" && outfile != "" {
  259. fmt.Println(storepath + " " + uuid + " " + outfile)
  260. joinFileChunks(storepath+"/"+uuid, outfile)
  261. } else {
  262. fmt.Println("ERROR. Undefined storepath, outfile or uuid.")
  263. }
  264. }
  265. func joinFileChunks(fileuuid string, outfilename string) bool {
  266. matches, _ := filepath.Glob(fileuuid + "_*")
  267. if len(matches) == 0 {
  268. fmt.Println("ERROR. No filechunk file for this uuid.")
  269. return false
  270. }
  271. outfile, err := os.Create(outfilename)
  272. if err != nil {
  273. return false
  274. }
  275. //For each file chunk, merge them into the output file
  276. for j := 0; j < len(matches); j++ {
  277. b, _ := ioutil.ReadFile(matches[j])
  278. outfile.Write(b)
  279. }
  280. return true
  281. }
  282. func startUploadProc() {
  283. for i, arg := range os.Args {
  284. // print index and value
  285. fmt.Println("item", i, "is", arg)
  286. }
  287. }
  288. func showHelp() {
  289. }
  290. func showNotFound() {
  291. fmt.Println("ERROR. Command not found for function group: " + os.Args[1])
  292. }