multicopy.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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, 0)
  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)
  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. completedBytes += (parts[part.PartNumber-1].End - parts[part.PartNumber-1].Start + 1)
  168. event = newProgressEvent(TransferDataEvent, completedBytes, totalBytes)
  169. publishProgress(listener, event)
  170. case err := <-failed:
  171. close(die)
  172. descBucket.AbortMultipartUpload(imur, options...)
  173. event = newProgressEvent(TransferFailedEvent, completedBytes, totalBytes)
  174. publishProgress(listener, event)
  175. return err
  176. }
  177. if completed >= len(parts) {
  178. break
  179. }
  180. }
  181. event = newProgressEvent(TransferCompletedEvent, completedBytes, totalBytes)
  182. publishProgress(listener, event)
  183. // Complete the multipart upload
  184. _, err = descBucket.CompleteMultipartUpload(imur, ups, options...)
  185. if err != nil {
  186. bucket.AbortMultipartUpload(imur, options...)
  187. return err
  188. }
  189. return nil
  190. }
  191. // ----- Concurrently copy with checkpoint -----
  192. const copyCpMagic = "84F1F18C-FF1D-403B-A1D8-9DEB5F65910A"
  193. type copyCheckpoint struct {
  194. Magic string // Magic
  195. MD5 string // CP content MD5
  196. SrcBucketName string // Source bucket
  197. SrcObjectKey string // Source object
  198. DestBucketName string // Target bucket
  199. DestObjectKey string // Target object
  200. CopyID string // Copy ID
  201. ObjStat objectStat // Object stat
  202. Parts []copyPart // Copy parts
  203. CopyParts []UploadPart // The uploaded parts
  204. PartStat []bool // The part status
  205. }
  206. // isValid checks if the data is valid which means CP is valid and object is not updated.
  207. func (cp copyCheckpoint) isValid(meta http.Header) (bool, error) {
  208. // Compare CP's magic number and the MD5.
  209. cpb := cp
  210. cpb.MD5 = ""
  211. js, _ := json.Marshal(cpb)
  212. sum := md5.Sum(js)
  213. b64 := base64.StdEncoding.EncodeToString(sum[:])
  214. if cp.Magic != downloadCpMagic || b64 != cp.MD5 {
  215. return false, nil
  216. }
  217. objectSize, err := strconv.ParseInt(meta.Get(HTTPHeaderContentLength), 10, 0)
  218. if err != nil {
  219. return false, err
  220. }
  221. // Compare the object size and last modified time and etag.
  222. if cp.ObjStat.Size != objectSize ||
  223. cp.ObjStat.LastModified != meta.Get(HTTPHeaderLastModified) ||
  224. cp.ObjStat.Etag != meta.Get(HTTPHeaderEtag) {
  225. return false, nil
  226. }
  227. return true, nil
  228. }
  229. // load loads from the checkpoint file
  230. func (cp *copyCheckpoint) load(filePath string) error {
  231. contents, err := ioutil.ReadFile(filePath)
  232. if err != nil {
  233. return err
  234. }
  235. err = json.Unmarshal(contents, cp)
  236. return err
  237. }
  238. // update updates the parts status
  239. func (cp *copyCheckpoint) update(part UploadPart) {
  240. cp.CopyParts[part.PartNumber-1] = part
  241. cp.PartStat[part.PartNumber-1] = true
  242. }
  243. // dump dumps the CP to the file
  244. func (cp *copyCheckpoint) dump(filePath string) error {
  245. bcp := *cp
  246. // Calculate MD5
  247. bcp.MD5 = ""
  248. js, err := json.Marshal(bcp)
  249. if err != nil {
  250. return err
  251. }
  252. sum := md5.Sum(js)
  253. b64 := base64.StdEncoding.EncodeToString(sum[:])
  254. bcp.MD5 = b64
  255. // Serialization
  256. js, err = json.Marshal(bcp)
  257. if err != nil {
  258. return err
  259. }
  260. // Dump
  261. return ioutil.WriteFile(filePath, js, FilePermMode)
  262. }
  263. // todoParts returns unfinished parts
  264. func (cp copyCheckpoint) todoParts() []copyPart {
  265. dps := []copyPart{}
  266. for i, ps := range cp.PartStat {
  267. if !ps {
  268. dps = append(dps, cp.Parts[i])
  269. }
  270. }
  271. return dps
  272. }
  273. // getCompletedBytes returns finished bytes count
  274. func (cp copyCheckpoint) getCompletedBytes() int64 {
  275. var completedBytes int64
  276. for i, part := range cp.Parts {
  277. if cp.PartStat[i] {
  278. completedBytes += (part.End - part.Start + 1)
  279. }
  280. }
  281. return completedBytes
  282. }
  283. // prepare initializes the multipart upload
  284. func (cp *copyCheckpoint) prepare(meta http.Header, srcBucket *Bucket, srcObjectKey string, destBucket *Bucket, destObjectKey string,
  285. partSize int64, options []Option) error {
  286. // CP
  287. cp.Magic = copyCpMagic
  288. cp.SrcBucketName = srcBucket.BucketName
  289. cp.SrcObjectKey = srcObjectKey
  290. cp.DestBucketName = destBucket.BucketName
  291. cp.DestObjectKey = destObjectKey
  292. objectSize, err := strconv.ParseInt(meta.Get(HTTPHeaderContentLength), 10, 0)
  293. if err != nil {
  294. return err
  295. }
  296. cp.ObjStat.Size = objectSize
  297. cp.ObjStat.LastModified = meta.Get(HTTPHeaderLastModified)
  298. cp.ObjStat.Etag = meta.Get(HTTPHeaderEtag)
  299. // Parts
  300. cp.Parts = getCopyParts(objectSize, partSize)
  301. cp.PartStat = make([]bool, len(cp.Parts))
  302. for i := range cp.PartStat {
  303. cp.PartStat[i] = false
  304. }
  305. cp.CopyParts = make([]UploadPart, len(cp.Parts))
  306. // Init copy
  307. imur, err := destBucket.InitiateMultipartUpload(destObjectKey, options...)
  308. if err != nil {
  309. return err
  310. }
  311. cp.CopyID = imur.UploadID
  312. return nil
  313. }
  314. func (cp *copyCheckpoint) complete(bucket *Bucket, parts []UploadPart, cpFilePath string, options []Option) error {
  315. imur := InitiateMultipartUploadResult{Bucket: cp.DestBucketName,
  316. Key: cp.DestObjectKey, UploadID: cp.CopyID}
  317. _, err := bucket.CompleteMultipartUpload(imur, parts, options...)
  318. if err != nil {
  319. return err
  320. }
  321. os.Remove(cpFilePath)
  322. return err
  323. }
  324. // copyFileWithCp is concurrently copy with checkpoint
  325. func (bucket Bucket) copyFileWithCp(srcBucketName, srcObjectKey, destBucketName, destObjectKey string,
  326. partSize int64, options []Option, cpFilePath string, routines int) error {
  327. descBucket, err := bucket.Client.Bucket(destBucketName)
  328. srcBucket, err := bucket.Client.Bucket(srcBucketName)
  329. listener := getProgressListener(options)
  330. // Load CP data
  331. ccp := copyCheckpoint{}
  332. err = ccp.load(cpFilePath)
  333. if err != nil {
  334. os.Remove(cpFilePath)
  335. }
  336. // Make sure the object is not updated.
  337. // get whole length
  338. skipOptions := deleteOption(options, HTTPHeaderRange)
  339. meta, err := srcBucket.GetObjectDetailedMeta(srcObjectKey, skipOptions...)
  340. if err != nil {
  341. return err
  342. }
  343. // Load error or the CP data is invalid---reinitialize
  344. valid, err := ccp.isValid(meta)
  345. if err != nil || !valid {
  346. if err = ccp.prepare(meta, srcBucket, srcObjectKey, descBucket, destObjectKey, partSize, options); err != nil {
  347. return err
  348. }
  349. os.Remove(cpFilePath)
  350. }
  351. // Unfinished parts
  352. parts := ccp.todoParts()
  353. imur := InitiateMultipartUploadResult{
  354. Bucket: destBucketName,
  355. Key: destObjectKey,
  356. UploadID: ccp.CopyID}
  357. jobs := make(chan copyPart, len(parts))
  358. results := make(chan UploadPart, len(parts))
  359. failed := make(chan error)
  360. die := make(chan bool)
  361. completedBytes := ccp.getCompletedBytes()
  362. event := newProgressEvent(TransferStartedEvent, completedBytes, ccp.ObjStat.Size)
  363. publishProgress(listener, event)
  364. // Start the worker coroutines
  365. arg := copyWorkerArg{descBucket, imur, srcBucketName, srcObjectKey, options, copyPartHooker}
  366. for w := 1; w <= routines; w++ {
  367. go copyWorker(w, arg, jobs, results, failed, die)
  368. }
  369. // Start the scheduler
  370. go copyScheduler(jobs, parts)
  371. // Wait for the parts completed.
  372. completed := 0
  373. for completed < len(parts) {
  374. select {
  375. case part := <-results:
  376. completed++
  377. ccp.update(part)
  378. ccp.dump(cpFilePath)
  379. completedBytes += (parts[part.PartNumber-1].End - parts[part.PartNumber-1].Start + 1)
  380. event = newProgressEvent(TransferDataEvent, completedBytes, ccp.ObjStat.Size)
  381. publishProgress(listener, event)
  382. case err := <-failed:
  383. close(die)
  384. event = newProgressEvent(TransferFailedEvent, completedBytes, ccp.ObjStat.Size)
  385. publishProgress(listener, event)
  386. return err
  387. }
  388. if completed >= len(parts) {
  389. break
  390. }
  391. }
  392. event = newProgressEvent(TransferCompletedEvent, completedBytes, ccp.ObjStat.Size)
  393. publishProgress(listener, event)
  394. return ccp.complete(descBucket, ccp.CopyParts, cpFilePath, options)
  395. }