multicopy.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. package oss
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "strconv"
  12. )
  13. // CopyFile is multipart copy object
  14. //
  15. // srcBucketName source bucket name
  16. // srcObjectKey source object name
  17. // destObjectKey target object name in the form of bucketname.objectkey
  18. // partSize the part size in byte.
  19. // options object's contraints. Check out function InitiateMultipartUpload.
  20. //
  21. // error it's nil if the operation succeeds, otherwise it's an error object.
  22. //
  23. func (bucket Bucket) CopyFile(srcBucketName, srcObjectKey, destObjectKey string, partSize int64, options ...Option) error {
  24. destBucketName := bucket.BucketName
  25. if partSize < MinPartSize || partSize > MaxPartSize {
  26. return errors.New("oss: part size invalid range (1024KB, 5GB]")
  27. }
  28. cpConf := getCpConfig(options)
  29. routines := getRoutines(options)
  30. if cpConf != nil && cpConf.IsEnable {
  31. cpFilePath := getCopyCpFilePath(cpConf, srcBucketName, srcObjectKey, destBucketName, destObjectKey)
  32. if cpFilePath != "" {
  33. return bucket.copyFileWithCp(srcBucketName, srcObjectKey, destBucketName, destObjectKey, partSize, options, cpFilePath, routines)
  34. }
  35. }
  36. return bucket.copyFile(srcBucketName, srcObjectKey, destBucketName, destObjectKey,
  37. partSize, options, routines)
  38. }
  39. func getCopyCpFilePath(cpConf *cpConfig, srcBucket, srcObject, destBucket, destObject string) string {
  40. if cpConf.FilePath == "" && cpConf.DirPath != "" {
  41. dest := fmt.Sprintf("oss://%v/%v", destBucket, destObject)
  42. src := fmt.Sprintf("oss://%v/%v", srcBucket, srcObject)
  43. cpFileName := getCpFileName(src, dest)
  44. cpConf.FilePath = cpConf.DirPath + string(os.PathSeparator) + cpFileName
  45. }
  46. return cpConf.FilePath
  47. }
  48. // ----- Concurrently copy without checkpoint ---------
  49. // copyWorkerArg defines the copy worker arguments
  50. type copyWorkerArg struct {
  51. bucket *Bucket
  52. imur InitiateMultipartUploadResult
  53. srcBucketName string
  54. srcObjectKey string
  55. options []Option
  56. hook copyPartHook
  57. }
  58. // copyPartHook is the hook for testing purpose
  59. type copyPartHook func(part copyPart) error
  60. var copyPartHooker copyPartHook = defaultCopyPartHook
  61. func defaultCopyPartHook(part copyPart) error {
  62. return nil
  63. }
  64. // copyWorker copies worker
  65. func copyWorker(id int, arg copyWorkerArg, jobs <-chan copyPart, results chan<- UploadPart, failed chan<- error, die <-chan bool) {
  66. for chunk := range jobs {
  67. if err := arg.hook(chunk); err != nil {
  68. failed <- err
  69. break
  70. }
  71. chunkSize := chunk.End - chunk.Start + 1
  72. part, err := arg.bucket.UploadPartCopy(arg.imur, arg.srcBucketName, arg.srcObjectKey,
  73. chunk.Start, chunkSize, chunk.Number, arg.options...)
  74. if err != nil {
  75. failed <- err
  76. break
  77. }
  78. select {
  79. case <-die:
  80. return
  81. default:
  82. }
  83. results <- part
  84. }
  85. }
  86. // copyScheduler
  87. func copyScheduler(jobs chan copyPart, parts []copyPart) {
  88. for _, part := range parts {
  89. jobs <- part
  90. }
  91. close(jobs)
  92. }
  93. // copyPart structure
  94. type copyPart struct {
  95. Number int // Part number (from 1 to 10,000)
  96. Start int64 // The start index in the source file.
  97. End int64 // The end index in the source file
  98. }
  99. // getCopyParts calculates copy parts
  100. func getCopyParts(objectSize, partSize int64) []copyPart {
  101. parts := []copyPart{}
  102. part := copyPart{}
  103. i := 0
  104. for offset := int64(0); offset < objectSize; offset += partSize {
  105. part.Number = i + 1
  106. part.Start = offset
  107. part.End = GetPartEnd(offset, objectSize, partSize)
  108. parts = append(parts, part)
  109. i++
  110. }
  111. return parts
  112. }
  113. // getSrcObjectBytes gets the source file size
  114. func getSrcObjectBytes(parts []copyPart) int64 {
  115. var ob int64
  116. for _, part := range parts {
  117. ob += (part.End - part.Start + 1)
  118. }
  119. return ob
  120. }
  121. // copyFile is a concurrently copy without checkpoint
  122. func (bucket Bucket) copyFile(srcBucketName, srcObjectKey, destBucketName, destObjectKey string,
  123. partSize int64, options []Option, routines int) error {
  124. descBucket, err := bucket.Client.Bucket(destBucketName)
  125. srcBucket, err := bucket.Client.Bucket(srcBucketName)
  126. listener := GetProgressListener(options)
  127. // for get whole length
  128. skipOptions := DeleteOption(options, HTTPHeaderRange)
  129. meta, err := srcBucket.GetObjectDetailedMeta(srcObjectKey, skipOptions...)
  130. if err != nil {
  131. return err
  132. }
  133. objectSize, err := strconv.ParseInt(meta.Get(HTTPHeaderContentLength), 10, 64)
  134. if err != nil {
  135. return err
  136. }
  137. // Get copy parts
  138. parts := getCopyParts(objectSize, partSize)
  139. // Initialize the multipart upload
  140. imur, err := descBucket.InitiateMultipartUpload(destObjectKey, options...)
  141. if err != nil {
  142. return err
  143. }
  144. jobs := make(chan copyPart, len(parts))
  145. results := make(chan UploadPart, len(parts))
  146. failed := make(chan error)
  147. die := make(chan bool)
  148. var completedBytes int64
  149. totalBytes := getSrcObjectBytes(parts)
  150. event := newProgressEvent(TransferStartedEvent, 0, totalBytes, 0)
  151. publishProgress(listener, event)
  152. // Start to copy workers
  153. arg := copyWorkerArg{descBucket, imur, srcBucketName, srcObjectKey, options, copyPartHooker}
  154. for w := 1; w <= routines; w++ {
  155. go copyWorker(w, arg, jobs, results, failed, die)
  156. }
  157. // Start the scheduler
  158. go copyScheduler(jobs, parts)
  159. // Wait for the parts finished.
  160. completed := 0
  161. ups := make([]UploadPart, len(parts))
  162. for completed < len(parts) {
  163. select {
  164. case part := <-results:
  165. completed++
  166. ups[part.PartNumber-1] = part
  167. copyBytes := (parts[part.PartNumber-1].End - parts[part.PartNumber-1].Start + 1)
  168. completedBytes += copyBytes
  169. event = newProgressEvent(TransferDataEvent, completedBytes, totalBytes, copyBytes)
  170. publishProgress(listener, event)
  171. case err := <-failed:
  172. close(die)
  173. descBucket.AbortMultipartUpload(imur, options...)
  174. event = newProgressEvent(TransferFailedEvent, completedBytes, totalBytes, 0)
  175. publishProgress(listener, event)
  176. return err
  177. }
  178. if completed >= len(parts) {
  179. break
  180. }
  181. }
  182. event = newProgressEvent(TransferCompletedEvent, completedBytes, totalBytes, 0)
  183. publishProgress(listener, event)
  184. // Complete the multipart upload
  185. _, err = descBucket.CompleteMultipartUpload(imur, ups, options...)
  186. if err != nil {
  187. bucket.AbortMultipartUpload(imur, options...)
  188. return err
  189. }
  190. return nil
  191. }
  192. // ----- Concurrently copy with checkpoint -----
  193. const copyCpMagic = "84F1F18C-FF1D-403B-A1D8-9DEB5F65910A"
  194. type copyCheckpoint struct {
  195. Magic string // Magic
  196. MD5 string // CP content MD5
  197. SrcBucketName string // Source bucket
  198. SrcObjectKey string // Source object
  199. DestBucketName string // Target bucket
  200. DestObjectKey string // Target object
  201. CopyID string // Copy ID
  202. ObjStat objectStat // Object stat
  203. Parts []copyPart // Copy parts
  204. CopyParts []UploadPart // The uploaded parts
  205. PartStat []bool // The part status
  206. }
  207. // isValid checks if the data is valid which means CP is valid and object is not updated.
  208. func (cp copyCheckpoint) isValid(meta http.Header) (bool, error) {
  209. // Compare CP's magic number and the MD5.
  210. cpb := cp
  211. cpb.MD5 = ""
  212. js, _ := json.Marshal(cpb)
  213. sum := md5.Sum(js)
  214. b64 := base64.StdEncoding.EncodeToString(sum[:])
  215. if cp.Magic != downloadCpMagic || b64 != cp.MD5 {
  216. return false, nil
  217. }
  218. objectSize, err := strconv.ParseInt(meta.Get(HTTPHeaderContentLength), 10, 64)
  219. if err != nil {
  220. return false, err
  221. }
  222. // Compare the object size and last modified time and etag.
  223. if cp.ObjStat.Size != objectSize ||
  224. cp.ObjStat.LastModified != meta.Get(HTTPHeaderLastModified) ||
  225. cp.ObjStat.Etag != meta.Get(HTTPHeaderEtag) {
  226. return false, nil
  227. }
  228. return true, nil
  229. }
  230. // load loads from the checkpoint file
  231. func (cp *copyCheckpoint) load(filePath string) error {
  232. contents, err := ioutil.ReadFile(filePath)
  233. if err != nil {
  234. return err
  235. }
  236. err = json.Unmarshal(contents, cp)
  237. return err
  238. }
  239. // update updates the parts status
  240. func (cp *copyCheckpoint) update(part UploadPart) {
  241. cp.CopyParts[part.PartNumber-1] = part
  242. cp.PartStat[part.PartNumber-1] = true
  243. }
  244. // dump dumps the CP to the file
  245. func (cp *copyCheckpoint) dump(filePath string) error {
  246. bcp := *cp
  247. // Calculate MD5
  248. bcp.MD5 = ""
  249. js, err := json.Marshal(bcp)
  250. if err != nil {
  251. return err
  252. }
  253. sum := md5.Sum(js)
  254. b64 := base64.StdEncoding.EncodeToString(sum[:])
  255. bcp.MD5 = b64
  256. // Serialization
  257. js, err = json.Marshal(bcp)
  258. if err != nil {
  259. return err
  260. }
  261. // Dump
  262. return ioutil.WriteFile(filePath, js, FilePermMode)
  263. }
  264. // todoParts returns unfinished parts
  265. func (cp copyCheckpoint) todoParts() []copyPart {
  266. dps := []copyPart{}
  267. for i, ps := range cp.PartStat {
  268. if !ps {
  269. dps = append(dps, cp.Parts[i])
  270. }
  271. }
  272. return dps
  273. }
  274. // getCompletedBytes returns finished bytes count
  275. func (cp copyCheckpoint) getCompletedBytes() int64 {
  276. var completedBytes int64
  277. for i, part := range cp.Parts {
  278. if cp.PartStat[i] {
  279. completedBytes += (part.End - part.Start + 1)
  280. }
  281. }
  282. return completedBytes
  283. }
  284. // prepare initializes the multipart upload
  285. func (cp *copyCheckpoint) prepare(meta http.Header, srcBucket *Bucket, srcObjectKey string, destBucket *Bucket, destObjectKey string,
  286. partSize int64, options []Option) error {
  287. // CP
  288. cp.Magic = copyCpMagic
  289. cp.SrcBucketName = srcBucket.BucketName
  290. cp.SrcObjectKey = srcObjectKey
  291. cp.DestBucketName = destBucket.BucketName
  292. cp.DestObjectKey = destObjectKey
  293. objectSize, err := strconv.ParseInt(meta.Get(HTTPHeaderContentLength), 10, 64)
  294. if err != nil {
  295. return err
  296. }
  297. cp.ObjStat.Size = objectSize
  298. cp.ObjStat.LastModified = meta.Get(HTTPHeaderLastModified)
  299. cp.ObjStat.Etag = meta.Get(HTTPHeaderEtag)
  300. // Parts
  301. cp.Parts = getCopyParts(objectSize, partSize)
  302. cp.PartStat = make([]bool, len(cp.Parts))
  303. for i := range cp.PartStat {
  304. cp.PartStat[i] = false
  305. }
  306. cp.CopyParts = make([]UploadPart, len(cp.Parts))
  307. // Init copy
  308. imur, err := destBucket.InitiateMultipartUpload(destObjectKey, options...)
  309. if err != nil {
  310. return err
  311. }
  312. cp.CopyID = imur.UploadID
  313. return nil
  314. }
  315. func (cp *copyCheckpoint) complete(bucket *Bucket, parts []UploadPart, cpFilePath string, options []Option) error {
  316. imur := InitiateMultipartUploadResult{Bucket: cp.DestBucketName,
  317. Key: cp.DestObjectKey, UploadID: cp.CopyID}
  318. _, err := bucket.CompleteMultipartUpload(imur, parts, options...)
  319. if err != nil {
  320. return err
  321. }
  322. os.Remove(cpFilePath)
  323. return err
  324. }
  325. // copyFileWithCp is concurrently copy with checkpoint
  326. func (bucket Bucket) copyFileWithCp(srcBucketName, srcObjectKey, destBucketName, destObjectKey string,
  327. partSize int64, options []Option, cpFilePath string, routines int) error {
  328. descBucket, err := bucket.Client.Bucket(destBucketName)
  329. srcBucket, err := bucket.Client.Bucket(srcBucketName)
  330. listener := GetProgressListener(options)
  331. // Load CP data
  332. ccp := copyCheckpoint{}
  333. err = ccp.load(cpFilePath)
  334. if err != nil {
  335. os.Remove(cpFilePath)
  336. }
  337. // Make sure the object is not updated.
  338. // get whole length
  339. skipOptions := DeleteOption(options, HTTPHeaderRange)
  340. meta, err := srcBucket.GetObjectDetailedMeta(srcObjectKey, skipOptions...)
  341. if err != nil {
  342. return err
  343. }
  344. // Load error or the CP data is invalid---reinitialize
  345. valid, err := ccp.isValid(meta)
  346. if err != nil || !valid {
  347. if err = ccp.prepare(meta, srcBucket, srcObjectKey, descBucket, destObjectKey, partSize, options); err != nil {
  348. return err
  349. }
  350. os.Remove(cpFilePath)
  351. }
  352. // Unfinished parts
  353. parts := ccp.todoParts()
  354. imur := InitiateMultipartUploadResult{
  355. Bucket: destBucketName,
  356. Key: destObjectKey,
  357. UploadID: ccp.CopyID}
  358. jobs := make(chan copyPart, len(parts))
  359. results := make(chan UploadPart, len(parts))
  360. failed := make(chan error)
  361. die := make(chan bool)
  362. completedBytes := ccp.getCompletedBytes()
  363. event := newProgressEvent(TransferStartedEvent, completedBytes, ccp.ObjStat.Size, 0)
  364. publishProgress(listener, event)
  365. // Start the worker coroutines
  366. arg := copyWorkerArg{descBucket, imur, srcBucketName, srcObjectKey, options, copyPartHooker}
  367. for w := 1; w <= routines; w++ {
  368. go copyWorker(w, arg, jobs, results, failed, die)
  369. }
  370. // Start the scheduler
  371. go copyScheduler(jobs, parts)
  372. // Wait for the parts completed.
  373. completed := 0
  374. for completed < len(parts) {
  375. select {
  376. case part := <-results:
  377. completed++
  378. ccp.update(part)
  379. ccp.dump(cpFilePath)
  380. copyBytes := (parts[part.PartNumber-1].End - parts[part.PartNumber-1].Start + 1)
  381. completedBytes += copyBytes
  382. event = newProgressEvent(TransferDataEvent, completedBytes, ccp.ObjStat.Size, copyBytes)
  383. publishProgress(listener, event)
  384. case err := <-failed:
  385. close(die)
  386. event = newProgressEvent(TransferFailedEvent, completedBytes, ccp.ObjStat.Size, 0)
  387. publishProgress(listener, event)
  388. return err
  389. }
  390. if completed >= len(parts) {
  391. break
  392. }
  393. }
  394. event = newProgressEvent(TransferCompletedEvent, completedBytes, ccp.ObjStat.Size,0)
  395. publishProgress(listener, event)
  396. return ccp.complete(descBucket, ccp.CopyParts, cpFilePath, options)
  397. }