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.

351 lines
10 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. "github.com/chrislusf/seaweedfs/weed/security"
  11. "path"
  12. "net/http"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. "strconv"
  15. "io"
  16. "time"
  17. "context"
  18. "github.com/chrislusf/seaweedfs/weed/util"
  19. )
  20. var (
  21. copy CopyOptions
  22. )
  23. type CopyOptions struct {
  24. filerGrpcPort *int
  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.filerGrpcPort = cmdCopy.Flag.Int("filer.port.grpc", 0, "filer grpc server listen port, default to filer port + 10000")
  44. copy.secretKey = cmdCopy.Flag.String("secure.secret", "", "secret to encrypt Json Web Token(JWT)")
  45. }
  46. var cmdCopy = &Command{
  47. UsageLine: "filer.copy file_or_dir1 [file_or_dir2 file_or_dir3] http://localhost:8888/path/to/a/folder/",
  48. Short: "copy one or a list of files to a filer folder",
  49. Long: `copy one or a list of files, or batch copy one whole folder recursively, to a filer folder
  50. It can copy one or a list of files or folders.
  51. If copying a whole folder recursively:
  52. All files under the folder and subfolders will be copyed.
  53. Optional parameter "-include" allows you to specify the file name patterns.
  54. If any file has a ".gz" extension, the content are considered gzipped already, and will be stored as is.
  55. This can save volume server's gzipped processing and allow customizable gzip compression level.
  56. The file name will strip out ".gz" and stored. For example, "jquery.js.gz" will be stored as "jquery.js".
  57. If "maxMB" is set to a positive number, files larger than it would be split into chunks and copyed separatedly.
  58. 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.
  59. `,
  60. }
  61. func runCopy(cmd *Command, args []string) bool {
  62. copy.secret = security.Secret(*copy.secretKey)
  63. if len(args) <= 1 {
  64. return false
  65. }
  66. filerDestination := args[len(args)-1]
  67. fileOrDirs := args[0: len(args)-1]
  68. filerUrl, err := url.Parse(filerDestination)
  69. if err != nil {
  70. fmt.Printf("The last argument should be a URL on filer: %v\n", err)
  71. return false
  72. }
  73. urlPath := filerUrl.Path
  74. if !strings.HasSuffix(urlPath, "/") {
  75. urlPath = urlPath + "/"
  76. }
  77. if filerUrl.Port() == "" {
  78. fmt.Printf("The filer port should be specified.\n")
  79. return false
  80. }
  81. filerPort, parseErr := strconv.ParseUint(filerUrl.Port(), 10, 64)
  82. if parseErr != nil {
  83. fmt.Printf("The filer port parse error: %v\n", parseErr)
  84. return false
  85. }
  86. filerGrpcPort := filerPort + 10000
  87. if *copy.filerGrpcPort != 0 {
  88. filerGrpcPort = uint64(*copy.filerGrpcPort)
  89. }
  90. filerGrpcAddress := fmt.Sprintf("%s:%d", filerUrl.Hostname(), filerGrpcPort)
  91. for _, fileOrDir := range fileOrDirs {
  92. if !doEachCopy(fileOrDir, filerUrl.Host, filerGrpcAddress, urlPath) {
  93. return false
  94. }
  95. }
  96. return true
  97. }
  98. func doEachCopy(fileOrDir string, filerAddress, filerGrpcAddress string, path string) bool {
  99. f, err := os.Open(fileOrDir)
  100. if err != nil {
  101. fmt.Printf("Failed to open file %s: %v\n", fileOrDir, err)
  102. return false
  103. }
  104. defer f.Close()
  105. fi, err := f.Stat()
  106. if err != nil {
  107. fmt.Printf("Failed to get stat for file %s: %v\n", fileOrDir, err)
  108. return false
  109. }
  110. mode := fi.Mode()
  111. if mode.IsDir() {
  112. files, _ := ioutil.ReadDir(fileOrDir)
  113. for _, subFileOrDir := range files {
  114. if !doEachCopy(fileOrDir+"/"+subFileOrDir.Name(), filerAddress, filerGrpcAddress, path+fi.Name()+"/") {
  115. return false
  116. }
  117. }
  118. return true
  119. }
  120. // this is a regular file
  121. if *copy.include != "" {
  122. if ok, _ := filepath.Match(*copy.include, filepath.Base(fileOrDir)); !ok {
  123. return true
  124. }
  125. }
  126. // find the chunk count
  127. chunkSize := int64(*copy.maxMB * 1024 * 1024)
  128. chunkCount := 1
  129. if chunkSize > 0 && fi.Size() > chunkSize {
  130. chunkCount = int(fi.Size()/chunkSize) + 1
  131. }
  132. if chunkCount == 1 {
  133. return uploadFileAsOne(filerAddress, filerGrpcAddress, path, f, fi)
  134. }
  135. return uploadFileInChunks(filerAddress, filerGrpcAddress, path, f, fi, chunkCount, chunkSize)
  136. }
  137. func uploadFileAsOne(filerAddress, filerGrpcAddress string, urlFolder string, f *os.File, fi os.FileInfo) bool {
  138. // upload the file content
  139. fileName := filepath.Base(f.Name())
  140. mimeType := detectMimeType(f)
  141. isGzipped := isGzipped(fileName)
  142. var chunks []*filer_pb.FileChunk
  143. if fi.Size() > 0 {
  144. // assign a volume
  145. assignResult, err := operation.Assign(*copy.master, &operation.VolumeAssignRequest{
  146. Count: 1,
  147. Replication: *copy.replication,
  148. Collection: *copy.collection,
  149. Ttl: *copy.ttl,
  150. })
  151. if err != nil {
  152. fmt.Printf("Failed to assign from %s: %v\n", *copy.master, err)
  153. }
  154. targetUrl := "http://" + assignResult.Url + "/" + assignResult.Fid
  155. uploadResult, err := operation.Upload(targetUrl, fileName, f, isGzipped, mimeType, nil, "")
  156. if err != nil {
  157. fmt.Printf("upload data %v to %s: %v\n", fileName, targetUrl, err)
  158. return false
  159. }
  160. if uploadResult.Error != "" {
  161. fmt.Printf("upload %v to %s result: %v\n", fileName, targetUrl, uploadResult.Error)
  162. return false
  163. }
  164. fmt.Printf("uploaded %s to %s\n", fileName, targetUrl)
  165. chunks = append(chunks, &filer_pb.FileChunk{
  166. FileId: assignResult.Fid,
  167. Offset: 0,
  168. Size: uint64(uploadResult.Size),
  169. Mtime: time.Now().UnixNano(),
  170. })
  171. fmt.Printf("copied %s => http://%s%s%s\n", fileName, filerAddress, urlFolder, fileName)
  172. }
  173. if err := withFilerClient(filerGrpcAddress, func(client filer_pb.SeaweedFilerClient) error {
  174. request := &filer_pb.CreateEntryRequest{
  175. Directory: urlFolder,
  176. Entry: &filer_pb.Entry{
  177. Name: fileName,
  178. Attributes: &filer_pb.FuseAttributes{
  179. Crtime: time.Now().Unix(),
  180. Mtime: time.Now().Unix(),
  181. Gid: uint32(os.Getgid()),
  182. Uid: uint32(os.Getuid()),
  183. FileSize: uint64(fi.Size()),
  184. FileMode: uint32(fi.Mode()),
  185. Mime: mimeType,
  186. Replication: *copy.replication,
  187. Collection: *copy.collection,
  188. TtlSec: int32(util.ParseInt(*copy.ttl, 0)),
  189. },
  190. Chunks: chunks,
  191. },
  192. }
  193. if _, err := client.CreateEntry(context.Background(), request); err != nil {
  194. return fmt.Errorf("update fh: %v", err)
  195. }
  196. return nil
  197. }); err != nil {
  198. fmt.Printf("upload data %v to http://%s%s%s: %v\n", fileName, filerAddress, urlFolder, fileName, err)
  199. return false
  200. }
  201. return true
  202. }
  203. func uploadFileInChunks(filerAddress, filerGrpcAddress string, urlFolder string, f *os.File, fi os.FileInfo, chunkCount int, chunkSize int64) bool {
  204. fileName := filepath.Base(f.Name())
  205. mimeType := detectMimeType(f)
  206. var chunks []*filer_pb.FileChunk
  207. for i := int64(0); i < int64(chunkCount); i++ {
  208. // assign a volume
  209. assignResult, err := operation.Assign(*copy.master, &operation.VolumeAssignRequest{
  210. Count: 1,
  211. Replication: *copy.replication,
  212. Collection: *copy.collection,
  213. Ttl: *copy.ttl,
  214. })
  215. if err != nil {
  216. fmt.Printf("Failed to assign from %s: %v\n", *copy.master, err)
  217. }
  218. targetUrl := "http://" + assignResult.Url + "/" + assignResult.Fid
  219. uploadResult, err := operation.Upload(targetUrl,
  220. fileName+"-"+strconv.FormatInt(i+1, 10),
  221. io.LimitReader(f, chunkSize),
  222. false, "application/octet-stream", nil, "")
  223. if err != nil {
  224. fmt.Printf("upload data %v to %s: %v\n", fileName, targetUrl, err)
  225. return false
  226. }
  227. if uploadResult.Error != "" {
  228. fmt.Printf("upload %v to %s result: %v\n", fileName, targetUrl, uploadResult.Error)
  229. return false
  230. }
  231. chunks = append(chunks, &filer_pb.FileChunk{
  232. FileId: assignResult.Fid,
  233. Offset: i * chunkSize,
  234. Size: uint64(uploadResult.Size),
  235. Mtime: time.Now().UnixNano(),
  236. })
  237. fmt.Printf("uploaded %s-%d to %s [%d,%d)\n", fileName, i+1, targetUrl, i*chunkSize, i*chunkSize+int64(uploadResult.Size))
  238. }
  239. if err := withFilerClient(filerGrpcAddress, func(client filer_pb.SeaweedFilerClient) error {
  240. request := &filer_pb.CreateEntryRequest{
  241. Directory: urlFolder,
  242. Entry: &filer_pb.Entry{
  243. Name: fileName,
  244. Attributes: &filer_pb.FuseAttributes{
  245. Crtime: time.Now().Unix(),
  246. Mtime: time.Now().Unix(),
  247. Gid: uint32(os.Getgid()),
  248. Uid: uint32(os.Getuid()),
  249. FileSize: uint64(fi.Size()),
  250. FileMode: uint32(fi.Mode()),
  251. Mime: mimeType,
  252. Replication: *copy.replication,
  253. Collection: *copy.collection,
  254. TtlSec: int32(util.ParseInt(*copy.ttl, 0)),
  255. },
  256. Chunks: chunks,
  257. },
  258. }
  259. if _, err := client.CreateEntry(context.Background(), request); err != nil {
  260. return fmt.Errorf("update fh: %v", err)
  261. }
  262. return nil
  263. }); err != nil {
  264. fmt.Printf("upload data %v to http://%s%s%s: %v\n", fileName, filerAddress, urlFolder, fileName, err)
  265. return false
  266. }
  267. fmt.Printf("copied %s => http://%s%s%s\n", fileName, filerAddress, urlFolder, fileName)
  268. return true
  269. }
  270. func isGzipped(filename string) bool {
  271. return strings.ToLower(path.Ext(filename)) == ".gz"
  272. }
  273. func detectMimeType(f *os.File) string {
  274. head := make([]byte, 512)
  275. f.Seek(0, 0)
  276. n, err := f.Read(head)
  277. if err == io.EOF {
  278. return ""
  279. }
  280. if err != nil {
  281. fmt.Printf("read head of %v: %v\n", f.Name(), err)
  282. return "application/octet-stream"
  283. }
  284. f.Seek(0, 0)
  285. mimeType := http.DetectContentType(head[:n])
  286. return mimeType
  287. }
  288. func withFilerClient(filerAddress string, fn func(filer_pb.SeaweedFilerClient) error) error {
  289. grpcConnection, err := util.GrpcDial(filerAddress)
  290. if err != nil {
  291. return fmt.Errorf("fail to dial %s: %v", filerAddress, err)
  292. }
  293. defer grpcConnection.Close()
  294. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  295. return fn(client)
  296. }