upload.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. // Initialize the multipart upload
  151. imur, err := bucket.InitiateMultipartUpload(objectKey, options...)
  152. if err != nil {
  153. return err
  154. }
  155. jobs := make(chan FileChunk, len(chunks))
  156. results := make(chan UploadPart, len(chunks))
  157. failed := make(chan error)
  158. die := make(chan bool)
  159. var completedBytes int64
  160. totalBytes := getTotalBytes(chunks)
  161. event := newProgressEvent(TransferStartedEvent, 0, totalBytes)
  162. publishProgress(listener, event)
  163. // Start the worker coroutine
  164. arg := workerArg{&bucket, filePath, imur, options, uploadPartHooker}
  165. for w := 1; w <= routines; w++ {
  166. go worker(w, arg, jobs, results, failed, die)
  167. }
  168. // Schedule the jobs
  169. go scheduler(jobs, chunks)
  170. // Waiting for the upload finished
  171. completed := 0
  172. parts := make([]UploadPart, len(chunks))
  173. for completed < len(chunks) {
  174. select {
  175. case part := <-results:
  176. completed++
  177. parts[part.PartNumber-1] = part
  178. completedBytes += chunks[part.PartNumber-1].Size
  179. event = newProgressEvent(TransferDataEvent, completedBytes, totalBytes)
  180. publishProgress(listener, event)
  181. case err := <-failed:
  182. close(die)
  183. event = newProgressEvent(TransferFailedEvent, completedBytes, totalBytes)
  184. publishProgress(listener, event)
  185. bucket.AbortMultipartUpload(imur, options...)
  186. return err
  187. }
  188. if completed >= len(chunks) {
  189. break
  190. }
  191. }
  192. event = newProgressEvent(TransferStartedEvent, completedBytes, totalBytes)
  193. publishProgress(listener, event)
  194. // Complete the multpart upload
  195. _, err = bucket.CompleteMultipartUpload(imur, parts, options...)
  196. if err != nil {
  197. bucket.AbortMultipartUpload(imur, options...)
  198. return err
  199. }
  200. return nil
  201. }
  202. // ----- concurrent upload with checkpoint -----
  203. const uploadCpMagic = "FE8BB4EA-B593-4FAC-AD7A-2459A36E2E62"
  204. type uploadCheckpoint struct {
  205. Magic string // Magic
  206. MD5 string // Checkpoint file content's MD5
  207. FilePath string // Local file path
  208. FileStat cpStat // File state
  209. ObjectKey string // Key
  210. UploadID string // Upload ID
  211. Parts []cpPart // All parts of the local file
  212. }
  213. type cpStat struct {
  214. Size int64 // File size
  215. LastModified time.Time // File's last modified time
  216. MD5 string // Local file's MD5
  217. }
  218. type cpPart struct {
  219. Chunk FileChunk // File chunk
  220. Part UploadPart // Uploaded part
  221. IsCompleted bool // Upload complete flag
  222. }
  223. // isValid checks if the uploaded data is valid---it's valid when the file is not updated and the checkpoint data is valid.
  224. func (cp uploadCheckpoint) isValid(filePath string) (bool, error) {
  225. // Compare the CP's magic number and MD5.
  226. cpb := cp
  227. cpb.MD5 = ""
  228. js, _ := json.Marshal(cpb)
  229. sum := md5.Sum(js)
  230. b64 := base64.StdEncoding.EncodeToString(sum[:])
  231. if cp.Magic != uploadCpMagic || b64 != cp.MD5 {
  232. return false, nil
  233. }
  234. // Make sure if the local file is updated.
  235. fd, err := os.Open(filePath)
  236. if err != nil {
  237. return false, err
  238. }
  239. defer fd.Close()
  240. st, err := fd.Stat()
  241. if err != nil {
  242. return false, err
  243. }
  244. md, err := calcFileMD5(filePath)
  245. if err != nil {
  246. return false, err
  247. }
  248. // Compare the file size, file's last modified time and file's MD5
  249. if cp.FileStat.Size != st.Size() ||
  250. cp.FileStat.LastModified != st.ModTime() ||
  251. cp.FileStat.MD5 != md {
  252. return false, nil
  253. }
  254. return true, nil
  255. }
  256. // load loads from the file
  257. func (cp *uploadCheckpoint) load(filePath string) error {
  258. contents, err := ioutil.ReadFile(filePath)
  259. if err != nil {
  260. return err
  261. }
  262. err = json.Unmarshal(contents, cp)
  263. return err
  264. }
  265. // dump dumps to the local file
  266. func (cp *uploadCheckpoint) dump(filePath string) error {
  267. bcp := *cp
  268. // Calculate MD5
  269. bcp.MD5 = ""
  270. js, err := json.Marshal(bcp)
  271. if err != nil {
  272. return err
  273. }
  274. sum := md5.Sum(js)
  275. b64 := base64.StdEncoding.EncodeToString(sum[:])
  276. bcp.MD5 = b64
  277. // Serialization
  278. js, err = json.Marshal(bcp)
  279. if err != nil {
  280. return err
  281. }
  282. // Dump
  283. return ioutil.WriteFile(filePath, js, FilePermMode)
  284. }
  285. // updatePart updates the part status
  286. func (cp *uploadCheckpoint) updatePart(part UploadPart) {
  287. cp.Parts[part.PartNumber-1].Part = part
  288. cp.Parts[part.PartNumber-1].IsCompleted = true
  289. }
  290. // todoParts returns unfinished parts
  291. func (cp *uploadCheckpoint) todoParts() []FileChunk {
  292. fcs := []FileChunk{}
  293. for _, part := range cp.Parts {
  294. if !part.IsCompleted {
  295. fcs = append(fcs, part.Chunk)
  296. }
  297. }
  298. return fcs
  299. }
  300. // allParts returns all parts
  301. func (cp *uploadCheckpoint) allParts() []UploadPart {
  302. ps := []UploadPart{}
  303. for _, part := range cp.Parts {
  304. ps = append(ps, part.Part)
  305. }
  306. return ps
  307. }
  308. // getCompletedBytes returns completed bytes count
  309. func (cp *uploadCheckpoint) getCompletedBytes() int64 {
  310. var completedBytes int64
  311. for _, part := range cp.Parts {
  312. if part.IsCompleted {
  313. completedBytes += part.Chunk.Size
  314. }
  315. }
  316. return completedBytes
  317. }
  318. // calcFileMD5 calculates the MD5 for the specified local file
  319. func calcFileMD5(filePath string) (string, error) {
  320. return "", nil
  321. }
  322. // prepare initializes the multipart upload
  323. func prepare(cp *uploadCheckpoint, objectKey, filePath string, partSize int64, bucket *Bucket, options []Option) error {
  324. // CP
  325. cp.Magic = uploadCpMagic
  326. cp.FilePath = filePath
  327. cp.ObjectKey = objectKey
  328. // Local file
  329. fd, err := os.Open(filePath)
  330. if err != nil {
  331. return err
  332. }
  333. defer fd.Close()
  334. st, err := fd.Stat()
  335. if err != nil {
  336. return err
  337. }
  338. cp.FileStat.Size = st.Size()
  339. cp.FileStat.LastModified = st.ModTime()
  340. md, err := calcFileMD5(filePath)
  341. if err != nil {
  342. return err
  343. }
  344. cp.FileStat.MD5 = md
  345. // Chunks
  346. parts, err := SplitFileByPartSize(filePath, partSize)
  347. if err != nil {
  348. return err
  349. }
  350. cp.Parts = make([]cpPart, len(parts))
  351. for i, part := range parts {
  352. cp.Parts[i].Chunk = part
  353. cp.Parts[i].IsCompleted = false
  354. }
  355. // Init load
  356. imur, err := bucket.InitiateMultipartUpload(objectKey, options...)
  357. if err != nil {
  358. return err
  359. }
  360. cp.UploadID = imur.UploadID
  361. return nil
  362. }
  363. // complete completes the multipart upload and deletes the local CP files
  364. func complete(cp *uploadCheckpoint, bucket *Bucket, parts []UploadPart, cpFilePath string, options []Option) error {
  365. imur := InitiateMultipartUploadResult{Bucket: bucket.BucketName,
  366. Key: cp.ObjectKey, UploadID: cp.UploadID}
  367. _, err := bucket.CompleteMultipartUpload(imur, parts, options...)
  368. if err != nil {
  369. return err
  370. }
  371. os.Remove(cpFilePath)
  372. return err
  373. }
  374. // uploadFileWithCp handles concurrent upload with checkpoint
  375. func (bucket Bucket) uploadFileWithCp(objectKey, filePath string, partSize int64, options []Option, cpFilePath string, routines int) error {
  376. listener := getProgressListener(options)
  377. // Load CP data
  378. ucp := uploadCheckpoint{}
  379. err := ucp.load(cpFilePath)
  380. if err != nil {
  381. os.Remove(cpFilePath)
  382. }
  383. // Load error or the CP data is invalid.
  384. valid, err := ucp.isValid(filePath)
  385. if err != nil || !valid {
  386. if err = prepare(&ucp, objectKey, filePath, partSize, &bucket, options); err != nil {
  387. return err
  388. }
  389. os.Remove(cpFilePath)
  390. }
  391. chunks := ucp.todoParts()
  392. imur := InitiateMultipartUploadResult{
  393. Bucket: bucket.BucketName,
  394. Key: objectKey,
  395. UploadID: ucp.UploadID}
  396. jobs := make(chan FileChunk, len(chunks))
  397. results := make(chan UploadPart, len(chunks))
  398. failed := make(chan error)
  399. die := make(chan bool)
  400. completedBytes := ucp.getCompletedBytes()
  401. event := newProgressEvent(TransferStartedEvent, completedBytes, ucp.FileStat.Size)
  402. publishProgress(listener, event)
  403. // Start the workers
  404. arg := workerArg{&bucket, filePath, imur, options, uploadPartHooker}
  405. for w := 1; w <= routines; w++ {
  406. go worker(w, arg, jobs, results, failed, die)
  407. }
  408. // Schedule jobs
  409. go scheduler(jobs, chunks)
  410. // Waiting for the job finished
  411. completed := 0
  412. for completed < len(chunks) {
  413. select {
  414. case part := <-results:
  415. completed++
  416. ucp.updatePart(part)
  417. ucp.dump(cpFilePath)
  418. completedBytes += ucp.Parts[part.PartNumber-1].Chunk.Size
  419. event = newProgressEvent(TransferDataEvent, completedBytes, ucp.FileStat.Size)
  420. publishProgress(listener, event)
  421. case err := <-failed:
  422. close(die)
  423. event = newProgressEvent(TransferFailedEvent, completedBytes, ucp.FileStat.Size)
  424. publishProgress(listener, event)
  425. return err
  426. }
  427. if completed >= len(chunks) {
  428. break
  429. }
  430. }
  431. event = newProgressEvent(TransferCompletedEvent, completedBytes, ucp.FileStat.Size)
  432. publishProgress(listener, event)
  433. // Complete the multipart upload
  434. err = complete(&ucp, &bucket, ucp.allParts(), cpFilePath, options)
  435. return err
  436. }