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.

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