Debian Codegraph @

oss/multi.go

raw symbols SCIP
1 package oss
2
3 import (
4 "bytes"
5 "crypto/md5"
6 "encoding/base64"
7 "encoding/hex"
8 "encoding/xml"
9 "errors"
10 "io"
11 "time"
12 //"log"
13 "net/http"
14 "net/url"
15 "sort"
16 "strconv"
17 "strings"
18 )
19
20 // Multi represents an unfinished multipart upload.
21 //
22 // Multipart uploads allow sending big objects in smaller chunks.
23 // After all parts have been sent, the upload must be explicitly
24 // completed by calling Complete with the list of parts.
25
26 type Multi struct {
27 Bucket *Bucket
28 Key string
29 UploadId string
30 }
31
32 // That's the default. Here just for testing.
33 var listMultiMax = 1000
34
35 type listMultiResp struct {
36 NextKeyMarker string
37 NextUploadIdMarker string
38 IsTruncated bool
39 Upload []Multi
40 CommonPrefixes []string `xml:"CommonPrefixes>Prefix"`
41 }
42
43 // ListMulti returns the list of unfinished multipart uploads in b.
44 //
45 // The prefix parameter limits the response to keys that begin with the
46 // specified prefix. You can use prefixes to separate a bucket into different
47 // groupings of keys (to get the feeling of folders, for example).
48 //
49 // The delim parameter causes the response to group all of the keys that
50 // share a common prefix up to the next delimiter in a single entry within
51 // the CommonPrefixes field. You can use delimiters to separate a bucket
52 // into different groupings of keys, similar to how folders would work.
53 //
54 func (b *Bucket) ListMulti(prefix, delim string) (multis []*Multi, prefixes []string, err error) {
55 params := make(url.Values)
56 params.Set("uploads", "")
57 params.Set("max-uploads", strconv.FormatInt(int64(listMultiMax), 10))
58 params.Set("prefix", prefix)
59 params.Set("delimiter", delim)
60
61 for attempt := attempts.Start(); attempt.Next(); {
62 req := &request{
63 method: "GET",
64 bucket: b.Name,
65 params: params,
66 }
67 var resp listMultiResp
68 err := b.Client.query(req, &resp)
69 if shouldRetry(err) && attempt.HasNext() {
70 continue
71 }
72 if err != nil {
73 return nil, nil, err
74 }
75 for i := range resp.Upload {
76 multi := &resp.Upload[i]
77 multi.Bucket = b
78 multis = append(multis, multi)
79 }
80 prefixes = append(prefixes, resp.CommonPrefixes...)
81 if !resp.IsTruncated {
82 return multis, prefixes, nil
83 }
84 params.Set("key-marker", resp.NextKeyMarker)
85 params.Set("upload-id-marker", resp.NextUploadIdMarker)
86 attempt = attempts.Start() // Last request worked.
87 }
88 panic("unreachable")
89 }
90
91 // Multi returns a multipart upload handler for the provided key
92 // inside b. If a multipart upload exists for key, it is returned,
93 // otherwise a new multipart upload is initiated with contType and perm.
94 func (b *Bucket) Multi(key, contType string, perm ACL, options Options) (*Multi, error) {
95 multis, _, err := b.ListMulti(key, "")
96 if err != nil && !hasCode(err, "NoSuchUpload") {
97 return nil, err
98 }
99 for _, m := range multis {
100 if m.Key == key {
101 return m, nil
102 }
103 }
104 return b.InitMulti(key, contType, perm, options)
105 }
106
107 // InitMulti initializes a new multipart upload at the provided
108 // key inside b and returns a value for manipulating it.
109 //
110 //
111 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/multipart-upload&InitiateMultipartUpload
112 func (b *Bucket) InitMulti(key string, contType string, perm ACL, options Options) (*Multi, error) {
113 headers := make(http.Header)
114 headers.Set("Content-Length", "0")
115 headers.Set("Content-Type", contType)
116 headers.Set("x-oss-acl", string(perm))
117
118 options.addHeaders(headers)
119 params := make(url.Values)
120 params.Set("uploads", "")
121 req := &request{
122 method: "POST",
123 bucket: b.Name,
124 path: key,
125 headers: headers,
126 params: params,
127 }
128 var err error
129 var resp struct {
130 UploadId string `xml:"UploadId"`
131 }
132 for attempt := attempts.Start(); attempt.Next(); {
133 err = b.Client.query(req, &resp)
134 if !shouldRetry(err) {
135 break
136 }
137 }
138 if err != nil {
139 return nil, err
140 }
141 return &Multi{Bucket: b, Key: key, UploadId: resp.UploadId}, nil
142 }
143
144 func (m *Multi) PutPartCopy(n int, options CopyOptions, source string) (*CopyObjectResult, Part, error) {
145 return m.PutPartCopyWithContentLength(n, options, source, -1)
146 }
147
148 //
149 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/multipart-upload&UploadPartCopy
150 func (m *Multi) PutPartCopyWithContentLength(n int, options CopyOptions, source string, contentLength int64) (*CopyObjectResult, Part, error) {
151 // TODO source format a /BUCKET/PATH/TO/OBJECT
152 // TODO not a good design. API could be changed to PutPartCopyWithinBucket(..., path) and PutPartCopyFromBucket(bucket, path)
153
154 headers := make(http.Header)
155 headers.Set("x-oss-copy-source", source)
156
157 options.addHeaders(headers)
158 params := make(url.Values)
159 params.Set("uploadId", m.UploadId)
160 params.Set("partNumber", strconv.FormatInt(int64(n), 10))
161
162 if contentLength < 0 {
163 sourceBucket := m.Bucket.Client.Bucket(strings.TrimRight(strings.Split(source, "/")[1], "/"))
164 //log.Println("source: ", source)
165 //log.Println("sourceBucket: ", sourceBucket.Name)
166 //log.Println("HEAD: ", strings.strings.SplitAfterN(source, "/", 3)[2])
167 // TODO SplitAfterN can be use in bucket name
168 sourceMeta, err := sourceBucket.Head(strings.SplitAfterN(source, "/", 3)[2], nil)
169 if err != nil {
170 return nil, Part{}, err
171 }
172 contentLength = sourceMeta.ContentLength
173 }
174
175 for attempt := attempts.Start(); attempt.Next(); {
176 req := &request{
177 method: "PUT",
178 bucket: m.Bucket.Name,
179 path: m.Key,
180 headers: headers,
181 params: params,
182 }
183 resp := &CopyObjectResult{}
184 err := m.Bucket.Client.query(req, resp)
185 if shouldRetry(err) && attempt.HasNext() {
186 continue
187 }
188 if err != nil {
189 return nil, Part{}, err
190 }
191 if resp.ETag == "" {
192 return nil, Part{}, errors.New("part upload succeeded with no ETag")
193 }
194 return resp, Part{n, resp.ETag, contentLength}, nil
195 }
196 panic("unreachable")
197 }
198
199 // PutPart sends part n of the multipart upload, reading all the content from r.
200 // Each part, except for the last one, must be at least 5MB in size.
201 //
202 //
203 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/multipart-upload&UploadPart
204 func (m *Multi) PutPart(n int, r io.ReadSeeker) (Part, error) {
205 partSize, _, md5b64, err := seekerInfo(r)
206 if err != nil {
207 return Part{}, err
208 }
209 return m.putPart(n, r, partSize, md5b64, 0)
210 }
211
212 func (m *Multi) PutPartWithTimeout(n int, r io.ReadSeeker, timeout time.Duration) (Part, error) {
213 partSize, _, md5b64, err := seekerInfo(r)
214 if err != nil {
215 return Part{}, err
216 }
217 return m.putPart(n, r, partSize, md5b64, timeout)
218 }
219
220 func (m *Multi) putPart(n int, r io.ReadSeeker, partSize int64, md5b64 string, timeout time.Duration) (Part, error) {
221 headers := make(http.Header)
222 headers.Set("Content-Length", strconv.FormatInt(partSize, 10))
223 headers.Set("Content-MD5", md5b64)
224
225 params := make(url.Values)
226 params.Set("uploadId", m.UploadId)
227 params.Set("partNumber", strconv.FormatInt(int64(n), 10))
228
229 for attempt := attempts.Start(); attempt.Next(); {
230 _, err := r.Seek(0, 0)
231 if err != nil {
232 return Part{}, err
233 }
234 req := &request{
235 method: "PUT",
236 bucket: m.Bucket.Name,
237 path: m.Key,
238 headers: headers,
239 params: params,
240 payload: r,
241 timeout: timeout,
242 }
243 err = m.Bucket.Client.prepare(req)
244 if err != nil {
245 return Part{}, err
246 }
247 resp, err := m.Bucket.Client.run(req, nil)
248 if shouldRetry(err) && attempt.HasNext() {
249 continue
250 }
251 if err != nil {
252 return Part{}, err
253 }
254 etag := resp.Header.Get("ETag")
255 if etag == "" {
256 return Part{}, errors.New("part upload succeeded with no ETag")
257 }
258 return Part{n, etag, partSize}, nil
259 }
260 panic("unreachable")
261 }
262
263 func seekerInfo(r io.ReadSeeker) (size int64, md5hex string, md5b64 string, err error) {
264 _, err = r.Seek(0, 0)
265 if err != nil {
266 return 0, "", "", err
267 }
268 digest := md5.New()
269 size, err = io.Copy(digest, r)
270 if err != nil {
271 return 0, "", "", err
272 }
273 sum := digest.Sum(nil)
274 md5hex = hex.EncodeToString(sum)
275 md5b64 = base64.StdEncoding.EncodeToString(sum)
276 return size, md5hex, md5b64, nil
277 }
278
279 type Part struct {
280 N int `xml:"PartNumber"`
281 ETag string
282 Size int64
283 }
284
285 type partSlice []Part
286
287 func (s partSlice) Len() int { return len(s) }
288 func (s partSlice) Less(i, j int) bool { return s[i].N < s[j].N }
289 func (s partSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
290
291 type listPartsResp struct {
292 NextPartNumberMarker string
293 IsTruncated bool
294 Part []Part
295 }
296
297 // That's the default. Here just for testing.
298 var listPartsMax = 1000
299
300 // ListParts for backcompatability. See the documentation for ListPartsFull
301 func (m *Multi) ListParts() ([]Part, error) {
302 return m.ListPartsFull(0, listPartsMax)
303 }
304
305 // ListPartsFull returns the list of previously uploaded parts in m,
306 // ordered by part number (Only parts with higher part numbers than
307 // partNumberMarker will be listed). Only up to maxParts parts will be
308 // returned.
309 //
310 func (m *Multi) ListPartsFull(partNumberMarker int, maxParts int) ([]Part, error) {
311 if maxParts > listPartsMax {
312 maxParts = listPartsMax
313 }
314
315 params := make(url.Values)
316 params.Set("uploadId", m.UploadId)
317 params.Set("max-parts", strconv.FormatInt(int64(maxParts), 10))
318 params.Set("part-number-marker", strconv.FormatInt(int64(partNumberMarker), 10))
319
320 var parts partSlice
321 for attempt := attempts.Start(); attempt.Next(); {
322 req := &request{
323 method: "GET",
324 bucket: m.Bucket.Name,
325 path: m.Key,
326 params: params,
327 }
328 var resp listPartsResp
329 err := m.Bucket.Client.query(req, &resp)
330 if shouldRetry(err) && attempt.HasNext() {
331 continue
332 }
333 if err != nil {
334 return nil, err
335 }
336 parts = append(parts, resp.Part...)
337 if !resp.IsTruncated {
338 sort.Sort(parts)
339 return parts, nil
340 }
341 params.Set("part-number-marker", resp.NextPartNumberMarker)
342 attempt = attempts.Start() // Last request worked.
343 }
344 panic("unreachable")
345 }
346
347 type ReaderAtSeeker interface {
348 io.ReaderAt
349 io.ReadSeeker
350 }
351
352 // PutAll sends all of r via a multipart upload with parts no larger
353 // than partSize bytes, which must be set to at least 5MB.
354 // Parts previously uploaded are either reused if their checksum
355 // and size match the new part, or otherwise overwritten with the
356 // new content.
357 // PutAll returns all the parts of m (reused or not).
358 func (m *Multi) PutAll(r ReaderAtSeeker, partSize int64) ([]Part, error) {
359 old, err := m.ListParts()
360 if err != nil && !hasCode(err, "NoSuchUpload") {
361 return nil, err
362 }
363 reuse := 0 // Index of next old part to consider reusing.
364 current := 1 // Part number of latest good part handled.
365 totalSize, err := r.Seek(0, 2)
366 if err != nil {
367 return nil, err
368 }
369 first := true // Must send at least one empty part if the file is empty.
370 var result []Part
371 NextSection:
372 for offset := int64(0); offset < totalSize || first; offset += partSize {
373 first = false
374 if offset+partSize > totalSize {
375 partSize = totalSize - offset
376 }
377 section := io.NewSectionReader(r, offset, partSize)
378 _, md5hex, md5b64, err := seekerInfo(section)
379 if err != nil {
380 return nil, err
381 }
382 for reuse < len(old) && old[reuse].N <= current {
383 // Looks like this part was already sent.
384 part := &old[reuse]
385 etag := `"` + md5hex + `"`
386 if part.N == current && part.Size == partSize && part.ETag == etag {
387 // Checksum matches. Reuse the old part.
388 result = append(result, *part)
389 current++
390 continue NextSection
391 }
392 reuse++
393 }
394
395 // Part wasn't found or doesn't match. Send it.
396 part, err := m.putPart(current, section, partSize, md5b64, 0)
397 if err != nil {
398 return nil, err
399 }
400 result = append(result, part)
401 current++
402 }
403 return result, nil
404 }
405
406 type completeUpload struct {
407 XMLName xml.Name `xml:"CompleteMultipartUpload"`
408 Parts completeParts `xml:"Part"`
409 }
410
411 type completePart struct {
412 PartNumber int
413 ETag string
414 }
415
416 type completeParts []completePart
417
418 func (p completeParts) Len() int { return len(p) }
419 func (p completeParts) Less(i, j int) bool { return p[i].PartNumber < p[j].PartNumber }
420 func (p completeParts) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
421
422 // Complete assembles the given previously uploaded parts into the
423 // final object. This operation may take several minutes.
424 //
425 func (m *Multi) Complete(parts []Part) error {
426 params := make(url.Values)
427 params.Set("uploadId", m.UploadId)
428
429 c := completeUpload{}
430 for _, p := range parts {
431 c.Parts = append(c.Parts, completePart{p.N, p.ETag})
432 }
433 sort.Sort(c.Parts)
434 data, err := xml.Marshal(&c)
435 if err != nil {
436 return err
437 }
438 for attempt := attempts.Start(); attempt.Next(); {
439 req := &request{
440 method: "POST",
441 bucket: m.Bucket.Name,
442 path: m.Key,
443 params: params,
444 payload: bytes.NewReader(data),
445 }
446 err := m.Bucket.Client.query(req, nil)
447 if shouldRetry(err) && attempt.HasNext() {
448 continue
449 }
450 return err
451 }
452 panic("unreachable")
453 }
454
455 // Abort deletes an unifinished multipart upload and any previously
456 // uploaded parts for it.
457 //
458 // After a multipart upload is aborted, no additional parts can be
459 // uploaded using it. However, if any part uploads are currently in
460 // progress, those part uploads might or might not succeed. As a result,
461 // it might be necessary to abort a given multipart upload multiple
462 // times in order to completely free all storage consumed by all parts.
463 //
464 // NOTE: If the described scenario happens to you, please report back to
465 // the goamz authors with details. In the future such retrying should be
466 // handled internally, but it's not clear what happens precisely (Is an
467 // error returned? Is the issue completely undetectable?).
468 //
469 //
470 // You can read doc at http://docs.aliyun.com/#/pub/oss/api-reference/multipart-upload&AbortMultipartUpload
471 func (m *Multi) Abort() error {
472 params := make(url.Values)
473 params.Set("uploadId", m.UploadId)
474
475 for attempt := attempts.Start(); attempt.Next(); {
476 req := &request{
477 method: "DELETE",
478 bucket: m.Bucket.Name,
479 path: m.Key,
480 params: params,
481 }
482 err := m.Bucket.Client.query(req, nil)
483 if shouldRetry(err) && attempt.HasNext() {
484 continue
485 }
486 return err
487 }
488 panic("unreachable")
489 }