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