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.

279 lines
8.2 KiB

  1. package command
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/url"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/chrislusf/seaweedfs/weed/operation"
  10. filer_operation "github.com/chrislusf/seaweedfs/weed/operation/filer"
  11. "github.com/chrislusf/seaweedfs/weed/security"
  12. "path"
  13. "net/http"
  14. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  15. "strconv"
  16. "io"
  17. "time"
  18. "google.golang.org/grpc"
  19. "context"
  20. )
  21. var (
  22. copy CopyOptions
  23. )
  24. type CopyOptions struct {
  25. master *string
  26. include *string
  27. replication *string
  28. collection *string
  29. ttl *string
  30. maxMB *int
  31. secretKey *string
  32. secret security.Secret
  33. }
  34. func init() {
  35. cmdCopy.Run = runCopy // break init cycle
  36. cmdCopy.IsDebug = cmdCopy.Flag.Bool("debug", false, "verbose debug information")
  37. copy.master = cmdCopy.Flag.String("master", "localhost:9333", "SeaweedFS master location")
  38. copy.include = cmdCopy.Flag.String("include", "", "pattens of files to copy, e.g., *.pdf, *.html, ab?d.txt, works together with -dir")
  39. copy.replication = cmdCopy.Flag.String("replication", "", "replication type")
  40. copy.collection = cmdCopy.Flag.String("collection", "", "optional collection name")
  41. copy.ttl = cmdCopy.Flag.String("ttl", "", "time to live, e.g.: 1m, 1h, 1d, 1M, 1y")
  42. copy.maxMB = cmdCopy.Flag.Int("maxMB", 0, "split files larger than the limit")
  43. copy.secretKey = cmdCopy.Flag.String("secure.secret", "", "secret to encrypt Json Web Token(JWT)")
  44. }
  45. var cmdCopy = &Command{
  46. UsageLine: "filer.copy file_or_dir1 [file_or_dir2 file_or_dir3] http://localhost:8888/path/to/a/folder/",
  47. Short: "copy one or a list of files to a filer folder",
  48. Long: `copy one or a list of files, or batch copy one whole folder recursively, to a filer folder
  49. It can copy one or a list of files or folders.
  50. If copying a whole folder recursively:
  51. All files under the folder and subfolders will be copyed.
  52. Optional parameter "-include" allows you to specify the file name patterns.
  53. If any file has a ".gz" extension, the content are considered gzipped already, and will be stored as is.
  54. This can save volume server's gzipped processing and allow customizable gzip compression level.
  55. The file name will strip out ".gz" and stored. For example, "jquery.js.gz" will be stored as "jquery.js".
  56. If "maxMB" is set to a positive number, files larger than it would be split into chunks and copyed separatedly.
  57. The list of file ids of those chunks would be stored in an additional chunk, and this additional chunk's file id would be returned.
  58. `,
  59. }
  60. func runCopy(cmd *Command, args []string) bool {
  61. copy.secret = security.Secret(*copy.secretKey)
  62. if len(args) <= 1 {
  63. return false
  64. }
  65. filerDestination := args[len(args)-1]
  66. fileOrDirs := args[0: len(args)-1]
  67. filerUrl, err := url.Parse(filerDestination)
  68. if err != nil {
  69. fmt.Printf("The last argument should be a URL on filer: %v\n", err)
  70. return false
  71. }
  72. urlPath := filerUrl.Path
  73. if !strings.HasSuffix(urlPath, "/") {
  74. urlPath = urlPath + "/"
  75. }
  76. for _, fileOrDir := range fileOrDirs {
  77. if !doEachCopy(fileOrDir, filerUrl.Host, urlPath) {
  78. return false
  79. }
  80. }
  81. return true
  82. }
  83. func doEachCopy(fileOrDir string, host string, path string) bool {
  84. f, err := os.Open(fileOrDir)
  85. if err != nil {
  86. fmt.Printf("Failed to open file %s: %v\n", fileOrDir, err)
  87. return false
  88. }
  89. defer f.Close()
  90. fi, err := f.Stat()
  91. if err != nil {
  92. fmt.Printf("Failed to get stat for file %s: %v\n", fileOrDir, err)
  93. return false
  94. }
  95. mode := fi.Mode()
  96. if mode.IsDir() {
  97. files, _ := ioutil.ReadDir(fileOrDir)
  98. for _, subFileOrDir := range files {
  99. if !doEachCopy(fileOrDir+"/"+subFileOrDir.Name(), host, path+fi.Name()+"/") {
  100. return false
  101. }
  102. }
  103. return true
  104. }
  105. // this is a regular file
  106. if *copy.include != "" {
  107. if ok, _ := filepath.Match(*copy.include, filepath.Base(fileOrDir)); !ok {
  108. return true
  109. }
  110. }
  111. // find the chunk count
  112. chunkSize := int64(*copy.maxMB * 1024 * 1024)
  113. chunkCount := 1
  114. if chunkSize > 0 && fi.Size() > chunkSize {
  115. chunkCount = int(fi.Size()/chunkSize) + 1
  116. }
  117. // assign a volume
  118. assignResult, err := operation.Assign(*copy.master, &operation.VolumeAssignRequest{
  119. Count: uint64(chunkCount),
  120. Replication: *copy.replication,
  121. Collection: *copy.collection,
  122. Ttl: *copy.ttl,
  123. })
  124. if err != nil {
  125. fmt.Printf("Failed to assign from %s: %v\n", *copy.master, err)
  126. }
  127. if chunkCount == 1 {
  128. return uploadFileAsOne(host, path, assignResult, f, fi)
  129. }
  130. return uploadFileInChunks(host, path, assignResult, f, fi, chunkCount, chunkSize)
  131. }
  132. func uploadFileAsOne(filerUrl string, urlFolder string, assignResult *operation.AssignResult, f *os.File, fi os.FileInfo) bool {
  133. // upload the file content
  134. mimeType := detectMimeType(f)
  135. isGzipped := isGzipped(f.Name())
  136. targetUrl := "http://" + assignResult.Url + "/" + assignResult.Fid
  137. uploadResult, err := operation.Upload(targetUrl, f.Name(), f, isGzipped, mimeType, nil, "")
  138. if err != nil {
  139. fmt.Printf("upload data %v to %s: %v\n", f.Name(), targetUrl, err)
  140. return false
  141. }
  142. if uploadResult.Error != "" {
  143. fmt.Printf("upload %v to %s result: %v\n", f.Name(), targetUrl, uploadResult.Error)
  144. return false
  145. }
  146. fmt.Printf("uploaded %s to %s\n", f.Name(), targetUrl)
  147. if err = filer_operation.RegisterFile(filerUrl, filepath.Join(urlFolder, f.Name()), assignResult.Fid, fi.Size(),
  148. os.Getuid(), os.Getgid(), copy.secret); err != nil {
  149. fmt.Printf("Failed to register file %s on %s: %v\n", f.Name(), filerUrl, err)
  150. return false
  151. }
  152. fmt.Printf("copied %s => http://%s%s%s\n", f.Name(), filerUrl, urlFolder, f.Name())
  153. return true
  154. }
  155. func uploadFileInChunks(filerUrl string, urlFolder string, assignResult *operation.AssignResult, f *os.File, fi os.FileInfo, chunkCount int, chunkSize int64) bool {
  156. var chunks []*filer_pb.FileChunk
  157. for i := int64(0); i < int64(chunkCount); i++ {
  158. fileId := assignResult.Fid
  159. if i > 0 {
  160. fileId += "_" + strconv.FormatInt(i, 10)
  161. }
  162. targetUrl := "http://" + assignResult.Url + "/" + fileId
  163. uploadResult, err := operation.Upload(targetUrl,
  164. f.Name()+"-"+strconv.FormatInt(i+1, 10),
  165. io.LimitReader(f, chunkSize),
  166. false, "application/octet-stream", nil, "")
  167. if err != nil {
  168. fmt.Printf("upload data %v to %s: %v\n", f.Name(), targetUrl, err)
  169. return false
  170. }
  171. if uploadResult.Error != "" {
  172. fmt.Printf("upload %v to %s result: %v\n", f.Name(), targetUrl, uploadResult.Error)
  173. return false
  174. }
  175. chunks = append(chunks, &filer_pb.FileChunk{
  176. FileId: fileId,
  177. Offset: i * chunkSize,
  178. Size: uint64(uploadResult.Size),
  179. Mtime: time.Now().UnixNano(),
  180. })
  181. fmt.Printf("uploaded %s split %d => %s\n", f.Name(), i, targetUrl)
  182. }
  183. if err := withFilerClient(filerUrl, func(client filer_pb.SeaweedFilerClient) error {
  184. request := &filer_pb.CreateEntryRequest{
  185. Directory: urlFolder,
  186. Entry: &filer_pb.Entry{
  187. Name: f.Name(),
  188. Attributes: &filer_pb.FuseAttributes{
  189. Crtime: time.Now().Unix(),
  190. Mtime: time.Now().Unix(),
  191. Gid: uint32(os.Getgid()),
  192. Uid: uint32(os.Getuid()),
  193. FileSize: uint64(fi.Size()),
  194. FileMode: uint32(fi.Mode()),
  195. },
  196. Chunks: chunks,
  197. },
  198. }
  199. fmt.Printf("%s%s set chunks: %v", urlFolder, f.Name(), len(chunks))
  200. for i, chunk := range chunks {
  201. fmt.Printf("%s%s chunks %d: %v [%d,%d)\n", urlFolder, f.Name(), i, chunk.FileId, chunk.Offset, chunk.Offset+int64(chunk.Size))
  202. }
  203. if _, err := client.CreateEntry(context.Background(), request); err != nil {
  204. return fmt.Errorf("update fh: %v", err)
  205. }
  206. return nil
  207. }); err != nil {
  208. fmt.Printf("upload data %v to http://%s%s%s: %v\n", f.Name(), filerUrl, urlFolder, f.Name(), err)
  209. return false
  210. }
  211. return true
  212. }
  213. func isGzipped(filename string) bool {
  214. return strings.ToLower(path.Ext(filename)) == ".gz"
  215. }
  216. func detectMimeType(f *os.File) string {
  217. head := make([]byte, 512)
  218. f.Seek(0, 0)
  219. n, err := f.Read(head)
  220. if err != nil {
  221. fmt.Printf("read head of %v: %v\n", f.Name(), err)
  222. return "application/octet-stream"
  223. }
  224. f.Seek(0, 0)
  225. mimeType := http.DetectContentType(head[:n])
  226. return mimeType
  227. }
  228. func withFilerClient(filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error {
  229. grpcConnection, err := grpc.Dial(filerAddress, grpc.WithInsecure())
  230. if err != nil {
  231. return fmt.Errorf("fail to dial %s: %v", filerAddress, err)
  232. }
  233. defer grpcConnection.Close()
  234. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  235. return fn(client)
  236. }