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.

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