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.

413 lines
12 KiB

7 years ago
  1. package command
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/operation"
  6. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  7. "github.com/chrislusf/seaweedfs/weed/security"
  8. "github.com/chrislusf/seaweedfs/weed/server"
  9. "github.com/chrislusf/seaweedfs/weed/util"
  10. "github.com/chrislusf/seaweedfs/weed/wdclient"
  11. "github.com/spf13/viper"
  12. "google.golang.org/grpc"
  13. "io"
  14. "io/ioutil"
  15. "net/http"
  16. "net/url"
  17. "os"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. )
  24. var (
  25. copy CopyOptions
  26. waitGroup sync.WaitGroup
  27. )
  28. type CopyOptions struct {
  29. filerGrpcPort *int
  30. master *string
  31. include *string
  32. replication *string
  33. collection *string
  34. ttl *string
  35. maxMB *int
  36. grpcDialOption grpc.DialOption
  37. masterClient *wdclient.MasterClient
  38. concurrency *int
  39. }
  40. func init() {
  41. cmdCopy.Run = runCopy // break init cycle
  42. cmdCopy.IsDebug = cmdCopy.Flag.Bool("debug", false, "verbose debug information")
  43. copy.master = cmdCopy.Flag.String("master", "localhost:9333", "SeaweedFS master location")
  44. copy.include = cmdCopy.Flag.String("include", "", "pattens of files to copy, e.g., *.pdf, *.html, ab?d.txt, works together with -dir")
  45. copy.replication = cmdCopy.Flag.String("replication", "", "replication type")
  46. copy.collection = cmdCopy.Flag.String("collection", "", "optional collection name")
  47. copy.ttl = cmdCopy.Flag.String("ttl", "", "time to live, e.g.: 1m, 1h, 1d, 1M, 1y")
  48. copy.maxMB = cmdCopy.Flag.Int("maxMB", 32, "split files larger than the limit")
  49. copy.filerGrpcPort = cmdCopy.Flag.Int("filer.port.grpc", 0, "filer grpc server listen port, default to filer port + 10000")
  50. copy.concurrency = cmdCopy.Flag.Int("c", 8, "concurrent file copy goroutines")
  51. }
  52. var cmdCopy = &Command{
  53. UsageLine: "filer.copy file_or_dir1 [file_or_dir2 file_or_dir3] http://localhost:8888/path/to/a/folder/",
  54. Short: "copy one or a list of files to a filer folder",
  55. Long: `copy one or a list of files, or batch copy one whole folder recursively, to a filer folder
  56. It can copy one or a list of files or folders.
  57. If copying a whole folder recursively:
  58. All files under the folder and subfolders will be copyed.
  59. Optional parameter "-include" allows you to specify the file name patterns.
  60. If "maxMB" is set to a positive number, files larger than it would be split into chunks.
  61. `,
  62. }
  63. func runCopy(cmd *Command, args []string) bool {
  64. weed_server.LoadConfiguration("security", false)
  65. if len(args) <= 1 {
  66. return false
  67. }
  68. filerDestination := args[len(args)-1]
  69. fileOrDirs := args[0 : len(args)-1]
  70. filerUrl, err := url.Parse(filerDestination)
  71. if err != nil {
  72. fmt.Printf("The last argument should be a URL on filer: %v\n", err)
  73. return false
  74. }
  75. urlPath := filerUrl.Path
  76. if !strings.HasSuffix(urlPath, "/") {
  77. fmt.Printf("The last argument should be a folder and end with \"/\": %v\n", err)
  78. return false
  79. }
  80. if filerUrl.Port() == "" {
  81. fmt.Printf("The filer port should be specified.\n")
  82. return false
  83. }
  84. filerPort, parseErr := strconv.ParseUint(filerUrl.Port(), 10, 64)
  85. if parseErr != nil {
  86. fmt.Printf("The filer port parse error: %v\n", parseErr)
  87. return false
  88. }
  89. filerGrpcPort := filerPort + 10000
  90. if *copy.filerGrpcPort != 0 {
  91. filerGrpcPort = uint64(*copy.filerGrpcPort)
  92. }
  93. filerGrpcAddress := fmt.Sprintf("%s:%d", filerUrl.Hostname(), filerGrpcPort)
  94. copy.grpcDialOption = security.LoadClientTLS(viper.Sub("grpc"), "client")
  95. copy.masterClient = wdclient.NewMasterClient(context.Background(), copy.grpcDialOption, "client", strings.Split(*copy.master, ","))
  96. go copy.masterClient.KeepConnectedToMaster()
  97. copy.masterClient.WaitUntilConnected()
  98. if *cmdCopy.IsDebug {
  99. util.SetupProfiling("filer.copy.cpu.pprof", "filer.copy.mem.pprof")
  100. }
  101. fileCopyTaskChan := make(chan FileCopyTask, *copy.concurrency)
  102. ctx := context.Background()
  103. go func() {
  104. defer close(fileCopyTaskChan)
  105. for _, fileOrDir := range fileOrDirs {
  106. if err := genFileCopyTask(fileOrDir, urlPath, fileCopyTaskChan); err != nil {
  107. fmt.Fprintf(os.Stderr, "gen file list error: %v\n", err)
  108. break
  109. }
  110. }
  111. }()
  112. for i := 0; i < *copy.concurrency; i++ {
  113. waitGroup.Add(1)
  114. go func() {
  115. defer waitGroup.Done()
  116. worker := FileCopyWorker{
  117. options: &copy,
  118. filerHost: filerUrl.Host,
  119. filerGrpcAddress: filerGrpcAddress,
  120. }
  121. if err := worker.copyFiles(ctx, fileCopyTaskChan); err != nil {
  122. fmt.Fprintf(os.Stderr, "copy file error: %v\n", err)
  123. return
  124. }
  125. }()
  126. }
  127. waitGroup.Wait()
  128. return true
  129. }
  130. func genFileCopyTask(fileOrDir string, destPath string, fileCopyTaskChan chan FileCopyTask) error {
  131. fi, err := os.Stat(fileOrDir)
  132. if err != nil {
  133. fmt.Fprintf(os.Stderr, "Failed to get stat for file %s: %v\n", fileOrDir, err)
  134. return nil
  135. }
  136. mode := fi.Mode()
  137. if mode.IsDir() {
  138. files, _ := ioutil.ReadDir(fileOrDir)
  139. for _, subFileOrDir := range files {
  140. if err = genFileCopyTask(fileOrDir+"/"+subFileOrDir.Name(), destPath+fi.Name()+"/", fileCopyTaskChan); err != nil {
  141. return err
  142. }
  143. }
  144. return nil
  145. }
  146. fileCopyTaskChan <- FileCopyTask{
  147. sourceLocation: fileOrDir,
  148. destinationUrlPath: destPath,
  149. fileSize: fi.Size(),
  150. fileMode: fi.Mode(),
  151. }
  152. return nil
  153. }
  154. type FileCopyWorker struct {
  155. options *CopyOptions
  156. filerHost string
  157. filerGrpcAddress string
  158. }
  159. func (worker *FileCopyWorker) copyFiles(ctx context.Context, fileCopyTaskChan chan FileCopyTask) error {
  160. for task := range fileCopyTaskChan {
  161. if err := worker.doEachCopy(ctx, task); err != nil {
  162. return err
  163. }
  164. }
  165. return nil
  166. }
  167. type FileCopyTask struct {
  168. sourceLocation string
  169. destinationUrlPath string
  170. fileSize int64
  171. fileMode os.FileMode
  172. }
  173. func (worker *FileCopyWorker) doEachCopy(ctx context.Context, task FileCopyTask) error {
  174. f, err := os.Open(task.sourceLocation)
  175. if err != nil {
  176. fmt.Printf("Failed to open file %s: %v\n", task.sourceLocation, err)
  177. if _, ok := err.(*os.PathError); ok {
  178. fmt.Printf("skipping %s\n", task.sourceLocation)
  179. return nil
  180. }
  181. return err
  182. }
  183. defer f.Close()
  184. // this is a regular file
  185. if *worker.options.include != "" {
  186. if ok, _ := filepath.Match(*worker.options.include, filepath.Base(task.sourceLocation)); !ok {
  187. return nil
  188. }
  189. }
  190. // find the chunk count
  191. chunkSize := int64(*worker.options.maxMB * 1024 * 1024)
  192. chunkCount := 1
  193. if chunkSize > 0 && task.fileSize > chunkSize {
  194. chunkCount = int(task.fileSize/chunkSize) + 1
  195. }
  196. if chunkCount == 1 {
  197. return worker.uploadFileAsOne(ctx, task, f)
  198. }
  199. return worker.uploadFileInChunks(ctx, task, f, chunkCount, chunkSize)
  200. }
  201. func (worker *FileCopyWorker) uploadFileAsOne(ctx context.Context, task FileCopyTask, f *os.File) error {
  202. // upload the file content
  203. fileName := filepath.Base(f.Name())
  204. mimeType := detectMimeType(f)
  205. var chunks []*filer_pb.FileChunk
  206. if task.fileSize > 0 {
  207. // assign a volume
  208. assignResult, err := operation.Assign(worker.options.masterClient.GetMaster(), worker.options.grpcDialOption, &operation.VolumeAssignRequest{
  209. Count: 1,
  210. Replication: *worker.options.replication,
  211. Collection: *worker.options.collection,
  212. Ttl: *worker.options.ttl,
  213. })
  214. if err != nil {
  215. fmt.Printf("Failed to assign from %s: %v\n", *worker.options.master, err)
  216. }
  217. targetUrl := "http://" + assignResult.Url + "/" + assignResult.Fid
  218. uploadResult, err := operation.Upload(targetUrl, fileName, f, false, mimeType, nil, assignResult.Auth)
  219. if err != nil {
  220. return fmt.Errorf("upload data %v to %s: %v\n", fileName, targetUrl, err)
  221. }
  222. if uploadResult.Error != "" {
  223. return fmt.Errorf("upload %v to %s result: %v\n", fileName, targetUrl, uploadResult.Error)
  224. }
  225. fmt.Printf("uploaded %s to %s\n", fileName, targetUrl)
  226. chunks = append(chunks, &filer_pb.FileChunk{
  227. FileId: assignResult.Fid,
  228. Offset: 0,
  229. Size: uint64(uploadResult.Size),
  230. Mtime: time.Now().UnixNano(),
  231. ETag: uploadResult.ETag,
  232. })
  233. fmt.Printf("copied %s => http://%s%s%s\n", fileName, worker.filerHost, task.destinationUrlPath, fileName)
  234. }
  235. if err := withFilerClient(ctx, worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  236. request := &filer_pb.CreateEntryRequest{
  237. Directory: task.destinationUrlPath,
  238. Entry: &filer_pb.Entry{
  239. Name: fileName,
  240. Attributes: &filer_pb.FuseAttributes{
  241. Crtime: time.Now().Unix(),
  242. Mtime: time.Now().Unix(),
  243. Gid: uint32(os.Getgid()),
  244. Uid: uint32(os.Getuid()),
  245. FileSize: uint64(task.fileSize),
  246. FileMode: uint32(task.fileMode),
  247. Mime: mimeType,
  248. Replication: *worker.options.replication,
  249. Collection: *worker.options.collection,
  250. TtlSec: int32(util.ParseInt(*worker.options.ttl, 0)),
  251. },
  252. Chunks: chunks,
  253. },
  254. }
  255. if _, err := client.CreateEntry(ctx, request); err != nil {
  256. return fmt.Errorf("update fh: %v", err)
  257. }
  258. return nil
  259. }); err != nil {
  260. return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerHost, task.destinationUrlPath, fileName, err)
  261. }
  262. return nil
  263. }
  264. func (worker *FileCopyWorker) uploadFileInChunks(ctx context.Context, task FileCopyTask, f *os.File, chunkCount int, chunkSize int64) error {
  265. fileName := filepath.Base(f.Name())
  266. mimeType := detectMimeType(f)
  267. var chunks []*filer_pb.FileChunk
  268. for i := int64(0); i < int64(chunkCount); i++ {
  269. // assign a volume
  270. assignResult, err := operation.Assign(worker.options.masterClient.GetMaster(), worker.options.grpcDialOption, &operation.VolumeAssignRequest{
  271. Count: 1,
  272. Replication: *worker.options.replication,
  273. Collection: *worker.options.collection,
  274. Ttl: *worker.options.ttl,
  275. })
  276. if err != nil {
  277. fmt.Printf("Failed to assign from %s: %v\n", *worker.options.master, err)
  278. }
  279. targetUrl := "http://" + assignResult.Url + "/" + assignResult.Fid
  280. uploadResult, err := operation.Upload(targetUrl,
  281. fileName+"-"+strconv.FormatInt(i+1, 10),
  282. io.LimitReader(f, chunkSize),
  283. false, "application/octet-stream", nil, assignResult.Auth)
  284. if err != nil {
  285. return fmt.Errorf("upload data %v to %s: %v\n", fileName, targetUrl, err)
  286. }
  287. if uploadResult.Error != "" {
  288. return fmt.Errorf("upload %v to %s result: %v\n", fileName, targetUrl, uploadResult.Error)
  289. }
  290. chunks = append(chunks, &filer_pb.FileChunk{
  291. FileId: assignResult.Fid,
  292. Offset: i * chunkSize,
  293. Size: uint64(uploadResult.Size),
  294. Mtime: time.Now().UnixNano(),
  295. ETag: uploadResult.ETag,
  296. })
  297. fmt.Printf("uploaded %s-%d to %s [%d,%d)\n", fileName, i+1, targetUrl, i*chunkSize, i*chunkSize+int64(uploadResult.Size))
  298. }
  299. if err := withFilerClient(ctx, worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  300. request := &filer_pb.CreateEntryRequest{
  301. Directory: task.destinationUrlPath,
  302. Entry: &filer_pb.Entry{
  303. Name: fileName,
  304. Attributes: &filer_pb.FuseAttributes{
  305. Crtime: time.Now().Unix(),
  306. Mtime: time.Now().Unix(),
  307. Gid: uint32(os.Getgid()),
  308. Uid: uint32(os.Getuid()),
  309. FileSize: uint64(task.fileSize),
  310. FileMode: uint32(task.fileMode),
  311. Mime: mimeType,
  312. Replication: *worker.options.replication,
  313. Collection: *worker.options.collection,
  314. TtlSec: int32(util.ParseInt(*worker.options.ttl, 0)),
  315. },
  316. Chunks: chunks,
  317. },
  318. }
  319. if _, err := client.CreateEntry(ctx, request); err != nil {
  320. return fmt.Errorf("update fh: %v", err)
  321. }
  322. return nil
  323. }); err != nil {
  324. return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerHost, task.destinationUrlPath, fileName, err)
  325. }
  326. fmt.Printf("copied %s => http://%s%s%s\n", fileName, worker.filerHost, task.destinationUrlPath, fileName)
  327. return nil
  328. }
  329. func detectMimeType(f *os.File) string {
  330. head := make([]byte, 512)
  331. f.Seek(0, io.SeekStart)
  332. n, err := f.Read(head)
  333. if err == io.EOF {
  334. return ""
  335. }
  336. if err != nil {
  337. fmt.Printf("read head of %v: %v\n", f.Name(), err)
  338. return "application/octet-stream"
  339. }
  340. f.Seek(0, io.SeekStart)
  341. mimeType := http.DetectContentType(head[:n])
  342. return mimeType
  343. }
  344. func withFilerClient(ctx context.Context, filerAddress string, grpcDialOption grpc.DialOption, fn func(filer_pb.SeaweedFilerClient) error) error {
  345. return util.WithCachedGrpcClient(ctx, func(clientConn *grpc.ClientConn) error {
  346. client := filer_pb.NewSeaweedFilerClient(clientConn)
  347. return fn(client)
  348. }, filerAddress, grpcDialOption)
  349. }