upload.go 13 KB

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