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.

503 lines
15 KiB

7 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/filer_pb"
  18. "github.com/chrislusf/seaweedfs/weed/security"
  19. "github.com/chrislusf/seaweedfs/weed/util"
  20. "github.com/chrislusf/seaweedfs/weed/wdclient"
  21. )
  22. var (
  23. copy CopyOptions
  24. waitGroup sync.WaitGroup
  25. )
  26. type CopyOptions struct {
  27. include *string
  28. replication *string
  29. collection *string
  30. ttl *string
  31. maxMB *int
  32. masterClient *wdclient.MasterClient
  33. concurrenctFiles *int
  34. concurrenctChunks *int
  35. compressionLevel *int
  36. grpcDialOption grpc.DialOption
  37. masters []string
  38. }
  39. func init() {
  40. cmdCopy.Run = runCopy // break init cycle
  41. cmdCopy.IsDebug = cmdCopy.Flag.Bool("debug", false, "verbose debug information")
  42. copy.include = cmdCopy.Flag.String("include", "", "pattens of files to copy, e.g., *.pdf, *.html, ab?d.txt, works together with -dir")
  43. copy.replication = cmdCopy.Flag.String("replication", "", "replication type")
  44. copy.collection = cmdCopy.Flag.String("collection", "", "optional collection name")
  45. copy.ttl = cmdCopy.Flag.String("ttl", "", "time to live, e.g.: 1m, 1h, 1d, 1M, 1y")
  46. copy.maxMB = cmdCopy.Flag.Int("maxMB", 32, "split files larger than the limit")
  47. copy.concurrenctFiles = cmdCopy.Flag.Int("c", 8, "concurrent file copy goroutines")
  48. copy.concurrenctChunks = cmdCopy.Flag.Int("concurrentChunks", 8, "concurrent chunk copy goroutines for each file")
  49. copy.compressionLevel = cmdCopy.Flag.Int("compressionLevel", 9, "local file compression level 1 ~ 9")
  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. ctx := context.Background()
  92. masters, collection, replication, maxMB, err := readFilerConfiguration(ctx, copy.grpcDialOption, filerGrpcAddress)
  93. if err != nil {
  94. fmt.Printf("read from filer %s: %v\n", filerGrpcAddress, err)
  95. return false
  96. }
  97. if *copy.collection == "" {
  98. *copy.collection = collection
  99. }
  100. if *copy.replication == "" {
  101. *copy.replication = replication
  102. }
  103. if *copy.maxMB == 0 {
  104. *copy.maxMB = int(maxMB)
  105. }
  106. copy.masters = masters
  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(ctx, 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(ctx context.Context, grpcDialOption grpc.DialOption, filerGrpcAddress string) (masters []string, collection, replication string, maxMB uint32, err error) {
  139. err = withFilerClient(ctx, filerGrpcAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  140. resp, err := client.GetFilerConfiguration(ctx, &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. return nil
  146. })
  147. return
  148. }
  149. func genFileCopyTask(fileOrDir string, destPath string, fileCopyTaskChan chan FileCopyTask) error {
  150. fi, err := os.Stat(fileOrDir)
  151. if err != nil {
  152. fmt.Fprintf(os.Stderr, "Failed to get stat for file %s: %v\n", fileOrDir, err)
  153. return nil
  154. }
  155. mode := fi.Mode()
  156. if mode.IsDir() {
  157. files, _ := ioutil.ReadDir(fileOrDir)
  158. for _, subFileOrDir := range files {
  159. if err = genFileCopyTask(fileOrDir+"/"+subFileOrDir.Name(), destPath+fi.Name()+"/", fileCopyTaskChan); err != nil {
  160. return err
  161. }
  162. }
  163. return nil
  164. }
  165. uid, gid := util.GetFileUidGid(fi)
  166. fileCopyTaskChan <- FileCopyTask{
  167. sourceLocation: fileOrDir,
  168. destinationUrlPath: destPath,
  169. fileSize: fi.Size(),
  170. fileMode: fi.Mode(),
  171. uid: uid,
  172. gid: gid,
  173. }
  174. return nil
  175. }
  176. type FileCopyWorker struct {
  177. options *CopyOptions
  178. filerHost string
  179. filerGrpcAddress string
  180. }
  181. func (worker *FileCopyWorker) copyFiles(ctx context.Context, fileCopyTaskChan chan FileCopyTask) error {
  182. for task := range fileCopyTaskChan {
  183. if err := worker.doEachCopy(ctx, task); err != nil {
  184. return err
  185. }
  186. }
  187. return nil
  188. }
  189. type FileCopyTask struct {
  190. sourceLocation string
  191. destinationUrlPath string
  192. fileSize int64
  193. fileMode os.FileMode
  194. uid uint32
  195. gid uint32
  196. }
  197. func (worker *FileCopyWorker) doEachCopy(ctx context.Context, task FileCopyTask) error {
  198. f, err := os.Open(task.sourceLocation)
  199. if err != nil {
  200. fmt.Printf("Failed to open file %s: %v\n", task.sourceLocation, err)
  201. if _, ok := err.(*os.PathError); ok {
  202. fmt.Printf("skipping %s\n", task.sourceLocation)
  203. return nil
  204. }
  205. return err
  206. }
  207. defer f.Close()
  208. // this is a regular file
  209. if *worker.options.include != "" {
  210. if ok, _ := filepath.Match(*worker.options.include, filepath.Base(task.sourceLocation)); !ok {
  211. return nil
  212. }
  213. }
  214. // find the chunk count
  215. chunkSize := int64(*worker.options.maxMB * 1024 * 1024)
  216. chunkCount := 1
  217. if chunkSize > 0 && task.fileSize > chunkSize {
  218. chunkCount = int(task.fileSize/chunkSize) + 1
  219. }
  220. if chunkCount == 1 {
  221. return worker.uploadFileAsOne(ctx, task, f)
  222. }
  223. return worker.uploadFileInChunks(ctx, task, f, chunkCount, chunkSize)
  224. }
  225. func (worker *FileCopyWorker) uploadFileAsOne(ctx context.Context, task FileCopyTask, f *os.File) error {
  226. // upload the file content
  227. fileName := filepath.Base(f.Name())
  228. mimeType := detectMimeType(f)
  229. var chunks []*filer_pb.FileChunk
  230. var assignResult *filer_pb.AssignVolumeResponse
  231. var assignError error
  232. if task.fileSize > 0 {
  233. // assign a volume
  234. err := withFilerClient(ctx, worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  235. request := &filer_pb.AssignVolumeRequest{
  236. Count: 1,
  237. Replication: *worker.options.replication,
  238. Collection: *worker.options.collection,
  239. TtlSec: int32(util.ParseInt(*worker.options.ttl, 0)),
  240. ParentPath: task.destinationUrlPath,
  241. }
  242. assignResult, assignError = client.AssignVolume(ctx, request)
  243. if assignError != nil {
  244. return fmt.Errorf("assign volume failure %v: %v", request, assignError)
  245. }
  246. return nil
  247. })
  248. if err != nil {
  249. fmt.Printf("Failed to assign from %v: %v\n", worker.options.masters, err)
  250. }
  251. targetUrl := "http://" + assignResult.Url + "/" + assignResult.FileId
  252. uploadResult, err := operation.UploadWithLocalCompressionLevel(targetUrl, fileName, f, false, mimeType, nil, security.EncodedJwt(assignResult.Auth), *worker.options.compressionLevel)
  253. if err != nil {
  254. return fmt.Errorf("upload data %v to %s: %v\n", fileName, targetUrl, err)
  255. }
  256. if uploadResult.Error != "" {
  257. return fmt.Errorf("upload %v to %s result: %v\n", fileName, targetUrl, uploadResult.Error)
  258. }
  259. fmt.Printf("uploaded %s to %s\n", fileName, targetUrl)
  260. chunks = append(chunks, &filer_pb.FileChunk{
  261. FileId: assignResult.FileId,
  262. Offset: 0,
  263. Size: uint64(uploadResult.Size),
  264. Mtime: time.Now().UnixNano(),
  265. ETag: uploadResult.ETag,
  266. })
  267. fmt.Printf("copied %s => http://%s%s%s\n", fileName, worker.filerHost, task.destinationUrlPath, fileName)
  268. }
  269. if err := withFilerClient(ctx, worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  270. request := &filer_pb.CreateEntryRequest{
  271. Directory: task.destinationUrlPath,
  272. Entry: &filer_pb.Entry{
  273. Name: fileName,
  274. Attributes: &filer_pb.FuseAttributes{
  275. Crtime: time.Now().Unix(),
  276. Mtime: time.Now().Unix(),
  277. Gid: task.gid,
  278. Uid: task.uid,
  279. FileSize: uint64(task.fileSize),
  280. FileMode: uint32(task.fileMode),
  281. Mime: mimeType,
  282. Replication: *worker.options.replication,
  283. Collection: *worker.options.collection,
  284. TtlSec: int32(util.ParseInt(*worker.options.ttl, 0)),
  285. },
  286. Chunks: chunks,
  287. },
  288. }
  289. if err := filer_pb.CreateEntry(ctx, client, request); err != nil {
  290. return fmt.Errorf("update fh: %v", err)
  291. }
  292. return nil
  293. }); err != nil {
  294. return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerHost, task.destinationUrlPath, fileName, err)
  295. }
  296. return nil
  297. }
  298. func (worker *FileCopyWorker) uploadFileInChunks(ctx context.Context, task FileCopyTask, f *os.File, chunkCount int, chunkSize int64) error {
  299. fileName := filepath.Base(f.Name())
  300. mimeType := detectMimeType(f)
  301. chunksChan := make(chan *filer_pb.FileChunk, chunkCount)
  302. concurrentChunks := make(chan struct{}, *worker.options.concurrenctChunks)
  303. var wg sync.WaitGroup
  304. var uploadError error
  305. var collection, replication string
  306. fmt.Printf("uploading %s in %d chunks ...\n", fileName, chunkCount)
  307. for i := int64(0); i < int64(chunkCount) && uploadError == nil; i++ {
  308. wg.Add(1)
  309. concurrentChunks <- struct{}{}
  310. go func(i int64) {
  311. defer func() {
  312. wg.Done()
  313. <-concurrentChunks
  314. }()
  315. // assign a volume
  316. var assignResult *filer_pb.AssignVolumeResponse
  317. var assignError error
  318. err := withFilerClient(ctx, worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  319. request := &filer_pb.AssignVolumeRequest{
  320. Count: 1,
  321. Replication: *worker.options.replication,
  322. Collection: *worker.options.collection,
  323. TtlSec: int32(util.ParseInt(*worker.options.ttl, 0)),
  324. ParentPath: task.destinationUrlPath,
  325. }
  326. assignResult, assignError = client.AssignVolume(ctx, request)
  327. if assignError != nil {
  328. return fmt.Errorf("assign volume failure %v: %v", request, assignError)
  329. }
  330. return nil
  331. })
  332. if err != nil {
  333. fmt.Printf("Failed to assign from %v: %v\n", worker.options.masters, err)
  334. }
  335. if err != nil {
  336. fmt.Printf("Failed to assign from %v: %v\n", worker.options.masters, err)
  337. }
  338. targetUrl := "http://" + assignResult.Url + "/" + assignResult.FileId
  339. if collection == "" {
  340. collection = assignResult.Collection
  341. }
  342. if replication == "" {
  343. replication = assignResult.Replication
  344. }
  345. uploadResult, err := operation.Upload(targetUrl,
  346. fileName+"-"+strconv.FormatInt(i+1, 10),
  347. io.NewSectionReader(f, i*chunkSize, chunkSize),
  348. false, "", nil, security.EncodedJwt(assignResult.Auth))
  349. if err != nil {
  350. uploadError = fmt.Errorf("upload data %v to %s: %v\n", fileName, targetUrl, err)
  351. return
  352. }
  353. if uploadResult.Error != "" {
  354. uploadError = fmt.Errorf("upload %v to %s result: %v\n", fileName, targetUrl, uploadResult.Error)
  355. return
  356. }
  357. chunksChan <- &filer_pb.FileChunk{
  358. FileId: assignResult.FileId,
  359. Offset: i * chunkSize,
  360. Size: uint64(uploadResult.Size),
  361. Mtime: time.Now().UnixNano(),
  362. ETag: uploadResult.ETag,
  363. }
  364. fmt.Printf("uploaded %s-%d to %s [%d,%d)\n", fileName, i+1, targetUrl, i*chunkSize, i*chunkSize+int64(uploadResult.Size))
  365. }(i)
  366. }
  367. wg.Wait()
  368. close(chunksChan)
  369. var chunks []*filer_pb.FileChunk
  370. for chunk := range chunksChan {
  371. chunks = append(chunks, chunk)
  372. }
  373. if uploadError != nil {
  374. var fileIds []string
  375. for _, chunk := range chunks {
  376. fileIds = append(fileIds, chunk.FileId)
  377. }
  378. operation.DeleteFiles(copy.masters[0], worker.options.grpcDialOption, fileIds)
  379. return uploadError
  380. }
  381. if err := withFilerClient(ctx, worker.filerGrpcAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  382. request := &filer_pb.CreateEntryRequest{
  383. Directory: task.destinationUrlPath,
  384. Entry: &filer_pb.Entry{
  385. Name: fileName,
  386. Attributes: &filer_pb.FuseAttributes{
  387. Crtime: time.Now().Unix(),
  388. Mtime: time.Now().Unix(),
  389. Gid: task.gid,
  390. Uid: task.uid,
  391. FileSize: uint64(task.fileSize),
  392. FileMode: uint32(task.fileMode),
  393. Mime: mimeType,
  394. Replication: replication,
  395. Collection: collection,
  396. TtlSec: int32(util.ParseInt(*worker.options.ttl, 0)),
  397. },
  398. Chunks: chunks,
  399. },
  400. }
  401. if err := filer_pb.CreateEntry(ctx, client, request); err != nil {
  402. return fmt.Errorf("update fh: %v", err)
  403. }
  404. return nil
  405. }); err != nil {
  406. return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerHost, task.destinationUrlPath, fileName, err)
  407. }
  408. fmt.Printf("copied %s => http://%s%s%s\n", fileName, worker.filerHost, task.destinationUrlPath, fileName)
  409. return nil
  410. }
  411. func detectMimeType(f *os.File) string {
  412. head := make([]byte, 512)
  413. f.Seek(0, io.SeekStart)
  414. n, err := f.Read(head)
  415. if err == io.EOF {
  416. return ""
  417. }
  418. if err != nil {
  419. fmt.Printf("read head of %v: %v\n", f.Name(), err)
  420. return "application/octet-stream"
  421. }
  422. f.Seek(0, io.SeekStart)
  423. mimeType := http.DetectContentType(head[:n])
  424. return mimeType
  425. }
  426. func withFilerClient(ctx context.Context, filerAddress string, grpcDialOption grpc.DialOption, fn func(filer_pb.SeaweedFilerClient) error) error {
  427. return util.WithCachedGrpcClient(ctx, func(ctx context.Context, clientConn *grpc.ClientConn) error {
  428. client := filer_pb.NewSeaweedFilerClient(clientConn)
  429. return fn(client)
  430. }, filerAddress, grpcDialOption)
  431. }