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.

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