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.

508 lines
15 KiB

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