filer_copy.go 17 KB

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