123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552 |
- package main
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "io/ioutil"
- "math"
- "mime/multipart"
- "net/http"
- "os"
- "path"
- "path/filepath"
- "strconv"
- "strings"
- "github.com/FossoresLP/go-uuid-v4"
- )
- func check(e error) {
- if e != nil {
- panic(e)
- }
- }
- //ArOZ PHP-Golang Bridge
- //The following sections remap the PHP functions to golang for the ease of development
- func file_exists(filepath string) bool {
- if _, err := os.Stat(filepath); !os.IsNotExist(err) {
- return true
- }
- return false
- }
- func mkdir(filepath string) {
- os.MkdirAll(filepath, os.ModePerm)
- }
- func file_put_contents(file string, data string) bool {
- f, err := os.Create(file)
- check(err)
- _, err = f.WriteString(data)
- defer f.Close()
- if err != nil {
- return false
- }
- return true
- }
- func file_get_contents(file string) string {
- b, err := ioutil.ReadFile(file)
- check(err)
- return string(b)
- }
- func strtolower(word string) string {
- return strings.ToLower(word)
- }
- func strtoupper(word string) string {
- return strings.ToUpper(word)
- }
- func trim(word string) string {
- return strings.Trim(word, " ")
- }
- func strlen(word string) int {
- return len(word)
- }
- func count(array []string) int {
- return len(array)
- }
- func explode(key string, word string) []string {
- return strings.Split(word, key)
- }
- func implode(key string, array []string) string {
- return strings.Join(array[:], key)
- }
- func str_replace(target string, result string, word string) string {
- return strings.Replace(word, target, result, -1)
- }
- func in_array(a string, list []string) bool {
- for _, b := range list {
- if b == a {
- return true
- }
- }
- return false
- }
- func strpos(word string, target string) int {
- return strings.Index(word, target)
- }
- func dirname(filepath string) string {
- return path.Dir(filepath)
- }
- func basename(filepath string) string {
- return path.Base(filepath)
- }
- //End of mapping functions
- //Utilities functions
- func genUUIDv4() string {
- uuid, err := uuid.NewString()
- check(err)
- return uuid
- }
- func padZeros(thisInt string, maxval int) string {
- targetLength := len(strconv.Itoa(maxval))
- result := thisInt
- if len(thisInt) < targetLength {
- padzeros := targetLength - len(thisInt)
- for i := 0; i < padzeros; i++ {
- result = "0" + result
- }
- }
- return result
- }
- type clusterConfig struct {
- Prefix string `json: "prefix"`
- Port string `json: "port`
- }
- //End of utilities functions
- func init() {
- //Check if the required directory exists. If not, create it.
- if !file_exists("chunks/") {
- mkdir("chunks/")
- }
- if !file_exists("uploads/") {
- mkdir("uploads/")
- }
- if !file_exists("index/") {
- mkdir("index/")
- }
- if !file_exists("tmp/") {
- mkdir("tmp/")
- }
- if !file_exists("remoteDisks.config") {
- file_put_contents("remoteDisks.config", "")
- }
- }
- func main() {
- //arozdfs implementation in Golang
- //Refer to the help section for the usable commands and parameters
- if len(os.Args) == 1 {
- fmt.Println("ERROR. Undefined function group or operations. Type 'arozdfs help' for usage instructions. ")
- return
- }
- //For each argument, start the processing
- switch functgroup := os.Args[1]; functgroup {
- case "help":
- showHelp()
- case "slice":
- startSlicingProc()
- case "upload":
- startUploadProc()
- case "download":
- startDownloadProc()
- case "open":
- openChunkedFile()
- case "debug":
- fmt.Println(padZeros("1", 32)) //Debug function. Change this line for unit testing
- default:
- showNotFound()
- }
- /*
- //Examples for using the Go-PHP bridge functions
- file_put_contents("Hello World.txt", "This is the content of the file.")
- fmt.Println(file_get_contents("Hello World.txt"))
- array := explode(",", "Apple,Orange,Pizza")
- fmt.Println(array)
- newstring := implode(",", array)
- fmt.Println(newstring)
- fmt.Println(in_array("Pizza", array))
- fmt.Println(strpos(newstring, "Pizza"))
- fmt.Println(strtoupper("hello world"))
- fmt.Println(str_replace("Pizza", "Ramen", newstring))
- */
- }
- func startDownloadProc() {
- }
- func startSlicingProc() {
- infile := ""
- slice := 64 //Default 64MB per file chunk
- fileUUID := genUUIDv4()
- storepath := fileUUID + "/"
- for i, arg := range os.Args {
- if strpos(arg, "-") == 0 {
- //This is a parameter defining keyword
- if arg == "-infile" {
- infile = os.Args[i+1]
- } else if arg == "-storepath" {
- storepath = os.Args[i+1]
- //Check if the storepath is end with /. if not, append it into the pathname
- if storepath[len(storepath)-1:] != "/" {
- storepath = storepath + "/"
- }
- } else if arg == "-slice" {
- sliceSize, err := strconv.Atoi(os.Args[i+1])
- check(err)
- slice = sliceSize
- }
- }
- }
- if slice <= 0 {
- fmt.Println("ERROR. slice size cannot be smaller or equal to 0")
- os.Exit(0)
- }
- if storepath != "" && infile != "" {
- fmt.Println(storepath + " " + infile + " " + strconv.Itoa(slice) + " " + fileUUID)
- splitFileChunks(infile, "chunks/"+storepath, fileUUID, slice)
- fmt.Println(fileUUID)
- } else {
- fmt.Println("ERROR. Undefined storepath or infile.")
- }
- }
- func splitFileChunks(rawfile string, outputdir string, outfilename string, chunksize int) bool {
- if !file_exists(outputdir) {
- mkdir(outputdir)
- }
- fileToBeChunked := rawfile
- file, err := os.Open(fileToBeChunked)
- if err != nil {
- return false
- }
- defer file.Close()
- fileInfo, _ := file.Stat()
- var fileSize int64 = fileInfo.Size()
- var fileChunk = float64(chunksize * 1024 * 1024) // chunksize in MB
- // calculate total number of parts the file will be chunked into
- totalPartsNum := uint64(math.Ceil(float64(fileSize) / float64(fileChunk)))
- fmt.Printf("Splitting to %d pieces.\n", totalPartsNum)
- for i := uint64(0); i < totalPartsNum; i++ {
- partSize := int(math.Min(fileChunk, float64(fileSize-int64(i*uint64(fileChunk)))))
- partBuffer := make([]byte, partSize)
- file.Read(partBuffer)
- // write to disk
- fileName := outputdir + outfilename + "_" + padZeros(strconv.FormatUint(i, 10), int(totalPartsNum))
- _, err := os.Create(fileName)
- if err != nil {
- return false
- }
- // write/save buffer to disk
- ioutil.WriteFile(fileName, partBuffer, os.ModeAppend)
- fmt.Println("Split to : ", fileName)
- }
- return true
- }
- func openChunkedFile() {
- storepath := "tmp/"
- uuid := ""
- outfile := ""
- removeAfterMerge := 0
- for i, arg := range os.Args {
- if strpos(arg, "-") == 0 {
- //This is a parameter defining keyword
- if arg == "-uuid" {
- uuid = os.Args[i+1]
- } else if arg == "-storepath" {
- storepath = os.Args[i+1]
- //Check if the storepath is end with /. if not, append it into the pathname
- if storepath[len(storepath)-1:] != "/" {
- storepath = storepath + "/"
- }
- } else if arg == "-outfile" {
- outfile = os.Args[i+1]
- } else if arg == "-c" {
- //Remove the file chunks after the merging process
- removeAfterMerge = 1
- }
- }
- }
- if storepath != "" && uuid != "" && outfile != "" {
- fmt.Println(storepath + " " + uuid + " " + outfile)
- if joinFileChunks(storepath+uuid, outfile) {
- //Do checksum here
- //Remove all files if -c is used
- if removeAfterMerge == 1 {
- matches, _ := filepath.Glob(storepath + uuid + "_*")
- for j := 0; j < len(matches); j++ {
- os.Remove(matches[j])
- }
- }
- } else {
- fmt.Println("ERROR. Unable to merge file chunks.")
- }
- } else {
- fmt.Println("ERROR. Undefined storepath, outfile or uuid.")
- }
- }
- func joinFileChunks(fileuuid string, outfilename string) bool {
- matches, _ := filepath.Glob(fileuuid + "_*")
- if len(matches) == 0 {
- fmt.Println("ERROR. No filechunk file for this uuid.")
- return false
- }
- outfile, err := os.Create(outfilename)
- if err != nil {
- return false
- }
- //For each file chunk, merge them into the output file
- for j := 0; j < len(matches); j++ {
- b, _ := ioutil.ReadFile(matches[j])
- outfile.Write(b)
- }
- return true
- }
- func startUploadProc() {
- push := "remoteDisks.config"
- storepath := "tmp/"
- uuid := ""
- vdir := ""
- for i, arg := range os.Args {
- if strpos(arg, "-") == 0 {
- //This is a parameter defining keyword
- if arg == "-uuid" {
- uuid = os.Args[i+1]
- } else if arg == "-storepath" {
- storepath = os.Args[i+1]
- //Check if the storepath is end with /. if not, append it into the pathname
- if storepath[len(storepath)-1:] != "/" {
- storepath = storepath + "/"
- }
- } else if arg == "-vdir" {
- vdir = os.Args[i+1]
- } else if arg == "-push" {
- //Remove the file chunks after the merging process
- push = os.Args[i+1]
- }
- }
- }
- //Check if the input data are valid
- if uuid == "" || vdir == "" {
- fmt.Println("ERROR. Undefined uuid or vdir.")
- os.Exit(0)
- }
- if !file_exists("clusterSetting.config") {
- fmt.Println("ERROR. clusterSetting configuration not found")
- os.Exit(0)
- }
- if file_exists("index/" + vdir + string(".index")) {
- fmt.Println("ERROR. Given file already exists in vdir. Please use remove before uploading a new file on the same vdir location.")
- os.Exit(0)
- }
- //Starting the uuid to ip conversion process
- var ipList []string
- //Read cluster setting from clusterSetting.config
- jsonFile, _ := os.Open("clusterSetting.config")
- byteValue, _ := ioutil.ReadAll(jsonFile)
- var config clusterConfig
- var uuiddata []string
- json.Unmarshal(byteValue, &config)
- //Read cluster uuid list from remoteDisks.config
- if file_exists(push) {
- clusteruuids := file_get_contents(push)
- if trim(clusteruuids) == "" {
- fmt.Println("ERROR. remoteDisks not found or it is empty! ")
- os.Exit(0)
- }
- clusteruuids = trim(strings.Trim(clusteruuids, "\n"))
- uuiddata = explode("\n", clusteruuids)
- //Generate iplist and ready for posting file chunks
- for i := 0; i < len(uuiddata); i++ {
- thisip := resolveUUID(uuiddata[i])
- clusterConfig := ":" + string(config.Port) + "/" + string(config.Prefix) + "/"
- fullip := "http://" + thisip + clusterConfig
- ipList = append(ipList, fullip)
- }
- } else {
- fmt.Println("ERROR. remoteDisks not found or it is empty! ")
- os.Exit(0)
- }
- fmt.Println(ipList)
- //Ready to push. Create index file.
- file_put_contents("index/"+vdir+string(".index"), "")
- fileList, _ := filepath.Glob(storepath + uuid + "_*")
- var pushResultTarget []string
- var pushResultFilename []string
- var failed []string
- var failedTarget []string
- for i := 0; i < len(fileList); i++ {
- uploadIP := (ipList[i%len(ipList)])
- r := pushFileChunk(uuid, uploadIP, fileList[i])
- if trim(r) == "DONE" {
- //This upload process is doing fine. Append to the result list
- pushResultTarget = append(pushResultTarget, uuiddata[i%len(ipList)])
- pushResultFilename = append(pushResultFilename, filepath.Base(fileList[i]))
- fmt.Println("[OK] " + fileList[i] + " uploaded.")
- } else {
- failed = append(failed, fileList[i])
- failedTarget = append(failedTarget, uuid)
- }
- }
- for j := 0; j < len(pushResultTarget); j++ {
- f, _ := os.OpenFile("index/"+vdir+string(".index"), os.O_APPEND|os.O_WRONLY, 0600)
- defer f.Close()
- f.WriteString(pushResultFilename[j])
- f.WriteString(",")
- f.WriteString(pushResultTarget[j])
- f.WriteString("\n")
- }
- fmt.Println("[OK] All chunks uploaded.")
- }
- func pushFileChunk(uuid string, targetEndpoint string, filename string) string {
- response := string(SendPostRequest(targetEndpoint+"SystemAOB/functions/arozdfs/upload.php", filename, "file"))
- return response
- }
- func resolveUUID(uuid string) string {
- tmp := []byte(uuid)
- uuid = string(bytes.Trim(tmp, "\xef\xbb\xbf"))
- uuid = strings.Trim(strings.Trim(uuid, "\n"), "\r")
- if file_exists("../cluster/mappers/") {
- if file_exists("../cluster/mappers/" + uuid + ".inf") {
- return file_get_contents("../cluster/mappers/" + uuid + ".inf")
- } else {
- fmt.Println("ERROR. UUID not found. Please perform a scan first before using arozdfs functions")
- }
- } else {
- fmt.Println("ERROR. Unable to resolve UUID to IP: cluster services not found. Continuing with UUID as IP address.")
- }
- return uuid
- }
- func SendPostRequest(url string, filename string, fieldname string) []byte {
- file, err := os.Open(filename)
- if err != nil {
- panic(err)
- }
- defer file.Close()
- body := &bytes.Buffer{}
- writer := multipart.NewWriter(body)
- part, err := writer.CreateFormFile(fieldname, filepath.Base(file.Name()))
- if err != nil {
- panic(err)
- }
- io.Copy(part, file)
- writer.Close()
- request, err := http.NewRequest("POST", url, body)
- if err != nil {
- panic(err)
- }
- request.Header.Add("Content-Type", writer.FormDataContentType())
- client := &http.Client{}
- response, err := client.Do(request)
- if err != nil {
- panic(err)
- }
- defer response.Body.Close()
- content, err := ioutil.ReadAll(response.Body)
- if err != nil {
- panic(err)
- }
- return content
- }
- func showHelp() {
- fmt.Println(`[arozdfs - Distributed File Storage Management Tool for ArOZ Online Cloud System]
- This is a command line tool build for the ArOZ Online distributed cloud platform file chunking and redundant data storage.
- Please refer to the ArOZ Online Documentaion for more information.
- `)
- fmt.Println(`Supported commands:
- help --> show all the help information
- [Uploading to arozdfs commands]
- slice
- -infile <filename> --> declare the input file
- -slice <filesize> --> declare the slicing filesize
- -storepath <pathname> (Optional) --> Relative path for storing the sliced chunk files, default ./{file-uuid}
- upload
- -push <remoteDisks.config> --> push to a list of clusters and sync file index to other clusters
- -storepath <pathname> --> The location where the file chunks are stored
- -uuid <file uuid> --> uuid of the file to be uploaded
- -vdir <file.index> --> where the file.index should be stored. (Use for file / folder navigation)
- [Download from arozdfs commands]
- download
- -vdir <file.index> --> file.index location
- -storepath <tmp directory> (Optional) --> define a special directory for caching the downloaded data chunks, default ./tmp
- open
- -storepath <tmp directory> --> the file chunks tmp folder, default ./tmp
- -uuid <file uuid> --> the uuid which the file is stored
- -outfile <filename> --> filepath for the exported and merged file
- -c --> remove all stored file chunks after merging the file chunks.
- [File Operations]
- remove <file.index> --> remove all chunks related to thie file index
- rename <file.index> <newfile.index> --> rename all records related to this file
- move <filepath/file.index> <newpath/file.index> --> move the file to a new path in index directory
- [System checking commands]
- checkfile <file.index> --> check if a file contains all chunks which has at least two copies of each chunks
- rebuild --> Check all files on the system and fix all chunks which has corrupted
- migrate <remoteDisks.config> --> Move all chunks from this host to other servers in the list.`)
- }
- func showNotFound() {
- fmt.Println("ERROR. Command not found for function group: " + os.Args[1])
- }
|