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.

507 lines
18 KiB

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