upload.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. package oss
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path/filepath"
  12. "time"
  13. )
  14. // UploadFile is multipart file upload.
  15. //
  16. // objectKey the object name.
  17. // filePath the local file path to upload.
  18. // partSize the part size in byte.
  19. // options the options for uploading object.
  20. //
  21. // error it's nil if the operation succeeds, otherwise it's an error object.
  22. //
  23. func (bucket Bucket) UploadFile(objectKey, filePath string, partSize int64, options ...Option) error {
  24. if partSize < MinPartSize || partSize > MaxPartSize {
  25. return errors.New("oss: part size invalid range (100KB, 5GB]")
  26. }
  27. cpConf := getCpConfig(options)
  28. routines := getRoutines(options)
  29. if cpConf != nil && cpConf.IsEnable {
  30. cpFilePath := getUploadCpFilePath(cpConf, filePath, bucket.BucketName, objectKey)
  31. if cpFilePath != "" {
  32. return bucket.uploadFileWithCp(objectKey, filePath, partSize, options, cpFilePath, routines)
  33. }
  34. }
  35. return bucket.uploadFile(objectKey, filePath, partSize, options, routines)
  36. }
  37. func getUploadCpFilePath(cpConf *cpConfig, srcFile, destBucket, destObject string) string {
  38. if cpConf.FilePath == "" && cpConf.DirPath != "" {
  39. dest := fmt.Sprintf("oss://%v/%v", destBucket, destObject)
  40. absPath, _ := filepath.Abs(srcFile)
  41. cpFileName := getCpFileName(absPath, dest)
  42. cpConf.FilePath = cpConf.DirPath + string(os.PathSeparator) + cpFileName
  43. }
  44. return cpConf.FilePath
  45. }
  46. // ----- concurrent upload without checkpoint -----
  47. // getCpConfig gets checkpoint configuration
  48. func getCpConfig(options []Option) *cpConfig {
  49. cpcOpt, err := findOption(options, checkpointConfig, nil)
  50. if err != nil || cpcOpt == nil {
  51. return nil
  52. }
  53. return cpcOpt.(*cpConfig)
  54. }
  55. // getCpFileName return the name of the checkpoint file
  56. func getCpFileName(src, dest string) string {
  57. md5Ctx := md5.New()
  58. md5Ctx.Write([]byte(src))
  59. srcCheckSum := hex.EncodeToString(md5Ctx.Sum(nil))
  60. md5Ctx.Reset()
  61. md5Ctx.Write([]byte(dest))
  62. destCheckSum := hex.EncodeToString(md5Ctx.Sum(nil))
  63. return fmt.Sprintf("%v-%v.cp", srcCheckSum, destCheckSum)
  64. }
  65. // getRoutines gets the routine count. by default it's 1.
  66. func getRoutines(options []Option) int {
  67. rtnOpt, err := findOption(options, routineNum, nil)
  68. if err != nil || rtnOpt == nil {
  69. return 1
  70. }
  71. rs := rtnOpt.(int)
  72. if rs < 1 {
  73. rs = 1
  74. } else if rs > 100 {
  75. rs = 100
  76. }
  77. return rs
  78. }
  79. // getPayer return the payer of the request
  80. func getPayer(options []Option) string {
  81. payerOpt, err := findOption(options, HTTPHeaderOssRequester, nil)
  82. if err != nil || payerOpt == nil {
  83. return ""
  84. }
  85. return payerOpt.(string)
  86. }
  87. // getProgressListener gets the progress callback
  88. func getProgressListener(options []Option) ProgressListener {
  89. isSet, listener, _ := isOptionSet(options, progressListener)
  90. if !isSet {
  91. return nil
  92. }
  93. return listener.(ProgressListener)
  94. }
  95. // uploadPartHook is for testing usage
  96. type uploadPartHook func(id int, chunk FileChunk) error
  97. var uploadPartHooker uploadPartHook = defaultUploadPart
  98. func defaultUploadPart(id int, chunk FileChunk) error {
  99. return nil
  100. }
  101. // workerArg defines worker argument structure
  102. type workerArg struct {
  103. bucket *Bucket
  104. filePath string
  105. imur InitiateMultipartUploadResult
  106. options []Option
  107. hook uploadPartHook
  108. }
  109. // worker is the worker coroutine function
  110. func worker(id int, arg workerArg, jobs <-chan FileChunk, results chan<- UploadPart, failed chan<- error, die <-chan bool) {
  111. for chunk := range jobs {
  112. if err := arg.hook(id, chunk); err != nil {
  113. failed <- err
  114. break
  115. }
  116. part, err := arg.bucket.UploadPartFromFile(arg.imur, arg.filePath, chunk.Offset, chunk.Size, chunk.Number, arg.options...)
  117. if err != nil {
  118. failed <- err
  119. break
  120. }
  121. select {
  122. case <-die:
  123. return
  124. default:
  125. }
  126. results <- part
  127. }
  128. }
  129. // scheduler function
  130. func scheduler(jobs chan FileChunk, chunks []FileChunk) {
  131. for _, chunk := range chunks {
  132. jobs <- chunk
  133. }
  134. close(jobs)
  135. }
  136. func getTotalBytes(chunks []FileChunk) int64 {
  137. var tb int64
  138. for _, chunk := range chunks {
  139. tb += chunk.Size
  140. }
  141. return tb
  142. }
  143. // uploadFile is a concurrent upload, without checkpoint
  144. func (bucket Bucket) uploadFile(objectKey, filePath string, partSize int64, options []Option, routines int) error {
  145. listener := getProgressListener(options)
  146. chunks, err := SplitFileByPartSize(filePath, partSize)
  147. if err != nil {
  148. return err
  149. }
  150. payerOptions := []Option{}
  151. payer := getPayer(options)
  152. if payer != "" {
  153. payerOptions = append(payerOptions, RequestPayer(PayerType(payer)))
  154. }
  155. // Initialize the multipart upload
  156. imur, err := bucket.InitiateMultipartUpload(objectKey, options...)
  157. if err != nil {
  158. return err
  159. }
  160. jobs := make(chan FileChunk, len(chunks))
  161. results := make(chan UploadPart, len(chunks))
  162. failed := make(chan error)
  163. die := make(chan bool)
  164. var completedBytes int64
  165. totalBytes := getTotalBytes(chunks)
  166. event := newProgressEvent(TransferStartedEvent, 0, totalBytes)
  167. publishProgress(listener, event)
  168. // Start the worker coroutine
  169. arg := workerArg{&bucket, filePath, imur, payerOptions, uploadPartHooker}
  170. for w := 1; w <= routines; w++ {
  171. go worker(w, arg, jobs, results, failed, die)
  172. }
  173. // Schedule the jobs
  174. go scheduler(jobs, chunks)
  175. // Waiting for the upload finished
  176. completed := 0
  177. parts := make([]UploadPart, len(chunks))
  178. for completed < len(chunks) {
  179. select {
  180. case part := <-results:
  181. completed++
  182. parts[part.PartNumber-1] = part
  183. completedBytes += chunks[part.PartNumber-1].Size
  184. event = newProgressEvent(TransferDataEvent, completedBytes, totalBytes)
  185. publishProgress(listener, event)
  186. case err := <-failed:
  187. close(die)
  188. event = newProgressEvent(TransferFailedEvent, completedBytes, totalBytes)
  189. publishProgress(listener, event)
  190. bucket.AbortMultipartUpload(imur, payerOptions...)
  191. return err
  192. }
  193. if completed >= len(chunks) {
  194. break
  195. }
  196. }
  197. event = newProgressEvent(TransferStartedEvent, completedBytes, totalBytes)
  198. publishProgress(listener, event)
  199. // Complete the multpart upload
  200. _, err = bucket.CompleteMultipartUpload(imur, parts, payerOptions...)
  201. if err != nil {
  202. bucket.AbortMultipartUpload(imur, payerOptions...)
  203. return err
  204. }
  205. return nil
  206. }
  207. // ----- concurrent upload with checkpoint -----
  208. const uploadCpMagic = "FE8BB4EA-B593-4FAC-AD7A-2459A36E2E62"
  209. type uploadCheckpoint struct {
  210. Magic string // Magic
  211. MD5 string // Checkpoint file content's MD5
  212. FilePath string // Local file path
  213. FileStat cpStat // File state
  214. ObjectKey string // Key
  215. UploadID string // Upload ID
  216. Parts []cpPart // All parts of the local file
  217. }
  218. type cpStat struct {
  219. Size int64 // File size
  220. LastModified time.Time // File's last modified time
  221. MD5 string // Local file's MD5
  222. }
  223. type cpPart struct {
  224. Chunk FileChunk // File chunk
  225. Part UploadPart // Uploaded part
  226. IsCompleted bool // Upload complete flag
  227. }
  228. // isValid checks if the uploaded data is valid---it's valid when the file is not updated and the checkpoint data is valid.
  229. func (cp uploadCheckpoint) isValid(filePath string) (bool, error) {
  230. // Compare the CP's magic number and MD5.
  231. cpb := cp
  232. cpb.MD5 = ""
  233. js, _ := json.Marshal(cpb)
  234. sum := md5.Sum(js)
  235. b64 := base64.StdEncoding.EncodeToString(sum[:])
  236. if cp.Magic != uploadCpMagic || b64 != cp.MD5 {
  237. return false, nil
  238. }
  239. // Make sure if the local file is updated.
  240. fd, err := os.Open(filePath)
  241. if err != nil {
  242. return false, err
  243. }
  244. defer fd.Close()
  245. st, err := fd.Stat()
  246. if err != nil {
  247. return false, err
  248. }
  249. md, err := calcFileMD5(filePath)
  250. if err != nil {
  251. return false, err
  252. }
  253. // Compare the file size, file's last modified time and file's MD5
  254. if cp.FileStat.Size != st.Size() ||
  255. cp.FileStat.LastModified != st.ModTime() ||
  256. cp.FileStat.MD5 != md {
  257. return false, nil
  258. }
  259. return true, nil
  260. }
  261. // load loads from the file
  262. func (cp *uploadCheckpoint) load(filePath string) error {
  263. contents, err := ioutil.ReadFile(filePath)
  264. if err != nil {
  265. return err
  266. }
  267. err = json.Unmarshal(contents, cp)
  268. return err
  269. }
  270. // dump dumps to the local file
  271. func (cp *uploadCheckpoint) dump(filePath string) error {
  272. bcp := *cp
  273. // Calculate MD5
  274. bcp.MD5 = ""
  275. js, err := json.Marshal(bcp)
  276. if err != nil {
  277. return err
  278. }
  279. sum := md5.Sum(js)
  280. b64 := base64.StdEncoding.EncodeToString(sum[:])
  281. bcp.MD5 = b64
  282. // Serialization
  283. js, err = json.Marshal(bcp)
  284. if err != nil {
  285. return err
  286. }
  287. // Dump
  288. return ioutil.WriteFile(filePath, js, FilePermMode)
  289. }
  290. // updatePart updates the part status
  291. func (cp *uploadCheckpoint) updatePart(part UploadPart) {
  292. cp.Parts[part.PartNumber-1].Part = part
  293. cp.Parts[part.PartNumber-1].IsCompleted = true
  294. }
  295. // todoParts returns unfinished parts
  296. func (cp *uploadCheckpoint) todoParts() []FileChunk {
  297. fcs := []FileChunk{}
  298. for _, part := range cp.Parts {
  299. if !part.IsCompleted {
  300. fcs = append(fcs, part.Chunk)
  301. }
  302. }
  303. return fcs
  304. }
  305. // allParts returns all parts
  306. func (cp *uploadCheckpoint) allParts() []UploadPart {
  307. ps := []UploadPart{}
  308. for _, part := range cp.Parts {
  309. ps = append(ps, part.Part)
  310. }
  311. return ps
  312. }
  313. // getCompletedBytes returns completed bytes count
  314. func (cp *uploadCheckpoint) getCompletedBytes() int64 {
  315. var completedBytes int64
  316. for _, part := range cp.Parts {
  317. if part.IsCompleted {
  318. completedBytes += part.Chunk.Size
  319. }
  320. }
  321. return completedBytes
  322. }
  323. // calcFileMD5 calculates the MD5 for the specified local file
  324. func calcFileMD5(filePath string) (string, error) {
  325. return "", nil
  326. }
  327. // prepare initializes the multipart upload
  328. func prepare(cp *uploadCheckpoint, objectKey, filePath string, partSize int64, bucket *Bucket, options []Option) error {
  329. // CP
  330. cp.Magic = uploadCpMagic
  331. cp.FilePath = filePath
  332. cp.ObjectKey = objectKey
  333. // Local file
  334. fd, err := os.Open(filePath)
  335. if err != nil {
  336. return err
  337. }
  338. defer fd.Close()
  339. st, err := fd.Stat()
  340. if err != nil {
  341. return err
  342. }
  343. cp.FileStat.Size = st.Size()
  344. cp.FileStat.LastModified = st.ModTime()
  345. md, err := calcFileMD5(filePath)
  346. if err != nil {
  347. return err
  348. }
  349. cp.FileStat.MD5 = md
  350. // Chunks
  351. parts, err := SplitFileByPartSize(filePath, partSize)
  352. if err != nil {
  353. return err
  354. }
  355. cp.Parts = make([]cpPart, len(parts))
  356. for i, part := range parts {
  357. cp.Parts[i].Chunk = part
  358. cp.Parts[i].IsCompleted = false
  359. }
  360. // Init load
  361. imur, err := bucket.InitiateMultipartUpload(objectKey, options...)
  362. if err != nil {
  363. return err
  364. }
  365. cp.UploadID = imur.UploadID
  366. return nil
  367. }
  368. // complete completes the multipart upload and deletes the local CP files
  369. func complete(cp *uploadCheckpoint, bucket *Bucket, parts []UploadPart, cpFilePath string, options []Option) error {
  370. imur := InitiateMultipartUploadResult{Bucket: bucket.BucketName,
  371. Key: cp.ObjectKey, UploadID: cp.UploadID}
  372. _, err := bucket.CompleteMultipartUpload(imur, parts, options...)
  373. if err != nil {
  374. return err
  375. }
  376. os.Remove(cpFilePath)
  377. return err
  378. }
  379. // uploadFileWithCp handles concurrent upload with checkpoint
  380. func (bucket Bucket) uploadFileWithCp(objectKey, filePath string, partSize int64, options []Option, cpFilePath string, routines int) error {
  381. listener := getProgressListener(options)
  382. payerOptions := []Option{}
  383. payer := getPayer(options)
  384. if payer != "" {
  385. payerOptions = append(payerOptions, RequestPayer(PayerType(payer)))
  386. }
  387. // Load CP data
  388. ucp := uploadCheckpoint{}
  389. err := ucp.load(cpFilePath)
  390. if err != nil {
  391. os.Remove(cpFilePath)
  392. }
  393. // Load error or the CP data is invalid.
  394. valid, err := ucp.isValid(filePath)
  395. if err != nil || !valid {
  396. if err = prepare(&ucp, objectKey, filePath, partSize, &bucket, options); err != nil {
  397. return err
  398. }
  399. os.Remove(cpFilePath)
  400. }
  401. chunks := ucp.todoParts()
  402. imur := InitiateMultipartUploadResult{
  403. Bucket: bucket.BucketName,
  404. Key: objectKey,
  405. UploadID: ucp.UploadID}
  406. jobs := make(chan FileChunk, len(chunks))
  407. results := make(chan UploadPart, len(chunks))
  408. failed := make(chan error)
  409. die := make(chan bool)
  410. completedBytes := ucp.getCompletedBytes()
  411. event := newProgressEvent(TransferStartedEvent, completedBytes, ucp.FileStat.Size)
  412. publishProgress(listener, event)
  413. // Start the workers
  414. arg := workerArg{&bucket, filePath, imur, payerOptions, uploadPartHooker}
  415. for w := 1; w <= routines; w++ {
  416. go worker(w, arg, jobs, results, failed, die)
  417. }
  418. // Schedule jobs
  419. go scheduler(jobs, chunks)
  420. // Waiting for the job finished
  421. completed := 0
  422. for completed < len(chunks) {
  423. select {
  424. case part := <-results:
  425. completed++
  426. ucp.updatePart(part)
  427. ucp.dump(cpFilePath)
  428. completedBytes += ucp.Parts[part.PartNumber-1].Chunk.Size
  429. event = newProgressEvent(TransferDataEvent, completedBytes, ucp.FileStat.Size)
  430. publishProgress(listener, event)
  431. case err := <-failed:
  432. close(die)
  433. event = newProgressEvent(TransferFailedEvent, completedBytes, ucp.FileStat.Size)
  434. publishProgress(listener, event)
  435. return err
  436. }
  437. if completed >= len(chunks) {
  438. break
  439. }
  440. }
  441. event = newProgressEvent(TransferCompletedEvent, completedBytes, ucp.FileStat.Size)
  442. publishProgress(listener, event)
  443. // Complete the multipart upload
  444. err = complete(&ucp, &bucket, ucp.allParts(), cpFilePath, payerOptions)
  445. return err
  446. }