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.

578 lines
17 KiB

5 years ago
4 years ago
7 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package command
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "google.golang.org/grpc"
  17. "github.com/chrislusf/seaweedfs/weed/util/grace"
  18. "github.com/chrislusf/seaweedfs/weed/operation"
  19. "github.com/chrislusf/seaweedfs/weed/pb"
  20. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  21. "github.com/chrislusf/seaweedfs/weed/security"
  22. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  23. "github.com/chrislusf/seaweedfs/weed/util"
  24. "github.com/chrislusf/seaweedfs/weed/wdclient"
  25. )
  26. var (
  27. copy CopyOptions
  28. waitGroup sync.WaitGroup
  29. )
  30. type CopyOptions struct {
  31. include *string
  32. replication *string
  33. collection *string
  34. ttl *string
  35. diskType *string
  36. maxMB *int
  37. masterClient *wdclient.MasterClient
  38. concurrenctFiles *int
  39. concurrenctChunks *int
  40. grpcDialOption grpc.DialOption
  41. masters []string
  42. cipher bool
  43. ttlSec int32
  44. checkSize *bool
  45. verbose *bool
  46. }
  47. func init() {
  48. cmdCopy.Run = runCopy // break init cycle
  49. cmdCopy.IsDebug = cmdCopy.Flag.Bool("debug", false, "verbose debug information")
  50. copy.include = cmdCopy.Flag.String("include", "", "pattens of files to copy, e.g., *.pdf, *.html, ab?d.txt, works together with -dir")
  51. copy.replication = cmdCopy.Flag.String("replication", "", "replication type")
  52. copy.collection = cmdCopy.Flag.String("collection", "", "optional collection name")
  53. copy.ttl = cmdCopy.Flag.String("ttl", "", "time to live, e.g.: 1m, 1h, 1d, 1M, 1y")
  54. copy.diskType = cmdCopy.Flag.String("disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
  55. copy.maxMB = cmdCopy.Flag.Int("maxMB", 4, "split files larger than the limit")
  56. copy.concurrenctFiles = cmdCopy.Flag.Int("c", 8, "concurrent file copy goroutines")
  57. copy.concurrenctChunks = cmdCopy.Flag.Int("concurrentChunks", 8, "concurrent chunk copy goroutines for each file")
  58. copy.checkSize = cmdCopy.Flag.Bool("check.size", false, "copy when the target file size is different from the source file")
  59. copy.verbose = cmdCopy.Flag.Bool("verbose", false, "print out details during copying")
  60. }
  61. var cmdCopy = &Command{
  62. UsageLine: "filer.copy file_or_dir1 [file_or_dir2 file_or_dir3] http://localhost:8888/path/to/a/folder/",
  63. Short: "copy one or a list of files to a filer folder",
  64. Long: `copy one or a list of files, or batch copy one whole folder recursively, to a filer folder
  65. It can copy one or a list of files or folders.
  66. If copying a whole folder recursively:
  67. All files under the folder and subfolders will be copyed.
  68. Optional parameter "-include" allows you to specify the file name patterns.
  69. If "maxMB" is set to a positive number, files larger than it would be split into chunks.
  70. `,
  71. }
  72. func runCopy(cmd *Command, args []string) bool {
  73. util.LoadConfiguration("security", false)
  74. if len(args) <= 1 {
  75. return false
  76. }
  77. filerDestination := args[len(args)-1]
  78. fileOrDirs := args[0 : len(args)-1]
  79. filerUrl, err := url.Parse(filerDestination)
  80. if err != nil {
  81. fmt.Printf("The last argument should be a URL on filer: %v\n", err)
  82. return false
  83. }
  84. urlPath := filerUrl.Path
  85. if !strings.HasSuffix(urlPath, "/") {
  86. fmt.Printf("The last argument should be a folder and end with \"/\"\n")
  87. return false
  88. }
  89. if filerUrl.Port() == "" {
  90. fmt.Printf("The filer port should be specified.\n")
  91. return false
  92. }
  93. filerPort, parseErr := strconv.ParseUint(filerUrl.Port(), 10, 64)
  94. if parseErr != nil {
  95. fmt.Printf("The filer port parse error: %v\n", parseErr)
  96. return false
  97. }
  98. filerGrpcPort := filerPort + 10000
  99. filerGrpcAddress := fmt.Sprintf("%s:%d", filerUrl.Hostname(), filerGrpcPort)
  100. copy.grpcDialOption = security.LoadClientTLS(util.GetViper(), "grpc.client")
  101. masters, collection, replication, dirBuckets, maxMB, cipher, err := readFilerConfiguration(copy.grpcDialOption, filerGrpcAddress)
  102. if err != nil {
  103. fmt.Printf("read from filer %s: %v\n", filerGrpcAddress, err)
  104. return false
  105. }
  106. if strings.HasPrefix(urlPath, dirBuckets+"/") {
  107. restPath := urlPath[len(dirBuckets)+1:]
  108. if strings.Index(restPath, "/") > 0 {
  109. expectedBucket := restPath[:strings.Index(restPath, "/")]
  110. if *copy.collection == "" {
  111. *copy.collection = expectedBucket
  112. } else if *copy.collection != expectedBucket {
  113. fmt.Printf("destination %s uses collection \"%s\": unexpected collection \"%v\"\n", urlPath, expectedBucket, *copy.collection)
  114. return true
  115. }
  116. }
  117. }
  118. if *copy.collection == "" {
  119. *copy.collection = collection
  120. }
  121. if *copy.replication == "" {
  122. *copy.replication = replication
  123. }
  124. if *copy.maxMB == 0 {
  125. *copy.maxMB = int(maxMB)
  126. }
  127. copy.masters = masters
  128. copy.cipher = cipher
  129. ttl, err := needle.ReadTTL(*copy.ttl)
  130. if err != nil {
  131. fmt.Printf("parsing ttl %s: %v\n", *copy.ttl, err)
  132. return false
  133. }
  134. copy.ttlSec = int32(ttl.Minutes()) * 60
  135. if *cmdCopy.IsDebug {
  136. grace.SetupProfiling("filer.copy.cpu.pprof", "filer.copy.mem.pprof")
  137. }
  138. fileCopyTaskChan := make(chan FileCopyTask, *copy.concurrenctFiles)
  139. go func() {
  140. defer close(fileCopyTaskChan)
  141. for _, fileOrDir := range fileOrDirs {
  142. if err := genFileCopyTask(fileOrDir, urlPath, fileCopyTaskChan); err != nil {
  143. fmt.Fprintf(os.Stderr, "genFileCopyTask : %v\n", err)
  144. break
  145. }
  146. }
  147. }()
  148. for i := 0; i < *copy.concurrenctFiles; i++ {
  149. waitGroup.Add(1)
  150. go func() {
  151. defer waitGroup.Done()
  152. worker := FileCopyWorker{
  153. options: &copy,
  154. filerHost: filerUrl.Host,
  155. filerGrpcAddress: filerGrpcAddress,
  156. }
  157. if err := worker.copyFiles(fileCopyTaskChan); err != nil {
  158. fmt.Fprintf(os.Stderr, "copy file error: %v\n", err)
  159. return
  160. }
  161. }()
  162. }
  163. waitGroup.Wait()
  164. return true
  165. }
  166. func readFilerConfiguration(grpcDialOption grpc.DialOption, filerGrpcAddress string) (masters []string, collection, replication string, dirBuckets string, maxMB uint32, cipher bool, err error) {
  167. err = pb.WithGrpcFilerClient(filerGrpcAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  168. resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
  169. if err != nil {
  170. return fmt.Errorf("get filer %s configuration: %v", filerGrpcAddress, err)
  171. }
  172. masters, collection, replication, maxMB = resp.Masters, resp.Collection, resp.Replication, resp.MaxMb
  173. dirBuckets = resp.DirBuckets
  174. cipher = resp.Cipher
  175. return nil
  176. })
  177. return
  178. }
  179. func genFileCopyTask(fileOrDir string, destPath string, fileCopyTaskChan chan FileCopyTask) error {
  180. fi, err := os.Stat(fileOrDir)
  181. if err != nil {
  182. fmt.Fprintf(os.Stderr, "Error: read file %s: %v\n", fileOrDir, err)
  183. return nil
  184. }
  185. mode := fi.Mode()
  186. uid, gid := util.GetFileUidGid(fi)
  187. fileCopyTaskChan <- FileCopyTask{
  188. sourceLocation: fileOrDir,
  189. destinationUrlPath: destPath,
  190. fileSize: fi.Size(),
  191. fileMode: fi.Mode(),
  192. uid: uid,
  193. gid: gid,
  194. }
  195. if mode.IsDir() {
  196. files, _ := ioutil.ReadDir(fileOrDir)
  197. for _, subFileOrDir := range files {
  198. cleanedDestDirectory := filepath.Clean(destPath + fi.Name())
  199. if err = genFileCopyTask(fileOrDir+"/"+subFileOrDir.Name(), cleanedDestDirectory+"/", fileCopyTaskChan); err != nil {
  200. return err
  201. }
  202. }
  203. }
  204. return nil
  205. }
  206. type FileCopyWorker struct {
  207. options *CopyOptions
  208. filerHost string
  209. filerGrpcAddress string
  210. }
  211. func (worker *FileCopyWorker) copyFiles(fileCopyTaskChan chan FileCopyTask) error {
  212. for task := range fileCopyTaskChan {
  213. if err := worker.doEachCopy(task); err != nil {
  214. return err
  215. }
  216. }
  217. return nil
  218. }
  219. type FileCopyTask struct {
  220. sourceLocation string
  221. destinationUrlPath string
  222. fileSize int64
  223. fileMode os.FileMode
  224. uid uint32
  225. gid uint32
  226. }
  227. func (worker *FileCopyWorker) doEachCopy(task FileCopyTask) error {
  228. f, err := os.Open(task.sourceLocation)
  229. if err != nil {
  230. fmt.Printf("Failed to open file %s: %v\n", task.sourceLocation, err)
  231. if _, ok := err.(*os.PathError); ok {
  232. fmt.Printf("skipping %s\n", task.sourceLocation)
  233. return nil
  234. }
  235. return err
  236. }
  237. defer f.Close()
  238. // this is a regular file
  239. if *worker.options.include != "" {
  240. if ok, _ := filepath.Match(*worker.options.include, filepath.Base(task.sourceLocation)); !ok {
  241. return nil
  242. }
  243. }
  244. if shouldCopy, err := worker.checkExistingFileFirst(task, f); err != nil {
  245. return fmt.Errorf("check existing file: %v", err)
  246. } else if !shouldCopy {
  247. if *worker.options.verbose {
  248. fmt.Printf("skipping copied file: %v\n", f.Name())
  249. }
  250. return nil
  251. }
  252. // find the chunk count
  253. chunkSize := int64(*worker.options.maxMB * 1024 * 1024)
  254. chunkCount := 1
  255. if chunkSize > 0 && task.fileSize > chunkSize {
  256. chunkCount = int(task.fileSize/chunkSize) + 1
  257. }
  258. if chunkCount == 1 {
  259. return worker.uploadFileAsOne(task, f)
  260. }
  261. return worker.uploadFileInChunks(task, f, chunkCount, chunkSize)
  262. }
  263. func (worker *FileCopyWorker) checkExistingFileFirst(task FileCopyTask, f *os.File) (shouldCopy bool, err error) {
  264. shouldCopy = true
  265. if !*worker.options.checkSize {
  266. return
  267. }
  268. fileStat, err := f.Stat()
  269. if err != nil {
  270. shouldCopy = false
  271. return
  272. }
  273. err = pb.WithGrpcFilerClient(worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  274. request := &filer_pb.LookupDirectoryEntryRequest{
  275. Directory: task.destinationUrlPath,
  276. Name: filepath.Base(f.Name()),
  277. }
  278. resp, lookupErr := client.LookupDirectoryEntry(context.Background(), request)
  279. if lookupErr != nil {
  280. // mostly not found error
  281. return nil
  282. }
  283. if fileStat.Size() == int64(filer.FileSize(resp.Entry)) {
  284. shouldCopy = false
  285. }
  286. return nil
  287. })
  288. return
  289. }
  290. func (worker *FileCopyWorker) uploadFileAsOne(task FileCopyTask, f *os.File) error {
  291. // upload the file content
  292. fileName := filepath.Base(f.Name())
  293. var mimeType string
  294. var chunks []*filer_pb.FileChunk
  295. var assignResult *filer_pb.AssignVolumeResponse
  296. var assignError error
  297. if task.fileMode&os.ModeDir == 0 && task.fileSize > 0 {
  298. mimeType = detectMimeType(f)
  299. data, err := ioutil.ReadAll(f)
  300. if err != nil {
  301. return err
  302. }
  303. // assign a volume
  304. err = util.Retry("assignVolume", func() error {
  305. return pb.WithGrpcFilerClient(worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  306. request := &filer_pb.AssignVolumeRequest{
  307. Count: 1,
  308. Replication: *worker.options.replication,
  309. Collection: *worker.options.collection,
  310. TtlSec: worker.options.ttlSec,
  311. DiskType: *worker.options.diskType,
  312. Path: task.destinationUrlPath,
  313. }
  314. assignResult, assignError = client.AssignVolume(context.Background(), request)
  315. if assignError != nil {
  316. return fmt.Errorf("assign volume failure %v: %v", request, assignError)
  317. }
  318. if assignResult.Error != "" {
  319. return fmt.Errorf("assign volume failure %v: %v", request, assignResult.Error)
  320. }
  321. return nil
  322. })
  323. })
  324. if err != nil {
  325. return fmt.Errorf("Failed to assign from %v: %v\n", worker.options.masters, err)
  326. }
  327. targetUrl := "http://" + assignResult.Url + "/" + assignResult.FileId
  328. uploadResult, err := operation.UploadData(targetUrl, fileName, worker.options.cipher, data, false, mimeType, nil, security.EncodedJwt(assignResult.Auth))
  329. if err != nil {
  330. return fmt.Errorf("upload data %v to %s: %v\n", fileName, targetUrl, err)
  331. }
  332. if uploadResult.Error != "" {
  333. return fmt.Errorf("upload %v to %s result: %v\n", fileName, targetUrl, uploadResult.Error)
  334. }
  335. if *worker.options.verbose {
  336. fmt.Printf("uploaded %s to %s\n", fileName, targetUrl)
  337. }
  338. chunks = append(chunks, uploadResult.ToPbFileChunk(assignResult.FileId, 0))
  339. fmt.Printf("copied %s => http://%s%s%s\n", f.Name(), worker.filerHost, task.destinationUrlPath, fileName)
  340. }
  341. if err := pb.WithGrpcFilerClient(worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  342. request := &filer_pb.CreateEntryRequest{
  343. Directory: task.destinationUrlPath,
  344. Entry: &filer_pb.Entry{
  345. Name: fileName,
  346. Attributes: &filer_pb.FuseAttributes{
  347. Crtime: time.Now().Unix(),
  348. Mtime: time.Now().Unix(),
  349. Gid: task.gid,
  350. Uid: task.uid,
  351. FileSize: uint64(task.fileSize),
  352. FileMode: uint32(task.fileMode),
  353. Mime: mimeType,
  354. Replication: *worker.options.replication,
  355. Collection: *worker.options.collection,
  356. TtlSec: worker.options.ttlSec,
  357. },
  358. Chunks: chunks,
  359. },
  360. }
  361. if err := filer_pb.CreateEntry(client, request); err != nil {
  362. return fmt.Errorf("update fh: %v", err)
  363. }
  364. return nil
  365. }); err != nil {
  366. return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerHost, task.destinationUrlPath, fileName, err)
  367. }
  368. return nil
  369. }
  370. func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File, chunkCount int, chunkSize int64) error {
  371. fileName := filepath.Base(f.Name())
  372. mimeType := detectMimeType(f)
  373. chunksChan := make(chan *filer_pb.FileChunk, chunkCount)
  374. concurrentChunks := make(chan struct{}, *worker.options.concurrenctChunks)
  375. var wg sync.WaitGroup
  376. var uploadError error
  377. var collection, replication string
  378. fmt.Printf("uploading %s in %d chunks ...\n", fileName, chunkCount)
  379. for i := int64(0); i < int64(chunkCount) && uploadError == nil; i++ {
  380. wg.Add(1)
  381. concurrentChunks <- struct{}{}
  382. go func(i int64) {
  383. defer func() {
  384. wg.Done()
  385. <-concurrentChunks
  386. }()
  387. // assign a volume
  388. var assignResult *filer_pb.AssignVolumeResponse
  389. var assignError error
  390. err := util.Retry("assignVolume", func() error {
  391. return pb.WithGrpcFilerClient(worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  392. request := &filer_pb.AssignVolumeRequest{
  393. Count: 1,
  394. Replication: *worker.options.replication,
  395. Collection: *worker.options.collection,
  396. TtlSec: worker.options.ttlSec,
  397. DiskType: *worker.options.diskType,
  398. Path: task.destinationUrlPath + fileName,
  399. }
  400. assignResult, assignError = client.AssignVolume(context.Background(), request)
  401. if assignError != nil {
  402. return fmt.Errorf("assign volume failure %v: %v", request, assignError)
  403. }
  404. if assignResult.Error != "" {
  405. return fmt.Errorf("assign volume failure %v: %v", request, assignResult.Error)
  406. }
  407. return nil
  408. })
  409. })
  410. if err != nil {
  411. fmt.Printf("Failed to assign from %v: %v\n", worker.options.masters, err)
  412. }
  413. targetUrl := "http://" + assignResult.Url + "/" + assignResult.FileId
  414. if collection == "" {
  415. collection = assignResult.Collection
  416. }
  417. if replication == "" {
  418. replication = assignResult.Replication
  419. }
  420. uploadResult, err, _ := operation.Upload(targetUrl, fileName+"-"+strconv.FormatInt(i+1, 10), worker.options.cipher, io.NewSectionReader(f, i*chunkSize, chunkSize), false, "", nil, security.EncodedJwt(assignResult.Auth))
  421. if err != nil {
  422. uploadError = fmt.Errorf("upload data %v to %s: %v\n", fileName, targetUrl, err)
  423. return
  424. }
  425. if uploadResult.Error != "" {
  426. uploadError = fmt.Errorf("upload %v to %s result: %v\n", fileName, targetUrl, uploadResult.Error)
  427. return
  428. }
  429. chunksChan <- uploadResult.ToPbFileChunk(assignResult.FileId, i*chunkSize)
  430. fmt.Printf("uploaded %s-%d to %s [%d,%d)\n", fileName, i+1, targetUrl, i*chunkSize, i*chunkSize+int64(uploadResult.Size))
  431. }(i)
  432. }
  433. wg.Wait()
  434. close(chunksChan)
  435. var chunks []*filer_pb.FileChunk
  436. for chunk := range chunksChan {
  437. chunks = append(chunks, chunk)
  438. }
  439. if uploadError != nil {
  440. var fileIds []string
  441. for _, chunk := range chunks {
  442. fileIds = append(fileIds, chunk.FileId)
  443. }
  444. operation.DeleteFiles(func() string {
  445. return copy.masters[0]
  446. }, false, worker.options.grpcDialOption, fileIds)
  447. return uploadError
  448. }
  449. if err := pb.WithGrpcFilerClient(worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  450. request := &filer_pb.CreateEntryRequest{
  451. Directory: task.destinationUrlPath,
  452. Entry: &filer_pb.Entry{
  453. Name: fileName,
  454. Attributes: &filer_pb.FuseAttributes{
  455. Crtime: time.Now().Unix(),
  456. Mtime: time.Now().Unix(),
  457. Gid: task.gid,
  458. Uid: task.uid,
  459. FileSize: uint64(task.fileSize),
  460. FileMode: uint32(task.fileMode),
  461. Mime: mimeType,
  462. Replication: replication,
  463. Collection: collection,
  464. TtlSec: worker.options.ttlSec,
  465. },
  466. Chunks: chunks,
  467. },
  468. }
  469. if err := filer_pb.CreateEntry(client, request); err != nil {
  470. return fmt.Errorf("update fh: %v", err)
  471. }
  472. return nil
  473. }); err != nil {
  474. return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerHost, task.destinationUrlPath, fileName, err)
  475. }
  476. fmt.Printf("copied %s => http://%s%s%s\n", f.Name(), worker.filerHost, task.destinationUrlPath, fileName)
  477. return nil
  478. }
  479. func detectMimeType(f *os.File) string {
  480. head := make([]byte, 512)
  481. f.Seek(0, io.SeekStart)
  482. n, err := f.Read(head)
  483. if err == io.EOF {
  484. return ""
  485. }
  486. if err != nil {
  487. fmt.Printf("read head of %v: %v\n", f.Name(), err)
  488. return ""
  489. }
  490. f.Seek(0, io.SeekStart)
  491. mimeType := http.DetectContentType(head[:n])
  492. if mimeType == "application/octet-stream" {
  493. return ""
  494. }
  495. return mimeType
  496. }