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.

593 lines
17 KiB

1 year ago
1 year ago
3 years ago
7 years ago
4 years ago
4 years ago
4 years ago
2 years ago
2 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
  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. "github.com/seaweedfs/seaweedfs/weed/wdclient"
  23. )
  24. var (
  25. copy CopyOptions
  26. waitGroup sync.WaitGroup
  27. )
  28. type CopyOptions struct {
  29. include *string
  30. replication *string
  31. collection *string
  32. ttl *string
  33. diskType *string
  34. maxMB *int
  35. masterClient *wdclient.MasterClient
  36. concurrentFiles *int
  37. concurrentChunks *int
  38. grpcDialOption grpc.DialOption
  39. masters []string
  40. cipher bool
  41. ttlSec int32
  42. checkSize *bool
  43. verbose *bool
  44. volumeServerAccess *string
  45. }
  46. func init() {
  47. cmdFilerCopy.Run = runCopy // break init cycle
  48. cmdFilerCopy.IsDebug = cmdFilerCopy.Flag.Bool("debug", false, "verbose debug information")
  49. copy.include = cmdFilerCopy.Flag.String("include", "", "pattens of files to copy, e.g., *.pdf, *.html, ab?d.txt, works together with -dir")
  50. copy.replication = cmdFilerCopy.Flag.String("replication", "", "replication type")
  51. copy.collection = cmdFilerCopy.Flag.String("collection", "", "optional collection name")
  52. copy.ttl = cmdFilerCopy.Flag.String("ttl", "", "time to live, e.g.: 1m, 1h, 1d, 1M, 1y")
  53. copy.diskType = cmdFilerCopy.Flag.String("disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
  54. copy.maxMB = cmdFilerCopy.Flag.Int("maxMB", 4, "split files larger than the limit")
  55. copy.concurrentFiles = cmdFilerCopy.Flag.Int("c", 8, "concurrent file copy goroutines")
  56. copy.concurrentChunks = cmdFilerCopy.Flag.Int("concurrentChunks", 8, "concurrent chunk copy goroutines for each file")
  57. copy.checkSize = cmdFilerCopy.Flag.Bool("check.size", false, "copy when the target file size is different from the source file")
  58. copy.verbose = cmdFilerCopy.Flag.Bool("verbose", false, "print out details during copying")
  59. copy.volumeServerAccess = cmdFilerCopy.Flag.String("volumeServerAccess", "direct", "access volume servers by [direct|publicUrl]")
  60. }
  61. var cmdFilerCopy = &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 sub folders will be copied.
  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. filerAddress, urlPath, err := pb.ParseUrl(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. if !strings.HasSuffix(urlPath, "/") {
  85. fmt.Printf("The last argument should be a folder and end with \"/\"\n")
  86. return false
  87. }
  88. copy.grpcDialOption = security.LoadClientTLS(util.GetViper(), "grpc.client")
  89. masters, collection, replication, dirBuckets, maxMB, cipher, err := readFilerConfiguration(copy.grpcDialOption, filerAddress)
  90. if err != nil {
  91. fmt.Printf("read from filer %s: %v\n", filerAddress, err)
  92. return false
  93. }
  94. if strings.HasPrefix(urlPath, dirBuckets+"/") {
  95. restPath := urlPath[len(dirBuckets)+1:]
  96. if strings.Index(restPath, "/") > 0 {
  97. expectedBucket := restPath[:strings.Index(restPath, "/")]
  98. if *copy.collection == "" {
  99. *copy.collection = expectedBucket
  100. } else if *copy.collection != expectedBucket {
  101. fmt.Printf("destination %s uses collection \"%s\": unexpected collection \"%v\"\n", urlPath, expectedBucket, *copy.collection)
  102. return true
  103. }
  104. }
  105. }
  106. if *copy.collection == "" {
  107. *copy.collection = collection
  108. }
  109. if *copy.replication == "" {
  110. *copy.replication = replication
  111. }
  112. if *copy.maxMB == 0 {
  113. *copy.maxMB = int(maxMB)
  114. }
  115. copy.masters = masters
  116. copy.cipher = cipher
  117. ttl, err := needle.ReadTTL(*copy.ttl)
  118. if err != nil {
  119. fmt.Printf("parsing ttl %s: %v\n", *copy.ttl, err)
  120. return false
  121. }
  122. copy.ttlSec = int32(ttl.Minutes()) * 60
  123. if *cmdFilerCopy.IsDebug {
  124. grace.SetupProfiling("filer.copy.cpu.pprof", "filer.copy.mem.pprof")
  125. }
  126. fileCopyTaskChan := make(chan FileCopyTask, *copy.concurrentFiles)
  127. go func() {
  128. defer close(fileCopyTaskChan)
  129. for _, fileOrDir := range fileOrDirs {
  130. if err := genFileCopyTask(fileOrDir, urlPath, fileCopyTaskChan); err != nil {
  131. fmt.Fprintf(os.Stderr, "genFileCopyTask : %v\n", err)
  132. break
  133. }
  134. }
  135. }()
  136. for i := 0; i < *copy.concurrentFiles; i++ {
  137. waitGroup.Add(1)
  138. go func() {
  139. defer waitGroup.Done()
  140. worker := FileCopyWorker{
  141. options: &copy,
  142. filerAddress: filerAddress,
  143. signature: util.RandomInt32(),
  144. }
  145. if err := worker.copyFiles(fileCopyTaskChan); err != nil {
  146. fmt.Fprintf(os.Stderr, "copy file error: %v\n", err)
  147. return
  148. }
  149. }()
  150. }
  151. waitGroup.Wait()
  152. return true
  153. }
  154. func readFilerConfiguration(grpcDialOption grpc.DialOption, filerGrpcAddress pb.ServerAddress) (masters []string, collection, replication string, dirBuckets string, maxMB uint32, cipher bool, err error) {
  155. err = pb.WithGrpcFilerClient(false, 0, filerGrpcAddress, grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  156. resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{})
  157. if err != nil {
  158. return fmt.Errorf("get filer %s configuration: %v", filerGrpcAddress, err)
  159. }
  160. masters, collection, replication, maxMB = resp.Masters, resp.Collection, resp.Replication, resp.MaxMb
  161. dirBuckets = resp.DirBuckets
  162. cipher = resp.Cipher
  163. return nil
  164. })
  165. return
  166. }
  167. func genFileCopyTask(fileOrDir string, destPath string, fileCopyTaskChan chan FileCopyTask) error {
  168. fi, err := os.Stat(fileOrDir)
  169. if err != nil {
  170. fmt.Fprintf(os.Stderr, "Error: read file %s: %v\n", fileOrDir, err)
  171. return nil
  172. }
  173. mode := fi.Mode()
  174. uid, gid := util.GetFileUidGid(fi)
  175. fileSize := fi.Size()
  176. if mode.IsDir() {
  177. fileSize = 0
  178. }
  179. fileCopyTaskChan <- FileCopyTask{
  180. sourceLocation: fileOrDir,
  181. destinationUrlPath: destPath,
  182. fileSize: fileSize,
  183. fileMode: fi.Mode(),
  184. uid: uid,
  185. gid: gid,
  186. }
  187. if mode.IsDir() {
  188. files, _ := os.ReadDir(fileOrDir)
  189. for _, subFileOrDir := range files {
  190. cleanedDestDirectory := destPath + fi.Name()
  191. if err = genFileCopyTask(fileOrDir+"/"+subFileOrDir.Name(), cleanedDestDirectory+"/", fileCopyTaskChan); err != nil {
  192. return err
  193. }
  194. }
  195. }
  196. return nil
  197. }
  198. type FileCopyWorker struct {
  199. options *CopyOptions
  200. filerAddress pb.ServerAddress
  201. signature int32
  202. }
  203. func (worker *FileCopyWorker) copyFiles(fileCopyTaskChan chan FileCopyTask) error {
  204. for task := range fileCopyTaskChan {
  205. if err := worker.doEachCopy(task); err != nil {
  206. return err
  207. }
  208. }
  209. return nil
  210. }
  211. type FileCopyTask struct {
  212. sourceLocation string
  213. destinationUrlPath string
  214. fileSize int64
  215. fileMode os.FileMode
  216. uid uint32
  217. gid uint32
  218. }
  219. func (worker *FileCopyWorker) doEachCopy(task FileCopyTask) error {
  220. f, err := os.Open(task.sourceLocation)
  221. if err != nil {
  222. fmt.Printf("Failed to open file %s: %v\n", task.sourceLocation, err)
  223. if _, ok := err.(*os.PathError); ok {
  224. fmt.Printf("skipping %s\n", task.sourceLocation)
  225. return nil
  226. }
  227. return err
  228. }
  229. defer f.Close()
  230. // this is a regular file
  231. if *worker.options.include != "" {
  232. if ok, _ := filepath.Match(*worker.options.include, filepath.Base(task.sourceLocation)); !ok {
  233. return nil
  234. }
  235. }
  236. if shouldCopy, err := worker.checkExistingFileFirst(task, f); err != nil {
  237. return fmt.Errorf("check existing file: %v", err)
  238. } else if !shouldCopy {
  239. if *worker.options.verbose {
  240. fmt.Printf("skipping copied file: %v\n", f.Name())
  241. }
  242. return nil
  243. }
  244. // find the chunk count
  245. chunkSize := int64(*worker.options.maxMB * 1024 * 1024)
  246. chunkCount := 1
  247. if chunkSize > 0 && task.fileSize > chunkSize {
  248. chunkCount = int(task.fileSize/chunkSize) + 1
  249. }
  250. if chunkCount == 1 {
  251. return worker.uploadFileAsOne(task, f)
  252. }
  253. return worker.uploadFileInChunks(task, f, chunkCount, chunkSize)
  254. }
  255. func (worker *FileCopyWorker) checkExistingFileFirst(task FileCopyTask, f *os.File) (shouldCopy bool, err error) {
  256. shouldCopy = true
  257. if !*worker.options.checkSize {
  258. return
  259. }
  260. fileStat, err := f.Stat()
  261. if err != nil {
  262. shouldCopy = false
  263. return
  264. }
  265. err = pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  266. request := &filer_pb.LookupDirectoryEntryRequest{
  267. Directory: task.destinationUrlPath,
  268. Name: filepath.Base(f.Name()),
  269. }
  270. resp, lookupErr := client.LookupDirectoryEntry(context.Background(), request)
  271. if lookupErr != nil {
  272. // mostly not found error
  273. return nil
  274. }
  275. if fileStat.Size() == int64(filer.FileSize(resp.Entry)) {
  276. shouldCopy = false
  277. }
  278. return nil
  279. })
  280. return
  281. }
  282. func (worker *FileCopyWorker) uploadFileAsOne(task FileCopyTask, f *os.File) error {
  283. // upload the file content
  284. fileName := filepath.Base(f.Name())
  285. var mimeType string
  286. var chunks []*filer_pb.FileChunk
  287. if task.fileMode&os.ModeDir == 0 && task.fileSize > 0 {
  288. mimeType = detectMimeType(f)
  289. data, err := io.ReadAll(f)
  290. if err != nil {
  291. return err
  292. }
  293. finalFileId, uploadResult, flushErr, _ := operation.UploadWithRetry(
  294. worker,
  295. &filer_pb.AssignVolumeRequest{
  296. Count: 1,
  297. Replication: *worker.options.replication,
  298. Collection: *worker.options.collection,
  299. TtlSec: worker.options.ttlSec,
  300. DiskType: *worker.options.diskType,
  301. Path: task.destinationUrlPath,
  302. },
  303. &operation.UploadOption{
  304. Filename: fileName,
  305. Cipher: worker.options.cipher,
  306. IsInputCompressed: false,
  307. MimeType: mimeType,
  308. PairMap: nil,
  309. },
  310. func(host, fileId string) string {
  311. return fmt.Sprintf("http://%s/%s", host, fileId)
  312. },
  313. util.NewBytesReader(data),
  314. )
  315. if flushErr != nil {
  316. return flushErr
  317. }
  318. chunks = append(chunks, uploadResult.ToPbFileChunk(finalFileId, 0, time.Now().UnixNano()))
  319. }
  320. if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  321. request := &filer_pb.CreateEntryRequest{
  322. Directory: task.destinationUrlPath,
  323. Entry: &filer_pb.Entry{
  324. Name: fileName,
  325. Attributes: &filer_pb.FuseAttributes{
  326. Crtime: time.Now().Unix(),
  327. Mtime: time.Now().Unix(),
  328. Gid: task.gid,
  329. Uid: task.uid,
  330. FileSize: uint64(task.fileSize),
  331. FileMode: uint32(task.fileMode),
  332. Mime: mimeType,
  333. TtlSec: worker.options.ttlSec,
  334. },
  335. Chunks: chunks,
  336. },
  337. }
  338. if err := filer_pb.CreateEntry(client, request); err != nil {
  339. return fmt.Errorf("update fh: %v", err)
  340. }
  341. return nil
  342. }); err != nil {
  343. return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerAddress.ToHttpAddress(), task.destinationUrlPath, fileName, err)
  344. }
  345. return nil
  346. }
  347. func (worker *FileCopyWorker) uploadFileInChunks(task FileCopyTask, f *os.File, chunkCount int, chunkSize int64) error {
  348. fileName := filepath.Base(f.Name())
  349. mimeType := detectMimeType(f)
  350. chunksChan := make(chan *filer_pb.FileChunk, chunkCount)
  351. concurrentChunks := make(chan struct{}, *worker.options.concurrentChunks)
  352. var wg sync.WaitGroup
  353. var uploadError error
  354. fmt.Printf("uploading %s in %d chunks ...\n", fileName, chunkCount)
  355. for i := int64(0); i < int64(chunkCount) && uploadError == nil; i++ {
  356. wg.Add(1)
  357. concurrentChunks <- struct{}{}
  358. go func(i int64) {
  359. defer func() {
  360. wg.Done()
  361. <-concurrentChunks
  362. }()
  363. fileId, uploadResult, err, _ := operation.UploadWithRetry(
  364. worker,
  365. &filer_pb.AssignVolumeRequest{
  366. Count: 1,
  367. Replication: *worker.options.replication,
  368. Collection: *worker.options.collection,
  369. TtlSec: worker.options.ttlSec,
  370. DiskType: *worker.options.diskType,
  371. Path: task.destinationUrlPath + fileName,
  372. },
  373. &operation.UploadOption{
  374. Filename: fileName + "-" + strconv.FormatInt(i+1, 10),
  375. Cipher: worker.options.cipher,
  376. IsInputCompressed: false,
  377. MimeType: "",
  378. PairMap: nil,
  379. },
  380. func(host, fileId string) string {
  381. return fmt.Sprintf("http://%s/%s", host, fileId)
  382. },
  383. io.NewSectionReader(f, i*chunkSize, chunkSize),
  384. )
  385. if err != nil {
  386. uploadError = fmt.Errorf("upload data %v: %v\n", fileName, err)
  387. return
  388. }
  389. if uploadResult.Error != "" {
  390. uploadError = fmt.Errorf("upload %v result: %v\n", fileName, uploadResult.Error)
  391. return
  392. }
  393. chunksChan <- uploadResult.ToPbFileChunk(fileId, i*chunkSize, time.Now().UnixNano())
  394. fmt.Printf("uploaded %s-%d [%d,%d)\n", fileName, i+1, i*chunkSize, i*chunkSize+int64(uploadResult.Size))
  395. }(i)
  396. }
  397. wg.Wait()
  398. close(chunksChan)
  399. var chunks []*filer_pb.FileChunk
  400. for chunk := range chunksChan {
  401. chunks = append(chunks, chunk)
  402. }
  403. if uploadError != nil {
  404. var fileIds []string
  405. for _, chunk := range chunks {
  406. fileIds = append(fileIds, chunk.FileId)
  407. }
  408. operation.DeleteFiles(func() pb.ServerAddress {
  409. return pb.ServerAddress(copy.masters[0])
  410. }, false, worker.options.grpcDialOption, fileIds)
  411. return uploadError
  412. }
  413. manifestedChunks, manifestErr := filer.MaybeManifestize(worker.saveDataAsChunk, chunks)
  414. if manifestErr != nil {
  415. return fmt.Errorf("create manifest: %v", manifestErr)
  416. }
  417. if err := pb.WithGrpcFilerClient(false, worker.signature, worker.filerAddress, worker.options.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  418. request := &filer_pb.CreateEntryRequest{
  419. Directory: task.destinationUrlPath,
  420. Entry: &filer_pb.Entry{
  421. Name: fileName,
  422. Attributes: &filer_pb.FuseAttributes{
  423. Crtime: time.Now().Unix(),
  424. Mtime: time.Now().Unix(),
  425. Gid: task.gid,
  426. Uid: task.uid,
  427. FileSize: uint64(task.fileSize),
  428. FileMode: uint32(task.fileMode),
  429. Mime: mimeType,
  430. TtlSec: worker.options.ttlSec,
  431. },
  432. Chunks: manifestedChunks,
  433. },
  434. }
  435. if err := filer_pb.CreateEntry(client, request); err != nil {
  436. return fmt.Errorf("update fh: %v", err)
  437. }
  438. return nil
  439. }); err != nil {
  440. return fmt.Errorf("upload data %v to http://%s%s%s: %v\n", fileName, worker.filerAddress.ToHttpAddress(), task.destinationUrlPath, fileName, err)
  441. }
  442. fmt.Printf("copied %s => http://%s%s%s\n", f.Name(), worker.filerAddress.ToHttpAddress(), task.destinationUrlPath, fileName)
  443. return nil
  444. }
  445. func detectMimeType(f *os.File) string {
  446. head := make([]byte, 512)
  447. f.Seek(0, io.SeekStart)
  448. n, err := f.Read(head)
  449. if err == io.EOF {
  450. return ""
  451. }
  452. if err != nil {
  453. fmt.Printf("read head of %v: %v\n", f.Name(), err)
  454. return ""
  455. }
  456. f.Seek(0, io.SeekStart)
  457. mimeType := http.DetectContentType(head[:n])
  458. if mimeType == "application/octet-stream" {
  459. return ""
  460. }
  461. return mimeType
  462. }
  463. func (worker *FileCopyWorker) saveDataAsChunk(reader io.Reader, name string, offset int64, tsNs int64) (chunk *filer_pb.FileChunk, err error) {
  464. finalFileId, uploadResult, flushErr, _ := operation.UploadWithRetry(
  465. worker,
  466. &filer_pb.AssignVolumeRequest{
  467. Count: 1,
  468. Replication: *worker.options.replication,
  469. Collection: *worker.options.collection,
  470. TtlSec: worker.options.ttlSec,
  471. DiskType: *worker.options.diskType,
  472. Path: name,
  473. },
  474. &operation.UploadOption{
  475. Filename: name,
  476. Cipher: worker.options.cipher,
  477. IsInputCompressed: false,
  478. MimeType: "",
  479. PairMap: nil,
  480. },
  481. func(host, fileId string) string {
  482. return fmt.Sprintf("http://%s/%s", host, fileId)
  483. },
  484. reader,
  485. )
  486. if flushErr != nil {
  487. return nil, fmt.Errorf("upload data: %v", flushErr)
  488. }
  489. if uploadResult.Error != "" {
  490. return nil, fmt.Errorf("upload result: %v", uploadResult.Error)
  491. }
  492. return uploadResult.ToPbFileChunk(finalFileId, offset, tsNs), nil
  493. }
  494. var _ = filer_pb.FilerClient(&FileCopyWorker{})
  495. func (worker *FileCopyWorker) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) (err error) {
  496. filerGrpcAddress := worker.filerAddress.ToGrpcAddress()
  497. err = pb.WithGrpcClient(streamingMode, worker.signature, func(grpcConnection *grpc.ClientConn) error {
  498. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  499. return fn(client)
  500. }, filerGrpcAddress, false, worker.options.grpcDialOption)
  501. return
  502. }
  503. func (worker *FileCopyWorker) AdjustedUrl(location *filer_pb.Location) string {
  504. if *worker.options.volumeServerAccess == "publicUrl" {
  505. return location.PublicUrl
  506. }
  507. return location.Url
  508. }
  509. func (worker *FileCopyWorker) GetDataCenter() string {
  510. return ""
  511. }