multicopy.go 13 KB

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