You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

172 lines
4.7 KiB

12 years ago
12 years ago
12 years ago
  1. package main
  2. import (
  3. "code.google.com/p/weed-fs/go/operation"
  4. "code.google.com/p/weed-fs/go/util"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strconv"
  13. )
  14. var (
  15. uploadReplication *string
  16. uploadDir *string
  17. include *string
  18. )
  19. func init() {
  20. cmdUpload.Run = runUpload // break init cycle
  21. cmdUpload.IsDebug = cmdUpload.Flag.Bool("debug", false, "verbose debug information")
  22. server = cmdUpload.Flag.String("server", "localhost:9333", "weedfs master location")
  23. uploadDir = cmdUpload.Flag.String("dir", "", "Upload the whole folder recursively if specified.")
  24. include = cmdUpload.Flag.String("include", "", "pattens of files to upload, e.g., *.pdf, *.html, ab?d.txt, works together with -dir")
  25. uploadReplication = cmdUpload.Flag.String("replication", "", "replication type(000,001,010,100,110,200)")
  26. }
  27. var cmdUpload = &Command{
  28. UsageLine: "upload -server=localhost:9333 file1 [file2 file3]\n upload -server=localhost:9333 -dir=one_directory -include=*.pdf",
  29. Short: "upload one or a list of files",
  30. Long: `upload one or a list of files, or batch upload one whole folder recursively.
  31. If uploading a list of files:
  32. It uses consecutive file keys for the list of files.
  33. e.g. If the file1 uses key k, file2 can be read via k_1
  34. If uploading a whole folder recursively:
  35. All files under the folder and subfolders will be uploaded, each with its own file key.
  36. Optional parameter "-include" allows you to specify the file name patterns.
  37. If any file has a ".gz" extension, the content are considered gzipped already, and will be stored as is.
  38. This can save volume server's gzipped processing and allow customizable gzip compression level.
  39. The file name will strip out ".gz" and stored. For example, "jquery.js.gz" will be stored as "jquery.js".
  40. `,
  41. }
  42. type AssignResult struct {
  43. Fid string `json:"fid"`
  44. Url string `json:"url"`
  45. PublicUrl string `json:"publicUrl"`
  46. Count int
  47. Error string `json:"error"`
  48. }
  49. func assign(count int) (*AssignResult, error) {
  50. values := make(url.Values)
  51. values.Add("count", strconv.Itoa(count))
  52. if *uploadReplication != "" {
  53. values.Add("replication", *uploadReplication)
  54. }
  55. jsonBlob, err := util.Post("http://"+*server+"/dir/assign", values)
  56. debug("assign result :", string(jsonBlob))
  57. if err != nil {
  58. return nil, err
  59. }
  60. var ret AssignResult
  61. err = json.Unmarshal(jsonBlob, &ret)
  62. if err != nil {
  63. return nil, err
  64. }
  65. if ret.Count <= 0 {
  66. return nil, errors.New(ret.Error)
  67. }
  68. return &ret, nil
  69. }
  70. func upload(filename string, server string, fid string) (int, error) {
  71. debug("Start uploading file:", filename)
  72. fh, err := os.Open(filename)
  73. if err != nil {
  74. debug("Failed to open file:", filename)
  75. return 0, err
  76. }
  77. fi, fiErr := fh.Stat()
  78. if fiErr != nil {
  79. debug("Failed to stat file:", filename)
  80. return 0, fiErr
  81. }
  82. filename = path.Base(filename)
  83. isGzipped := path.Ext(filename) == ".gz"
  84. if isGzipped {
  85. filename = filename[0 : len(filename)-3]
  86. }
  87. ret, e := operation.Upload("http://"+server+"/"+fid+"?ts="+strconv.Itoa(int(fi.ModTime().Unix())), filename, fh, isGzipped)
  88. if e != nil {
  89. return 0, e
  90. }
  91. return ret.Size, e
  92. }
  93. type SubmitResult struct {
  94. FileName string `json:"fileName"`
  95. FileUrl string `json:"fileUrl"`
  96. Fid string `json:"fid"`
  97. Size int `json:"size"`
  98. Error string `json:"error"`
  99. }
  100. func submit(files []string) ([]SubmitResult, error) {
  101. results := make([]SubmitResult, len(files))
  102. for index, file := range files {
  103. results[index].FileName = file
  104. }
  105. ret, err := assign(len(files))
  106. if err != nil {
  107. for index, _ := range files {
  108. results[index].Error = err.Error()
  109. }
  110. return results, err
  111. }
  112. for index, file := range files {
  113. fid := ret.Fid
  114. if index > 0 {
  115. fid = fid + "_" + strconv.Itoa(index)
  116. }
  117. results[index].Size, err = upload(file, ret.PublicUrl, fid)
  118. if err != nil {
  119. fid = ""
  120. results[index].Error = err.Error()
  121. }
  122. results[index].Fid = fid
  123. results[index].FileUrl = ret.PublicUrl + "/" + fid
  124. }
  125. return results, nil
  126. }
  127. func runUpload(cmd *Command, args []string) bool {
  128. if len(cmdUpload.Flag.Args()) == 0 {
  129. if *uploadDir == "" {
  130. return false
  131. }
  132. filepath.Walk(*uploadDir, func(path string, info os.FileInfo, err error) error {
  133. if err == nil {
  134. if !info.IsDir() {
  135. if *include != "" {
  136. if ok, _ := filepath.Match(*include, filepath.Base(path)); !ok {
  137. return nil
  138. }
  139. }
  140. results, e := submit([]string{path})
  141. bytes, _ := json.Marshal(results)
  142. fmt.Println(string(bytes))
  143. if e != nil {
  144. return e
  145. }
  146. }
  147. } else {
  148. fmt.Println(err)
  149. }
  150. return err
  151. })
  152. } else {
  153. results, _ := submit(args)
  154. bytes, _ := json.Marshal(results)
  155. fmt.Println(string(bytes))
  156. }
  157. return true
  158. }