1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.curoverse.com/arvados.git/sdk/go/arvados"
24 "github.com/AdRoll/goamz/aws"
25 "github.com/AdRoll/goamz/s3"
29 s3DefaultReadTimeout = arvados.Duration(10 * time.Minute)
30 s3DefaultConnectTimeout = arvados.Duration(time.Minute)
34 // ErrS3TrashDisabled is returned by Trash if that operation
35 // is impossible with the current config.
36 ErrS3TrashDisabled = fmt.Errorf("trash function is disabled because -trash-lifetime=0 and -s3-unsafe-delete=false")
38 s3AccessKeyFile string
39 s3SecretKeyFile string
44 s3RaceWindow time.Duration
52 maxClockSkew = 600 * time.Second
53 nearlyRFC1123 = "Mon, 2 Jan 2006 15:04:05 GMT"
56 type s3VolumeAdder struct {
60 // String implements flag.Value
61 func (s *s3VolumeAdder) String() string {
65 func (s *s3VolumeAdder) Set(bucketName string) error {
67 return fmt.Errorf("no container name given")
69 if s3AccessKeyFile == "" || s3SecretKeyFile == "" {
70 return fmt.Errorf("-s3-access-key-file and -s3-secret-key-file arguments must given before -s3-bucket-volume")
72 if deprecated.flagSerializeIO {
73 log.Print("Notice: -serialize is not supported by s3-bucket volumes.")
75 s.Config.Volumes = append(s.Config.Volumes, &S3Volume{
77 AccessKeyFile: s3AccessKeyFile,
78 SecretKeyFile: s3SecretKeyFile,
81 RaceWindow: arvados.Duration(s3RaceWindow),
82 S3Replication: s3Replication,
83 UnsafeDelete: s3UnsafeDelete,
84 ReadOnly: deprecated.flagReadonly,
90 func s3regions() (okList []string) {
91 for r := range aws.Regions {
92 okList = append(okList, r)
98 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &S3Volume{} })
100 flag.Var(&s3VolumeAdder{theConfig},
102 "Use the given bucket as a storage volume. Can be given multiple times.")
107 fmt.Sprintf("AWS region used for subsequent -s3-bucket-volume arguments. Allowed values are %+q.", s3regions()))
112 "Endpoint URL used for subsequent -s3-bucket-volume arguments. If blank, use the AWS endpoint corresponding to the -s3-region argument. For Google Storage, use \"https://storage.googleapis.com\".")
115 "s3-access-key-file",
117 "`File` containing the access key used for subsequent -s3-bucket-volume arguments.")
120 "s3-secret-key-file",
122 "`File` containing the secret key used for subsequent -s3-bucket-volume arguments.")
127 "Maximum eventual consistency latency for subsequent -s3-bucket-volume arguments.")
132 "Replication level reported to clients for subsequent -s3-bucket-volume arguments.")
137 "EXPERIMENTAL. Enable deletion (garbage collection) even when trash lifetime is zero, even though there are known race conditions that can cause data loss.")
140 // S3Volume implements Volume using an S3 bucket.
141 type S3Volume struct {
147 LocationConstraint bool
150 ConnectTimeout arvados.Duration
151 ReadTimeout arvados.Duration
152 RaceWindow arvados.Duration
161 // Examples implements VolumeWithExamples.
162 func (*S3Volume) Examples() []Volume {
165 AccessKeyFile: "/etc/aws_s3_access_key.txt",
166 SecretKeyFile: "/etc/aws_s3_secret_key.txt",
169 Bucket: "example-bucket-name",
172 RaceWindow: arvados.Duration(24 * time.Hour),
173 ConnectTimeout: arvados.Duration(time.Minute),
174 ReadTimeout: arvados.Duration(5 * time.Minute),
177 AccessKeyFile: "/etc/gce_s3_access_key.txt",
178 SecretKeyFile: "/etc/gce_s3_secret_key.txt",
179 Endpoint: "https://storage.googleapis.com",
181 Bucket: "example-bucket-name",
184 RaceWindow: arvados.Duration(24 * time.Hour),
185 ConnectTimeout: arvados.Duration(time.Minute),
186 ReadTimeout: arvados.Duration(5 * time.Minute),
191 // Type implements Volume.
192 func (*S3Volume) Type() string {
196 // Start populates private fields and verifies the configuration is
198 func (v *S3Volume) Start() error {
199 region, ok := aws.Regions[v.Region]
200 if v.Endpoint == "" {
202 return fmt.Errorf("unrecognized region %+q; try specifying -s3-endpoint instead", v.Region)
205 return fmt.Errorf("refusing to use AWS region name %+q with endpoint %+q; "+
206 "specify empty endpoint (\"-s3-endpoint=\") or use a different region name", v.Region, v.Endpoint)
210 S3Endpoint: v.Endpoint,
211 S3LocationConstraint: v.LocationConstraint,
217 auth.AccessKey, err = readKeyFromFile(v.AccessKeyFile)
221 auth.SecretKey, err = readKeyFromFile(v.SecretKeyFile)
226 // Zero timeouts mean "wait forever", which is a bad
227 // default. Default to long timeouts instead.
228 if v.ConnectTimeout == 0 {
229 v.ConnectTimeout = s3DefaultConnectTimeout
231 if v.ReadTimeout == 0 {
232 v.ReadTimeout = s3DefaultReadTimeout
235 client := s3.New(auth, region)
236 client.ConnectTimeout = time.Duration(v.ConnectTimeout)
237 client.ReadTimeout = time.Duration(v.ReadTimeout)
238 v.bucket = &s3bucket{
247 // DeviceID returns a globally unique ID for the storage bucket.
248 func (v *S3Volume) DeviceID() string {
249 return "s3://" + v.Endpoint + "/" + v.Bucket
252 func (v *S3Volume) getReaderWithContext(ctx context.Context, loc string) (rdr io.ReadCloser, err error) {
253 ready := make(chan bool)
255 rdr, err = v.getReader(loc)
262 theConfig.debugLogf("s3: abandoning getReader(): %s", ctx.Err())
269 return nil, ctx.Err()
273 // getReader wraps (Bucket)GetReader.
275 // In situations where (Bucket)GetReader would fail because the block
276 // disappeared in a Trash race, getReader calls fixRace to recover the
277 // data, and tries again.
278 func (v *S3Volume) getReader(loc string) (rdr io.ReadCloser, err error) {
279 rdr, err = v.bucket.GetReader(loc)
280 err = v.translateError(err)
281 if err == nil || !os.IsNotExist(err) {
285 _, err = v.bucket.Head("recent/"+loc, nil)
286 err = v.translateError(err)
288 // If we can't read recent/X, there's no point in
289 // trying fixRace. Give up.
297 rdr, err = v.bucket.GetReader(loc)
299 log.Printf("warning: reading %s after successful fixRace: %s", loc, err)
300 err = v.translateError(err)
305 // Get a block: copy the block data into buf, and return the number of
307 func (v *S3Volume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
308 rdr, err := v.getReaderWithContext(ctx, loc)
314 ready := make(chan bool)
319 n, err = io.ReadFull(rdr, buf)
322 case nil, io.EOF, io.ErrUnexpectedEOF:
325 err = v.translateError(err)
330 theConfig.debugLogf("s3: interrupting ReadFull() with Close() because %s", ctx.Err())
332 // Must wait for ReadFull to return, to ensure it
333 // doesn't write to buf after we return.
334 theConfig.debugLogf("s3: waiting for ReadFull() to fail")
342 // Compare the given data with the stored data.
343 func (v *S3Volume) Compare(ctx context.Context, loc string, expect []byte) error {
344 errChan := make(chan error, 1)
346 _, err := v.bucket.Head("recent/"+loc, nil)
353 case err = <-errChan:
356 // Checking for "loc" itself here would interfere with
357 // future GET requests.
359 // On AWS, if X doesn't exist, a HEAD or GET request
360 // for X causes X's non-existence to be cached. Thus,
361 // if we test for X, then create X and return a
362 // signature to our client, the client might still get
363 // 404 from all keepstores when trying to read it.
365 // To avoid this, we avoid doing HEAD X or GET X until
366 // we know X has been written.
368 // Note that X might exist even though recent/X
369 // doesn't: for example, the response to HEAD recent/X
370 // might itself come from a stale cache. In such
371 // cases, we will return a false negative and
372 // PutHandler might needlessly create another replica
373 // on a different volume. That's not ideal, but it's
374 // better than passing the eventually-consistent
375 // problem on to our clients.
376 return v.translateError(err)
378 rdr, err := v.getReaderWithContext(ctx, loc)
383 return v.translateError(compareReaderWithBuf(ctx, rdr, expect, loc[:32]))
386 // Put writes a block.
387 func (v *S3Volume) Put(ctx context.Context, loc string, block []byte) error {
389 return MethodDisabledError
394 md5, err := hex.DecodeString(loc)
398 opts.ContentMD5 = base64.StdEncoding.EncodeToString(md5)
401 // Send the block data through a pipe, so that (if we need to)
402 // we can close the pipe early and abandon our PutReader()
403 // goroutine, without worrying about PutReader() accessing our
404 // block buffer after we release it.
405 bufr, bufw := io.Pipe()
407 io.Copy(bufw, bytes.NewReader(block))
412 ready := make(chan bool)
415 if ctx.Err() != nil {
416 theConfig.debugLogf("%s: abandoned PutReader goroutine finished with err: %s", v, err)
420 err = v.bucket.PutReader(loc, bufr, int64(size), "application/octet-stream", s3ACL, opts)
424 err = v.bucket.PutReader("recent/"+loc, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
428 theConfig.debugLogf("%s: taking PutReader's input away: %s", v, ctx.Err())
429 // Our pipe might be stuck in Write(), waiting for
430 // io.Copy() to read. If so, un-stick it. This means
431 // PutReader will get corrupt data, but that's OK: the
432 // size and MD5 won't match, so the write will fail.
433 go io.Copy(ioutil.Discard, bufr)
434 // CloseWithError() will return once pending I/O is done.
435 bufw.CloseWithError(ctx.Err())
436 theConfig.debugLogf("%s: abandoning PutReader goroutine", v)
439 return v.translateError(err)
443 // Touch sets the timestamp for the given locator to the current time.
444 func (v *S3Volume) Touch(loc string) error {
446 return MethodDisabledError
448 _, err := v.bucket.Head(loc, nil)
449 err = v.translateError(err)
450 if os.IsNotExist(err) && v.fixRace(loc) {
451 // The data object got trashed in a race, but fixRace
453 } else if err != nil {
456 err = v.bucket.PutReader("recent/"+loc, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
457 return v.translateError(err)
460 // Mtime returns the stored timestamp for the given locator.
461 func (v *S3Volume) Mtime(loc string) (time.Time, error) {
462 _, err := v.bucket.Head(loc, nil)
464 return zeroTime, v.translateError(err)
466 resp, err := v.bucket.Head("recent/"+loc, nil)
467 err = v.translateError(err)
468 if os.IsNotExist(err) {
469 // The data object X exists, but recent/X is missing.
470 err = v.bucket.PutReader("recent/"+loc, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
472 log.Printf("error: creating %q: %s", "recent/"+loc, err)
473 return zeroTime, v.translateError(err)
475 log.Printf("info: created %q to migrate existing block to new storage scheme", "recent/"+loc)
476 resp, err = v.bucket.Head("recent/"+loc, nil)
478 log.Printf("error: created %q but HEAD failed: %s", "recent/"+loc, err)
479 return zeroTime, v.translateError(err)
481 } else if err != nil {
482 // HEAD recent/X failed for some other reason.
485 return v.lastModified(resp)
488 // IndexTo writes a complete list of locators with the given prefix
489 // for which Get() can retrieve data.
490 func (v *S3Volume) IndexTo(prefix string, writer io.Writer) error {
491 // Use a merge sort to find matching sets of X and recent/X.
493 Bucket: v.bucket.Bucket,
495 PageSize: v.IndexPageSize,
498 Bucket: v.bucket.Bucket,
499 Prefix: "recent/" + prefix,
500 PageSize: v.IndexPageSize,
502 v.bucket.stats.Tick(&v.bucket.stats.Ops, &v.bucket.stats.ListOps)
503 v.bucket.stats.Tick(&v.bucket.stats.Ops, &v.bucket.stats.ListOps)
504 for data, recent := dataL.First(), recentL.First(); data != nil; data = dataL.Next() {
505 v.bucket.stats.Tick(&v.bucket.stats.Ops, &v.bucket.stats.ListOps)
507 // Conveniently, "recent/*" and "trash/*" are
508 // lexically greater than all hex-encoded data
509 // hashes, so stopping here avoids iterating
510 // over all of them needlessly with dataL.
513 if !v.isKeepBlock(data.Key) {
517 // stamp is the list entry we should use to report the
518 // last-modified time for this data block: it will be
519 // the recent/X entry if one exists, otherwise the
520 // entry for the data block itself.
523 // Advance to the corresponding recent/X marker, if any
525 if cmp := strings.Compare(recent.Key[7:], data.Key); cmp < 0 {
526 recent = recentL.Next()
527 v.bucket.stats.Tick(&v.bucket.stats.Ops, &v.bucket.stats.ListOps)
531 recent = recentL.Next()
532 v.bucket.stats.Tick(&v.bucket.stats.Ops, &v.bucket.stats.ListOps)
535 // recent/X marker is missing: we'll
536 // use the timestamp on the data
541 t, err := time.Parse(time.RFC3339, stamp.LastModified)
545 fmt.Fprintf(writer, "%s+%d %d\n", data.Key, data.Size, t.UnixNano())
550 // Trash a Keep block.
551 func (v *S3Volume) Trash(loc string) error {
553 return MethodDisabledError
555 if t, err := v.Mtime(loc); err != nil {
557 } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
560 if theConfig.TrashLifetime == 0 {
562 return ErrS3TrashDisabled
564 return v.translateError(v.bucket.Del(loc))
566 err := v.checkRaceWindow(loc)
570 err = v.safeCopy("trash/"+loc, loc)
574 return v.translateError(v.bucket.Del(loc))
577 // checkRaceWindow returns a non-nil error if trash/loc is, or might
578 // be, in the race window (i.e., it's not safe to trash loc).
579 func (v *S3Volume) checkRaceWindow(loc string) error {
580 resp, err := v.bucket.Head("trash/"+loc, nil)
581 err = v.translateError(err)
582 if os.IsNotExist(err) {
583 // OK, trash/X doesn't exist so we're not in the race
586 } else if err != nil {
587 // Error looking up trash/X. We don't know whether
588 // we're in the race window
591 t, err := v.lastModified(resp)
593 // Can't parse timestamp
596 safeWindow := t.Add(theConfig.TrashLifetime.Duration()).Sub(time.Now().Add(time.Duration(v.RaceWindow)))
598 // We can't count on "touch trash/X" to prolong
599 // trash/X's lifetime. The new timestamp might not
600 // become visible until now+raceWindow, and EmptyTrash
601 // is allowed to delete trash/X before then.
602 return fmt.Errorf("same block is already in trash, and safe window ended %s ago", -safeWindow)
604 // trash/X exists, but it won't be eligible for deletion until
605 // after now+raceWindow, so it's safe to overwrite it.
609 // safeCopy calls PutCopy, and checks the response to make sure the
610 // copy succeeded and updated the timestamp on the destination object
611 // (PutCopy returns 200 OK if the request was received, even if the
613 func (v *S3Volume) safeCopy(dst, src string) error {
614 resp, err := v.bucket.PutCopy(dst, s3ACL, s3.CopyOptions{
615 ContentType: "application/octet-stream",
616 MetadataDirective: "REPLACE",
617 }, v.bucket.Name+"/"+src)
618 err = v.translateError(err)
622 if t, err := time.Parse(time.RFC3339Nano, resp.LastModified); err != nil {
623 return fmt.Errorf("PutCopy succeeded but did not return a timestamp: %q: %s", resp.LastModified, err)
624 } else if time.Now().Sub(t) > maxClockSkew {
625 return fmt.Errorf("PutCopy succeeded but returned an old timestamp: %q: %s", resp.LastModified, t)
630 // Get the LastModified header from resp, and parse it as RFC1123 or
631 // -- if it isn't valid RFC1123 -- as Amazon's variant of RFC1123.
632 func (v *S3Volume) lastModified(resp *http.Response) (t time.Time, err error) {
633 s := resp.Header.Get("Last-Modified")
634 t, err = time.Parse(time.RFC1123, s)
635 if err != nil && s != "" {
636 // AWS example is "Sun, 1 Jan 2006 12:00:00 GMT",
637 // which isn't quite "Sun, 01 Jan 2006 12:00:00 GMT"
638 // as required by HTTP spec. If it's not a valid HTTP
639 // header value, it's probably AWS (or s3test) giving
640 // us a nearly-RFC1123 timestamp.
641 t, err = time.Parse(nearlyRFC1123, s)
646 // Untrash moves block from trash back into store
647 func (v *S3Volume) Untrash(loc string) error {
648 err := v.safeCopy(loc, "trash/"+loc)
652 err = v.bucket.PutReader("recent/"+loc, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
653 return v.translateError(err)
656 // Status returns a *VolumeStatus representing the current in-use
657 // storage capacity and a fake available capacity that doesn't make
658 // the volume seem full or nearly-full.
659 func (v *S3Volume) Status() *VolumeStatus {
660 return &VolumeStatus{
662 BytesFree: BlockSize * 1000,
667 // InternalStats returns bucket I/O and API call counters.
668 func (v *S3Volume) InternalStats() interface{} {
669 return &v.bucket.stats
672 // String implements fmt.Stringer.
673 func (v *S3Volume) String() string {
674 return fmt.Sprintf("s3-bucket:%+q", v.Bucket)
677 // Writable returns false if all future Put, Mtime, and Delete calls
678 // are expected to fail.
679 func (v *S3Volume) Writable() bool {
683 // Replication returns the storage redundancy of the underlying
684 // device. Configured via command line flag.
685 func (v *S3Volume) Replication() int {
686 return v.S3Replication
689 var s3KeepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
691 func (v *S3Volume) isKeepBlock(s string) bool {
692 return s3KeepBlockRegexp.MatchString(s)
695 // fixRace(X) is called when "recent/X" exists but "X" doesn't
696 // exist. If the timestamps on "recent/"+loc and "trash/"+loc indicate
697 // there was a race between Put and Trash, fixRace recovers from the
698 // race by Untrashing the block.
699 func (v *S3Volume) fixRace(loc string) bool {
700 trash, err := v.bucket.Head("trash/"+loc, nil)
702 if !os.IsNotExist(v.translateError(err)) {
703 log.Printf("error: fixRace: HEAD %q: %s", "trash/"+loc, err)
707 trashTime, err := v.lastModified(trash)
709 log.Printf("error: fixRace: parse %q: %s", trash.Header.Get("Last-Modified"), err)
713 recent, err := v.bucket.Head("recent/"+loc, nil)
715 log.Printf("error: fixRace: HEAD %q: %s", "recent/"+loc, err)
718 recentTime, err := v.lastModified(recent)
720 log.Printf("error: fixRace: parse %q: %s", recent.Header.Get("Last-Modified"), err)
724 ageWhenTrashed := trashTime.Sub(recentTime)
725 if ageWhenTrashed >= theConfig.BlobSignatureTTL.Duration() {
726 // No evidence of a race: block hasn't been written
727 // since it became eligible for Trash. No fix needed.
731 log.Printf("notice: fixRace: %q: trashed at %s but touched at %s (age when trashed = %s < %s)", loc, trashTime, recentTime, ageWhenTrashed, theConfig.BlobSignatureTTL)
732 log.Printf("notice: fixRace: copying %q to %q to recover from race between Put/Touch and Trash", "recent/"+loc, loc)
733 err = v.safeCopy(loc, "trash/"+loc)
735 log.Printf("error: fixRace: %s", err)
741 func (v *S3Volume) translateError(err error) error {
742 switch err := err.(type) {
744 if (err.StatusCode == http.StatusNotFound && err.Code == "NoSuchKey") ||
745 strings.Contains(err.Error(), "Not Found") {
746 return os.ErrNotExist
748 // Other 404 errors like NoSuchVersion and
749 // NoSuchBucket are different problems which should
750 // get called out downstream, so we don't convert them
751 // to os.ErrNotExist.
756 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
757 // and deletes them from the volume.
758 func (v *S3Volume) EmptyTrash() {
759 var bytesInTrash, blocksInTrash, bytesDeleted, blocksDeleted int64
761 // Use a merge sort to find matching sets of trash/X and recent/X.
763 Bucket: v.bucket.Bucket,
765 PageSize: v.IndexPageSize,
767 // Define "ready to delete" as "...when EmptyTrash started".
769 for trash := trashL.First(); trash != nil; trash = trashL.Next() {
771 if !v.isKeepBlock(loc) {
774 bytesInTrash += trash.Size
777 trashT, err := time.Parse(time.RFC3339, trash.LastModified)
779 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, trash.Key, trash.LastModified, err)
782 recent, err := v.bucket.Head("recent/"+loc, nil)
783 if err != nil && os.IsNotExist(v.translateError(err)) {
784 log.Printf("warning: %s: EmptyTrash: found trash marker %q but no %q (%s); calling Untrash", v, trash.Key, "recent/"+loc, err)
787 log.Printf("error: %s: EmptyTrash: Untrash(%q): %s", v, loc, err)
790 } else if err != nil {
791 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, "recent/"+loc, err)
794 recentT, err := v.lastModified(recent)
796 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, "recent/"+loc, recent.Header.Get("Last-Modified"), err)
799 if trashT.Sub(recentT) < theConfig.BlobSignatureTTL.Duration() {
800 if age := startT.Sub(recentT); age >= theConfig.BlobSignatureTTL.Duration()-time.Duration(v.RaceWindow) {
801 // recent/loc is too old to protect
802 // loc from being Trashed again during
803 // the raceWindow that starts if we
804 // delete trash/X now.
806 // Note this means (TrashCheckInterval
807 // < BlobSignatureTTL - raceWindow) is
808 // necessary to avoid starvation.
809 log.Printf("notice: %s: EmptyTrash: detected old race for %q, calling fixRace + Touch", v, loc)
814 _, err := v.bucket.Head(loc, nil)
815 if os.IsNotExist(err) {
816 log.Printf("notice: %s: EmptyTrash: detected recent race for %q, calling fixRace", v, loc)
819 } else if err != nil {
820 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, loc, err)
824 if startT.Sub(trashT) < theConfig.TrashLifetime.Duration() {
827 err = v.bucket.Del(trash.Key)
829 log.Printf("warning: %s: EmptyTrash: deleting %q: %s", v, trash.Key, err)
832 bytesDeleted += trash.Size
835 _, err = v.bucket.Head(loc, nil)
836 if os.IsNotExist(err) {
837 err = v.bucket.Del("recent/" + loc)
839 log.Printf("warning: %s: EmptyTrash: deleting %q: %s", v, "recent/"+loc, err)
841 } else if err != nil {
842 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, "recent/"+loc, err)
845 if err := trashL.Error(); err != nil {
846 log.Printf("error: %s: EmptyTrash: lister: %s", v, err)
848 log.Printf("EmptyTrash stats for %v: Deleted %v bytes in %v blocks. Remaining in trash: %v bytes in %v blocks.", v.String(), bytesDeleted, blocksDeleted, bytesInTrash-bytesDeleted, blocksInTrash-blocksDeleted)
851 type s3Lister struct {
860 // First fetches the first page and returns the first item. It returns
861 // nil if the response is the empty set or an error occurs.
862 func (lister *s3Lister) First() *s3.Key {
867 // Next returns the next item, fetching the next page if necessary. It
868 // returns nil if the last available item has already been fetched, or
870 func (lister *s3Lister) Next() *s3.Key {
871 if len(lister.buf) == 0 && lister.nextMarker != "" {
877 // Return the most recent error encountered by First or Next.
878 func (lister *s3Lister) Error() error {
882 func (lister *s3Lister) getPage() {
883 resp, err := lister.Bucket.List(lister.Prefix, "", lister.nextMarker, lister.PageSize)
884 lister.nextMarker = ""
889 if resp.IsTruncated {
890 lister.nextMarker = resp.NextMarker
892 lister.buf = make([]s3.Key, 0, len(resp.Contents))
893 for _, key := range resp.Contents {
894 if !strings.HasPrefix(key.Key, lister.Prefix) {
895 log.Printf("warning: s3Lister: S3 Bucket.List(prefix=%q) returned key %q", lister.Prefix, key.Key)
898 lister.buf = append(lister.buf, key)
902 func (lister *s3Lister) pop() (k *s3.Key) {
903 if len(lister.buf) > 0 {
905 lister.buf = lister.buf[1:]
910 // s3bucket wraps s3.bucket and counts I/O and API usage stats.
911 type s3bucket struct {
916 func (b *s3bucket) GetReader(path string) (io.ReadCloser, error) {
917 rdr, err := b.Bucket.GetReader(path)
918 b.stats.Tick(&b.stats.Ops, &b.stats.GetOps)
920 return NewCountingReader(rdr, b.stats.TickInBytes), err
923 func (b *s3bucket) Head(path string, headers map[string][]string) (*http.Response, error) {
924 resp, err := b.Bucket.Head(path, headers)
925 b.stats.Tick(&b.stats.Ops, &b.stats.HeadOps)
930 func (b *s3bucket) PutReader(path string, r io.Reader, length int64, contType string, perm s3.ACL, options s3.Options) error {
932 // goamz will only send Content-Length: 0 when reader
933 // is nil due to net.http.Request.ContentLength
934 // behavior. Otherwise, Content-Length header is
935 // omitted which will cause some S3 services
936 // (including AWS and Ceph RadosGW) to fail to create
940 r = NewCountingReader(r, b.stats.TickOutBytes)
942 err := b.Bucket.PutReader(path, r, length, contType, perm, options)
943 b.stats.Tick(&b.stats.Ops, &b.stats.PutOps)
948 func (b *s3bucket) Del(path string) error {
949 err := b.Bucket.Del(path)
950 b.stats.Tick(&b.stats.Ops, &b.stats.DelOps)
955 type s3bucketStats struct {
965 func (s *s3bucketStats) TickErr(err error) {
969 errType := fmt.Sprintf("%T", err)
970 if err, ok := err.(*s3.Error); ok {
971 errType = errType + fmt.Sprintf(" %d %s", err.StatusCode, err.Code)
973 s.statsTicker.TickErr(err, errType)