You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

515 lines
18 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package cos
  2. import (
  3. "context"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "sort"
  11. "strings"
  12. )
  13. // InitiateMultipartUploadOptions is the option of InitateMultipartUpload
  14. type InitiateMultipartUploadOptions struct {
  15. *ACLHeaderOptions
  16. *ObjectPutHeaderOptions
  17. }
  18. // InitiateMultipartUploadResult is the result of InitateMultipartUpload
  19. type InitiateMultipartUploadResult struct {
  20. XMLName xml.Name `xml:"InitiateMultipartUploadResult"`
  21. Bucket string
  22. Key string
  23. UploadID string `xml:"UploadId"`
  24. }
  25. // InitiateMultipartUpload 请求实现初始化分片上传,成功执行此请求以后会返回Upload ID用于后续的Upload Part请求。
  26. //
  27. // https://www.qcloud.com/document/product/436/7746
  28. func (s *ObjectService) InitiateMultipartUpload(ctx context.Context, name string, opt *InitiateMultipartUploadOptions) (*InitiateMultipartUploadResult, *Response, error) {
  29. var res InitiateMultipartUploadResult
  30. sendOpt := sendOptions{
  31. baseURL: s.client.BaseURL.BucketURL,
  32. uri: "/" + encodeURIComponent(name) + "?uploads",
  33. method: http.MethodPost,
  34. optHeader: opt,
  35. result: &res,
  36. }
  37. resp, err := s.client.send(ctx, &sendOpt)
  38. return &res, resp, err
  39. }
  40. // ObjectUploadPartOptions is the options of upload-part
  41. type ObjectUploadPartOptions struct {
  42. Expect string `header:"Expect,omitempty" url:"-"`
  43. XCosContentSHA1 string `header:"x-cos-content-sha1,omitempty" url:"-"`
  44. ContentLength int `header:"Content-Length,omitempty" url:"-"`
  45. ContentMD5 string `header:"Content-MD5,omitempty" url:"-"`
  46. XCosSSECustomerAglo string `header:"x-cos-server-side-encryption-customer-algorithm,omitempty" url:"-" xml:"-"`
  47. XCosSSECustomerKey string `header:"x-cos-server-side-encryption-customer-key,omitempty" url:"-" xml:"-"`
  48. XCosSSECustomerKeyMD5 string `header:"x-cos-server-side-encryption-customer-key-MD5,omitempty" url:"-" xml:"-"`
  49. XCosTrafficLimit int `header:"x-cos-traffic-limit,omitempty" url:"-" xml:"-"`
  50. XOptionHeader *http.Header `header:"-,omitempty" url:"-" xml:"-"`
  51. // 上传进度, ProgressCompleteEvent不能表示对应API调用成功,API是否调用成功的判断标准为返回err==nil
  52. Listener ProgressListener `header:"-" url:"-" xml:"-"`
  53. }
  54. // UploadPart 请求实现在初始化以后的分块上传,支持的块的数量为1到10000,块的大小为1 MB 到5 GB。
  55. // 在每次请求Upload Part时候,需要携带partNumber和uploadID,partNumber为块的编号,支持乱序上传。
  56. //
  57. // 当传入uploadID和partNumber都相同的时候,后传入的块将覆盖之前传入的块。当uploadID不存在时会返回404错误,NoSuchUpload.
  58. //
  59. // 当 r 不是 bytes.Buffer/bytes.Reader/strings.Reader 时,必须指定 opt.ContentLength
  60. //
  61. // https://www.qcloud.com/document/product/436/7750
  62. func (s *ObjectService) UploadPart(ctx context.Context, name, uploadID string, partNumber int, r io.Reader, opt *ObjectUploadPartOptions) (*Response, error) {
  63. if err := CheckReaderLen(r); err != nil {
  64. return nil, err
  65. }
  66. if opt != nil && opt.Listener != nil {
  67. totalBytes, err := GetReaderLen(r)
  68. if err != nil {
  69. return nil, err
  70. }
  71. r = TeeReader(r, nil, totalBytes, opt.Listener)
  72. }
  73. u := fmt.Sprintf("/%s?partNumber=%d&uploadId=%s", encodeURIComponent(name), partNumber, uploadID)
  74. sendOpt := sendOptions{
  75. baseURL: s.client.BaseURL.BucketURL,
  76. uri: u,
  77. method: http.MethodPut,
  78. optHeader: opt,
  79. body: r,
  80. }
  81. resp, err := s.client.send(ctx, &sendOpt)
  82. return resp, err
  83. }
  84. // ObjectListPartsOptions is the option of ListParts
  85. type ObjectListPartsOptions struct {
  86. EncodingType string `url:"Encoding-type,omitempty"`
  87. MaxParts string `url:"max-parts,omitempty"`
  88. PartNumberMarker string `url:"part-number-marker,omitempty"`
  89. }
  90. // ObjectListPartsResult is the result of ListParts
  91. type ObjectListPartsResult struct {
  92. XMLName xml.Name `xml:"ListPartsResult"`
  93. Bucket string
  94. EncodingType string `xml:"Encoding-type,omitempty"`
  95. Key string
  96. UploadID string `xml:"UploadId"`
  97. Initiator *Initiator `xml:"Initiator,omitempty"`
  98. Owner *Owner `xml:"Owner,omitempty"`
  99. StorageClass string
  100. PartNumberMarker string
  101. NextPartNumberMarker string `xml:"NextPartNumberMarker,omitempty"`
  102. MaxParts string
  103. IsTruncated bool
  104. Parts []Object `xml:"Part,omitempty"`
  105. }
  106. // ListParts 用来查询特定分块上传中的已上传的块。
  107. //
  108. // https://www.qcloud.com/document/product/436/7747
  109. func (s *ObjectService) ListParts(ctx context.Context, name, uploadID string, opt *ObjectListPartsOptions) (*ObjectListPartsResult, *Response, error) {
  110. u := fmt.Sprintf("/%s?uploadId=%s", encodeURIComponent(name), uploadID)
  111. var res ObjectListPartsResult
  112. sendOpt := sendOptions{
  113. baseURL: s.client.BaseURL.BucketURL,
  114. uri: u,
  115. method: http.MethodGet,
  116. result: &res,
  117. optQuery: opt,
  118. }
  119. resp, err := s.client.send(ctx, &sendOpt)
  120. return &res, resp, err
  121. }
  122. // CompleteMultipartUploadOptions is the option of CompleteMultipartUpload
  123. type CompleteMultipartUploadOptions struct {
  124. XMLName xml.Name `xml:"CompleteMultipartUpload" header:"-" url:"-"`
  125. Parts []Object `xml:"Part" header:"-" url:"-"`
  126. XOptionHeader *http.Header `header:"-,omitempty" xml:"-" url:"-"`
  127. }
  128. // CompleteMultipartUploadResult is the result CompleteMultipartUpload
  129. type CompleteMultipartUploadResult struct {
  130. XMLName xml.Name `xml:"CompleteMultipartUploadResult"`
  131. Location string
  132. Bucket string
  133. Key string
  134. ETag string
  135. }
  136. // ObjectList can used for sort the parts which needs in complete upload part
  137. // sort.Sort(cos.ObjectList(opt.Parts))
  138. type ObjectList []Object
  139. func (o ObjectList) Len() int {
  140. return len(o)
  141. }
  142. func (o ObjectList) Swap(i, j int) {
  143. o[i], o[j] = o[j], o[i]
  144. }
  145. func (o ObjectList) Less(i, j int) bool { // rewrite the Less method from small to big
  146. return o[i].PartNumber < o[j].PartNumber
  147. }
  148. // CompleteMultipartUpload 用来实现完成整个分块上传。当您已经使用Upload Parts上传所有块以后,你可以用该API完成上传。
  149. // 在使用该API时,您必须在Body中给出每一个块的PartNumber和ETag,用来校验块的准确性。
  150. //
  151. // 由于分块上传的合并需要数分钟时间,因而当合并分块开始的时候,COS就立即返回200的状态码,在合并的过程中,
  152. // COS会周期性的返回空格信息来保持连接活跃,直到合并完成,COS会在Body中返回合并后块的内容。
  153. //
  154. // 当上传块小于1 MB的时候,在调用该请求时,会返回400 EntityTooSmall;
  155. // 当上传块编号不连续的时候,在调用该请求时,会返回400 InvalidPart;
  156. // 当请求Body中的块信息没有按序号从小到大排列的时候,在调用该请求时,会返回400 InvalidPartOrder;
  157. // 当UploadId不存在的时候,在调用该请求时,会返回404 NoSuchUpload。
  158. //
  159. // 建议您及时完成分块上传或者舍弃分块上传,因为已上传但是未终止的块会占用存储空间进而产生存储费用。
  160. //
  161. // https://www.qcloud.com/document/product/436/7742
  162. func (s *ObjectService) CompleteMultipartUpload(ctx context.Context, name, uploadID string, opt *CompleteMultipartUploadOptions) (*CompleteMultipartUploadResult, *Response, error) {
  163. u := fmt.Sprintf("/%s?uploadId=%s", encodeURIComponent(name), uploadID)
  164. var res CompleteMultipartUploadResult
  165. sendOpt := sendOptions{
  166. baseURL: s.client.BaseURL.BucketURL,
  167. uri: u,
  168. method: http.MethodPost,
  169. optHeader: opt,
  170. body: opt,
  171. result: &res,
  172. }
  173. resp, err := s.client.send(ctx, &sendOpt)
  174. // If the error occurs during the copy operation, the error response is embedded in the 200 OK response. This means that a 200 OK response can contain either a success or an error.
  175. if err == nil && resp.StatusCode == 200 {
  176. if res.ETag == "" {
  177. return &res, resp, errors.New("response 200 OK, but body contains an error")
  178. }
  179. }
  180. return &res, resp, err
  181. }
  182. // AbortMultipartUpload 用来实现舍弃一个分块上传并删除已上传的块。当您调用Abort Multipart Upload时,
  183. // 如果有正在使用这个Upload Parts上传块的请求,则Upload Parts会返回失败。当该UploadID不存在时,会返回404 NoSuchUpload。
  184. //
  185. // 建议您及时完成分块上传或者舍弃分块上传,因为已上传但是未终止的块会占用存储空间进而产生存储费用。
  186. //
  187. // https://www.qcloud.com/document/product/436/7740
  188. func (s *ObjectService) AbortMultipartUpload(ctx context.Context, name, uploadID string) (*Response, error) {
  189. u := fmt.Sprintf("/%s?uploadId=%s", encodeURIComponent(name), uploadID)
  190. sendOpt := sendOptions{
  191. baseURL: s.client.BaseURL.BucketURL,
  192. uri: u,
  193. method: http.MethodDelete,
  194. }
  195. resp, err := s.client.send(ctx, &sendOpt)
  196. return resp, err
  197. }
  198. // ObjectCopyPartOptions is the options of copy-part
  199. type ObjectCopyPartOptions struct {
  200. XCosCopySource string `header:"x-cos-copy-source" url:"-"`
  201. XCosCopySourceRange string `header:"x-cos-copy-source-range,omitempty" url:"-"`
  202. XCosCopySourceIfModifiedSince string `header:"x-cos-copy-source-If-Modified-Since,omitempty" url:"-"`
  203. XCosCopySourceIfUnmodifiedSince string `header:"x-cos-copy-source-If-Unmodified-Since,omitempty" url:"-"`
  204. XCosCopySourceIfMatch string `header:"x-cos-copy-source-If-Match,omitempty" url:"-"`
  205. XCosCopySourceIfNoneMatch string `header:"x-cos-copy-source-If-None-Match,omitempty" url:"-"`
  206. }
  207. // CopyPartResult is the result CopyPart
  208. type CopyPartResult struct {
  209. XMLName xml.Name `xml:"CopyPartResult"`
  210. ETag string
  211. LastModified string
  212. }
  213. // CopyPart 请求实现在初始化以后的分块上传,支持的块的数量为1到10000,块的大小为1 MB 到5 GB。
  214. // 在每次请求Upload Part时候,需要携带partNumber和uploadID,partNumber为块的编号,支持乱序上传。
  215. // ObjectCopyPartOptions的XCosCopySource为必填参数,格式为<bucket-name>-<app-id>.cos.<region-id>.myqcloud.com/<object-key>
  216. // ObjectCopyPartOptions的XCosCopySourceRange指定源的Range,格式为bytes=<start>-<end>
  217. //
  218. // 当传入uploadID和partNumber都相同的时候,后传入的块将覆盖之前传入的块。当uploadID不存在时会返回404错误,NoSuchUpload.
  219. //
  220. // https://www.qcloud.com/document/product/436/7750
  221. func (s *ObjectService) CopyPart(ctx context.Context, name, uploadID string, partNumber int, sourceURL string, opt *ObjectCopyPartOptions) (*CopyPartResult, *Response, error) {
  222. if opt == nil {
  223. opt = &ObjectCopyPartOptions{}
  224. }
  225. opt.XCosCopySource = sourceURL
  226. u := fmt.Sprintf("/%s?partNumber=%d&uploadId=%s", encodeURIComponent(name), partNumber, uploadID)
  227. var res CopyPartResult
  228. sendOpt := sendOptions{
  229. baseURL: s.client.BaseURL.BucketURL,
  230. uri: u,
  231. method: http.MethodPut,
  232. optHeader: opt,
  233. result: &res,
  234. }
  235. resp, err := s.client.send(ctx, &sendOpt)
  236. // If the error occurs during the copy operation, the error response is embedded in the 200 OK response. This means that a 200 OK response can contain either a success or an error.
  237. if err == nil && resp != nil && resp.StatusCode == 200 {
  238. if res.ETag == "" {
  239. return &res, resp, errors.New("response 200 OK, but body contains an error")
  240. }
  241. }
  242. return &res, resp, err
  243. }
  244. type ObjectListUploadsOptions struct {
  245. Delimiter string `url:"Delimiter,omitempty"`
  246. EncodingType string `url:"EncodingType,omitempty"`
  247. Prefix string `url:"Prefix"`
  248. MaxUploads int `url:"MaxUploads"`
  249. KeyMarker string `url:"KeyMarker"`
  250. UploadIdMarker string `url:"UploadIDMarker"`
  251. }
  252. type ObjectListUploadsResult struct {
  253. XMLName xml.Name `xml:"ListMultipartUploadsResult"`
  254. Bucket string `xml:"Bucket,omitempty"`
  255. EncodingType string `xml:"Encoding-Type,omitempty"`
  256. KeyMarker string `xml:"KeyMarker,omitempty"`
  257. UploadIdMarker string `xml:"UploadIdMarker,omitempty"`
  258. NextKeyMarker string `xml:"NextKeyMarker,omitempty"`
  259. NextUploadIdMarker string `xml:"NextUploadIdMarker,omitempty"`
  260. MaxUploads string `xml:"MaxUploads,omitempty"`
  261. IsTruncated bool `xml:"IsTruncated,omitempty"`
  262. Prefix string `xml:"Prefix,omitempty"`
  263. Delimiter string `xml:"Delimiter,omitempty"`
  264. Upload []ListUploadsResultUpload `xml:"Upload,omitempty"`
  265. CommonPrefixes []string `xml:"CommonPrefixes>Prefix,omitempty"`
  266. }
  267. type ListUploadsResultUpload struct {
  268. Key string `xml:"Key,omitempty"`
  269. UploadID string `xml:"UploadId,omitempty"`
  270. StorageClass string `xml:"StorageClass,omitempty"`
  271. Initiator *Initiator `xml:"Initiator,omitempty"`
  272. Owner *Owner `xml:"Owner,omitempty"`
  273. Initiated string `xml:"Initiated,omitempty"`
  274. }
  275. func (s *ObjectService) ListUploads(ctx context.Context, opt *ObjectListUploadsOptions) (*ObjectListUploadsResult, *Response, error) {
  276. var res ObjectListUploadsResult
  277. sendOpt := &sendOptions{
  278. baseURL: s.client.BaseURL.BucketURL,
  279. uri: "/?uploads",
  280. method: http.MethodGet,
  281. optQuery: opt,
  282. result: &res,
  283. }
  284. resp, err := s.client.send(ctx, sendOpt)
  285. return &res, resp, err
  286. }
  287. type MultiCopyOptions struct {
  288. OptCopy *ObjectCopyOptions
  289. PartSize int64
  290. ThreadPoolSize int
  291. }
  292. type CopyJobs struct {
  293. Name string
  294. UploadId string
  295. RetryTimes int
  296. Chunk Chunk
  297. Opt *ObjectCopyPartOptions
  298. }
  299. type CopyResults struct {
  300. PartNumber int
  301. Resp *Response
  302. err error
  303. res *CopyPartResult
  304. }
  305. func copyworker(s *ObjectService, jobs <-chan *CopyJobs, results chan<- *CopyResults) {
  306. for j := range jobs {
  307. var copyres CopyResults
  308. j.Opt.XCosCopySourceRange = fmt.Sprintf("bytes=%d-%d", j.Chunk.OffSet, j.Chunk.OffSet+j.Chunk.Size-1)
  309. rt := j.RetryTimes
  310. for {
  311. res, resp, err := s.CopyPart(context.Background(), j.Name, j.UploadId, j.Chunk.Number, j.Opt.XCosCopySource, j.Opt)
  312. copyres.PartNumber = j.Chunk.Number
  313. copyres.Resp = resp
  314. copyres.err = err
  315. copyres.res = res
  316. if err != nil {
  317. rt--
  318. if rt == 0 {
  319. results <- &copyres
  320. break
  321. }
  322. continue
  323. }
  324. results <- &copyres
  325. break
  326. }
  327. }
  328. }
  329. func (s *ObjectService) innerHead(ctx context.Context, sourceURL string, opt *ObjectHeadOptions, id []string) (resp *Response, err error) {
  330. surl := strings.SplitN(sourceURL, "/", 2)
  331. if len(surl) < 2 {
  332. err = errors.New(fmt.Sprintf("sourceURL format error: %s", sourceURL))
  333. return
  334. }
  335. u, err := url.Parse(fmt.Sprintf("https://%s", surl[0]))
  336. if err != nil {
  337. return
  338. }
  339. b := &BaseURL{BucketURL: u}
  340. client := NewClient(b, &http.Client{
  341. Transport: s.client.client.Transport,
  342. })
  343. if len(id) > 0 {
  344. resp, err = client.Object.Head(ctx, surl[1], nil, id[0])
  345. } else {
  346. resp, err = client.Object.Head(ctx, surl[1], nil)
  347. }
  348. return
  349. }
  350. func SplitCopyFileIntoChunks(totalBytes int64, partSize int64) ([]Chunk, int, error) {
  351. var partNum int64
  352. if partSize > 0 {
  353. partSize = partSize * 1024 * 1024
  354. partNum = totalBytes / partSize
  355. if partNum >= 10000 {
  356. return nil, 0, errors.New("Too many parts, out of 10000")
  357. }
  358. } else {
  359. partNum, partSize = DividePart(totalBytes, 64)
  360. }
  361. var chunks []Chunk
  362. var chunk = Chunk{}
  363. for i := int64(0); i < partNum; i++ {
  364. chunk.Number = int(i + 1)
  365. chunk.OffSet = i * partSize
  366. chunk.Size = partSize
  367. chunks = append(chunks, chunk)
  368. }
  369. if totalBytes%partSize > 0 {
  370. chunk.Number = len(chunks) + 1
  371. chunk.OffSet = int64(len(chunks)) * partSize
  372. chunk.Size = totalBytes % partSize
  373. chunks = append(chunks, chunk)
  374. partNum++
  375. }
  376. return chunks, int(partNum), nil
  377. }
  378. func (s *ObjectService) MultiCopy(ctx context.Context, name string, sourceURL string, opt *MultiCopyOptions, id ...string) (*ObjectCopyResult, *Response, error) {
  379. resp, err := s.innerHead(ctx, sourceURL, nil, id)
  380. if err != nil {
  381. return nil, nil, err
  382. }
  383. totalBytes := resp.ContentLength
  384. surl := strings.SplitN(sourceURL, "/", 2)
  385. if len(surl) < 2 {
  386. return nil, nil, errors.New(fmt.Sprintf("x-cos-copy-source format error: %s", sourceURL))
  387. }
  388. var u string
  389. if len(id) == 1 {
  390. u = fmt.Sprintf("%s/%s?versionId=%s", surl[0], encodeURIComponent(surl[1]), id[0])
  391. } else if len(id) == 0 {
  392. u = fmt.Sprintf("%s/%s", surl[0], encodeURIComponent(surl[1]))
  393. } else {
  394. return nil, nil, errors.New("wrong params")
  395. }
  396. if opt == nil {
  397. opt = &MultiCopyOptions{}
  398. }
  399. chunks, partNum, err := SplitCopyFileIntoChunks(totalBytes, opt.PartSize)
  400. if err != nil {
  401. return nil, nil, err
  402. }
  403. if partNum == 0 || totalBytes < singleUploadMaxLength {
  404. if len(id) > 0 {
  405. return s.Copy(ctx, name, sourceURL, opt.OptCopy, id[0])
  406. } else {
  407. return s.Copy(ctx, name, sourceURL, opt.OptCopy)
  408. }
  409. }
  410. optini := CopyOptionsToMulti(opt.OptCopy)
  411. var uploadID string
  412. res, _, err := s.InitiateMultipartUpload(ctx, name, optini)
  413. if err != nil {
  414. return nil, nil, err
  415. }
  416. uploadID = res.UploadID
  417. var poolSize int
  418. if opt.ThreadPoolSize > 0 {
  419. poolSize = opt.ThreadPoolSize
  420. } else {
  421. poolSize = 1
  422. }
  423. chjobs := make(chan *CopyJobs, 100)
  424. chresults := make(chan *CopyResults, 10000)
  425. optcom := &CompleteMultipartUploadOptions{}
  426. for w := 1; w <= poolSize; w++ {
  427. go copyworker(s, chjobs, chresults)
  428. }
  429. go func() {
  430. for _, chunk := range chunks {
  431. partOpt := &ObjectCopyPartOptions{
  432. XCosCopySource: u,
  433. }
  434. job := &CopyJobs{
  435. Name: name,
  436. RetryTimes: 3,
  437. UploadId: uploadID,
  438. Chunk: chunk,
  439. Opt: partOpt,
  440. }
  441. chjobs <- job
  442. }
  443. close(chjobs)
  444. }()
  445. err = nil
  446. for i := 0; i < partNum; i++ {
  447. res := <-chresults
  448. if res.res == nil || res.err != nil {
  449. err = fmt.Errorf("UploadID %s, part %d failed to get resp content. error: %s", uploadID, res.PartNumber, res.err.Error())
  450. break
  451. }
  452. etag := res.res.ETag
  453. optcom.Parts = append(optcom.Parts, Object{
  454. PartNumber: res.PartNumber, ETag: etag},
  455. )
  456. }
  457. close(chresults)
  458. if err != nil {
  459. return nil, nil, err
  460. }
  461. sort.Sort(ObjectList(optcom.Parts))
  462. v, resp, err := s.CompleteMultipartUpload(ctx, name, uploadID, optcom)
  463. if err != nil {
  464. s.AbortMultipartUpload(ctx, name, uploadID)
  465. }
  466. cpres := &ObjectCopyResult{
  467. ETag: v.ETag,
  468. CRC64: resp.Header.Get("x-cos-hash-crc64ecma"),
  469. VersionId: resp.Header.Get("x-cos-version-id"),
  470. }
  471. return cpres, resp, err
  472. }