21 "git.curoverse.com/arvados.git/sdk/go/arvados"
22 "github.com/AdRoll/goamz/aws"
23 "github.com/AdRoll/goamz/s3"
27 s3DefaultReadTimeout = arvados.Duration(10 * time.Minute)
28 s3DefaultConnectTimeout = arvados.Duration(time.Minute)
32 // ErrS3TrashDisabled is returned by Trash if that operation
33 // is impossible with the current config.
34 ErrS3TrashDisabled = fmt.Errorf("trash function is disabled because -trash-lifetime=0 and -s3-unsafe-delete=false")
36 s3AccessKeyFile string
37 s3SecretKeyFile string
42 s3RaceWindow time.Duration
48 maxClockSkew = 600 * time.Second
49 nearlyRFC1123 = "Mon, 2 Jan 2006 15:04:05 GMT"
52 type s3VolumeAdder struct {
56 // String implements flag.Value
57 func (s *s3VolumeAdder) String() string {
61 func (s *s3VolumeAdder) Set(bucketName string) error {
63 return fmt.Errorf("no container name given")
65 if s3AccessKeyFile == "" || s3SecretKeyFile == "" {
66 return fmt.Errorf("-s3-access-key-file and -s3-secret-key-file arguments must given before -s3-bucket-volume")
68 if deprecated.flagSerializeIO {
69 log.Print("Notice: -serialize is not supported by s3-bucket volumes.")
71 s.Config.Volumes = append(s.Config.Volumes, &S3Volume{
73 AccessKeyFile: s3AccessKeyFile,
74 SecretKeyFile: s3SecretKeyFile,
77 RaceWindow: arvados.Duration(s3RaceWindow),
78 S3Replication: s3Replication,
79 UnsafeDelete: s3UnsafeDelete,
80 ReadOnly: deprecated.flagReadonly,
86 func s3regions() (okList []string) {
87 for r := range aws.Regions {
88 okList = append(okList, r)
94 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &S3Volume{} })
96 flag.Var(&s3VolumeAdder{theConfig},
98 "Use the given bucket as a storage volume. Can be given multiple times.")
103 fmt.Sprintf("AWS region used for subsequent -s3-bucket-volume arguments. Allowed values are %+q.", s3regions()))
108 "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\".")
111 "s3-access-key-file",
113 "`File` containing the access key used for subsequent -s3-bucket-volume arguments.")
116 "s3-secret-key-file",
118 "`File` containing the secret key used for subsequent -s3-bucket-volume arguments.")
123 "Maximum eventual consistency latency for subsequent -s3-bucket-volume arguments.")
128 "Replication level reported to clients for subsequent -s3-bucket-volume arguments.")
133 "EXPERIMENTAL. Enable deletion (garbage collection), even though there are known race conditions that can cause data loss.")
136 // S3Volume implements Volume using an S3 bucket.
137 type S3Volume struct {
143 LocationConstraint bool
146 ConnectTimeout arvados.Duration
147 ReadTimeout arvados.Duration
148 RaceWindow arvados.Duration
153 bucketStats bucketStats
159 type bucketStats struct {
169 ErrorCodes map[string]uint64 `json:",omitempty"`
174 // Examples implements VolumeWithExamples.
175 func (*S3Volume) Examples() []Volume {
178 AccessKeyFile: "/etc/aws_s3_access_key.txt",
179 SecretKeyFile: "/etc/aws_s3_secret_key.txt",
182 Bucket: "example-bucket-name",
185 RaceWindow: arvados.Duration(24 * time.Hour),
186 ConnectTimeout: arvados.Duration(time.Minute),
187 ReadTimeout: arvados.Duration(5 * time.Minute),
190 AccessKeyFile: "/etc/gce_s3_access_key.txt",
191 SecretKeyFile: "/etc/gce_s3_secret_key.txt",
192 Endpoint: "https://storage.googleapis.com",
194 Bucket: "example-bucket-name",
197 RaceWindow: arvados.Duration(24 * time.Hour),
198 ConnectTimeout: arvados.Duration(time.Minute),
199 ReadTimeout: arvados.Duration(5 * time.Minute),
204 // Type implements Volume.
205 func (*S3Volume) Type() string {
209 // Start populates private fields and verifies the configuration is
211 func (v *S3Volume) Start() error {
212 region, ok := aws.Regions[v.Region]
213 if v.Endpoint == "" {
215 return fmt.Errorf("unrecognized region %+q; try specifying -s3-endpoint instead", v.Region)
218 return fmt.Errorf("refusing to use AWS region name %+q with endpoint %+q; "+
219 "specify empty endpoint (\"-s3-endpoint=\") or use a different region name", v.Region, v.Endpoint)
223 S3Endpoint: v.Endpoint,
224 S3LocationConstraint: v.LocationConstraint,
230 auth.AccessKey, err = readKeyFromFile(v.AccessKeyFile)
234 auth.SecretKey, err = readKeyFromFile(v.SecretKeyFile)
239 // Zero timeouts mean "wait forever", which is a bad
240 // default. Default to long timeouts instead.
241 if v.ConnectTimeout == 0 {
242 v.ConnectTimeout = s3DefaultConnectTimeout
244 if v.ReadTimeout == 0 {
245 v.ReadTimeout = s3DefaultReadTimeout
248 client := s3.New(auth, region)
249 client.ConnectTimeout = time.Duration(v.ConnectTimeout)
250 client.ReadTimeout = time.Duration(v.ReadTimeout)
251 v.bucket = &s3.Bucket{
258 func (v *S3Volume) getReaderWithContext(ctx context.Context, loc string) (rdr io.ReadCloser, err error) {
259 ready := make(chan bool)
261 rdr, err = v.getReader(loc)
268 theConfig.debugLogf("s3: abandoning getReader(): %s", ctx.Err())
275 return nil, ctx.Err()
279 // getReader wraps (Bucket)GetReader.
281 // In situations where (Bucket)GetReader would fail because the block
282 // disappeared in a Trash race, getReader calls fixRace to recover the
283 // data, and tries again.
284 func (v *S3Volume) getReader(loc string) (rdr io.ReadCloser, err error) {
285 v.tick(&v.bucketStats.Ops, &v.bucketStats.GetOps)
286 rdr, err = v.bucket.GetReader(loc)
287 err = v.translateError(err)
289 rdr = NewCountingReader(rdr, v.tickInBytes)
291 } else if !os.IsNotExist(v.tickErr(err)) {
295 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
296 _, err = v.bucket.Head("recent/"+loc, nil)
297 err = v.translateError(v.tickErr(err))
299 // If we can't read recent/X, there's no point in
300 // trying fixRace. Give up.
308 v.tick(&v.bucketStats.Ops, &v.bucketStats.GetOps)
309 rdr, err = v.bucket.GetReader(loc)
311 log.Printf("warning: reading %s after successful fixRace: %s", loc, err)
312 err = v.translateError(v.tickErr(err))
314 rdr = NewCountingReader(rdr, v.tickInBytes)
318 // Get a block: copy the block data into buf, and return the number of
320 func (v *S3Volume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
321 rdr, err := v.getReaderWithContext(ctx, loc)
327 ready := make(chan bool)
332 n, err = io.ReadFull(rdr, buf)
335 case nil, io.EOF, io.ErrUnexpectedEOF:
338 err = v.translateError(err)
343 theConfig.debugLogf("s3: interrupting ReadFull() with Close() because %s", ctx.Err())
345 // Must wait for ReadFull to return, to ensure it
346 // doesn't write to buf after we return.
347 theConfig.debugLogf("s3: waiting for ReadFull() to fail")
355 // Compare the given data with the stored data.
356 func (v *S3Volume) Compare(ctx context.Context, loc string, expect []byte) error {
357 rdr, err := v.getReaderWithContext(ctx, loc)
362 return v.translateError(compareReaderWithBuf(ctx, rdr, expect, loc[:32]))
365 // Put writes a block.
366 func (v *S3Volume) Put(ctx context.Context, loc string, block []byte) error {
368 return MethodDisabledError
373 md5, err := hex.DecodeString(loc)
377 opts.ContentMD5 = base64.StdEncoding.EncodeToString(md5)
380 // Send the block data through a pipe, so that (if we need to)
381 // we can close the pipe early and abandon our PutReader()
382 // goroutine, without worrying about PutReader() accessing our
383 // block buffer after we release it.
384 bufr, bufw := io.Pipe()
386 io.Copy(bufw, bytes.NewReader(block))
391 ready := make(chan bool)
394 if ctx.Err() != nil {
395 theConfig.debugLogf("%s: abandoned PutReader goroutine finished with err: %s", v, err)
399 v.tick(&v.bucketStats.Ops, &v.bucketStats.PutOps)
400 rdr := NewCountingReader(bufr, v.tickOutBytes)
401 err = v.bucket.PutReader(loc, rdr, int64(size), "application/octet-stream", s3ACL, opts)
406 v.tick(&v.bucketStats.Ops, &v.bucketStats.PutOps)
407 err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
412 theConfig.debugLogf("%s: taking PutReader's input away: %s", v, ctx.Err())
413 // Our pipe might be stuck in Write(), waiting for
414 // io.Copy() to read. If so, un-stick it. This means
415 // PutReader will get corrupt data, but that's OK: the
416 // size and MD5 won't match, so the write will fail.
417 go io.Copy(ioutil.Discard, bufr)
418 // CloseWithError() will return once pending I/O is done.
419 bufw.CloseWithError(ctx.Err())
420 theConfig.debugLogf("%s: abandoning PutReader goroutine", v)
423 return v.translateError(err)
427 // Touch sets the timestamp for the given locator to the current time.
428 func (v *S3Volume) Touch(loc string) error {
430 return MethodDisabledError
432 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
433 _, err := v.bucket.Head(loc, nil)
434 err = v.translateError(v.tickErr(err))
435 if os.IsNotExist(err) && v.fixRace(loc) {
436 // The data object got trashed in a race, but fixRace
438 } else if err != nil {
441 v.tick(&v.bucketStats.Ops, &v.bucketStats.PutOps)
442 err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
443 return v.translateError(v.tickErr(err))
446 // Mtime returns the stored timestamp for the given locator.
447 func (v *S3Volume) Mtime(loc string) (time.Time, error) {
448 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
449 _, err := v.bucket.Head(loc, nil)
451 return zeroTime, v.translateError(v.tickErr(err))
453 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
454 resp, err := v.bucket.Head("recent/"+loc, nil)
455 err = v.translateError(v.tickErr(err))
456 if os.IsNotExist(err) {
457 // The data object X exists, but recent/X is missing.
458 v.tick(&v.bucketStats.Ops, &v.bucketStats.PutOps)
459 err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
461 log.Printf("error: creating %q: %s", "recent/"+loc, err)
462 return zeroTime, v.translateError(v.tickErr(err))
464 log.Printf("info: created %q to migrate existing block to new storage scheme", "recent/"+loc)
465 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
466 resp, err = v.bucket.Head("recent/"+loc, nil)
468 log.Printf("error: created %q but HEAD failed: %s", "recent/"+loc, err)
469 return zeroTime, v.translateError(v.tickErr(err))
471 } else if err != nil {
472 // HEAD recent/X failed for some other reason.
475 return v.lastModified(resp)
478 // IndexTo writes a complete list of locators with the given prefix
479 // for which Get() can retrieve data.
480 func (v *S3Volume) IndexTo(prefix string, writer io.Writer) error {
481 // Use a merge sort to find matching sets of X and recent/X.
485 PageSize: v.IndexPageSize,
489 Prefix: "recent/" + prefix,
490 PageSize: v.IndexPageSize,
492 for data, recent := dataL.First(), recentL.First(); data != nil; data = dataL.Next() {
494 // Conveniently, "recent/*" and "trash/*" are
495 // lexically greater than all hex-encoded data
496 // hashes, so stopping here avoids iterating
497 // over all of them needlessly with dataL.
500 if !v.isKeepBlock(data.Key) {
504 // stamp is the list entry we should use to report the
505 // last-modified time for this data block: it will be
506 // the recent/X entry if one exists, otherwise the
507 // entry for the data block itself.
510 // Advance to the corresponding recent/X marker, if any
512 if cmp := strings.Compare(recent.Key[7:], data.Key); cmp < 0 {
513 recent = recentL.Next()
517 recent = recentL.Next()
520 // recent/X marker is missing: we'll
521 // use the timestamp on the data
526 t, err := time.Parse(time.RFC3339, stamp.LastModified)
530 fmt.Fprintf(writer, "%s+%d %d\n", data.Key, data.Size, t.UnixNano())
535 // Trash a Keep block.
536 func (v *S3Volume) Trash(loc string) error {
538 return MethodDisabledError
540 if t, err := v.Mtime(loc); err != nil {
542 } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
545 if theConfig.TrashLifetime == 0 {
547 return ErrS3TrashDisabled
549 v.tick(&v.bucketStats.Ops, &v.bucketStats.DelOps)
550 return v.translateError(v.tickErr(v.bucket.Del(loc)))
552 err := v.checkRaceWindow(loc)
556 err = v.safeCopy("trash/"+loc, loc)
560 v.tick(&v.bucketStats.Ops, &v.bucketStats.DelOps)
561 return v.translateError(v.tickErr(v.bucket.Del(loc)))
564 // checkRaceWindow returns a non-nil error if trash/loc is, or might
565 // be, in the race window (i.e., it's not safe to trash loc).
566 func (v *S3Volume) checkRaceWindow(loc string) error {
567 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
568 resp, err := v.bucket.Head("trash/"+loc, nil)
569 err = v.translateError(v.tickErr(err))
570 if os.IsNotExist(err) {
571 // OK, trash/X doesn't exist so we're not in the race
574 } else if err != nil {
575 // Error looking up trash/X. We don't know whether
576 // we're in the race window
579 t, err := v.lastModified(resp)
581 // Can't parse timestamp
584 safeWindow := t.Add(theConfig.TrashLifetime.Duration()).Sub(time.Now().Add(time.Duration(v.RaceWindow)))
586 // We can't count on "touch trash/X" to prolong
587 // trash/X's lifetime. The new timestamp might not
588 // become visible until now+raceWindow, and EmptyTrash
589 // is allowed to delete trash/X before then.
590 return fmt.Errorf("same block is already in trash, and safe window ended %s ago", -safeWindow)
592 // trash/X exists, but it won't be eligible for deletion until
593 // after now+raceWindow, so it's safe to overwrite it.
597 // safeCopy calls PutCopy, and checks the response to make sure the
598 // copy succeeded and updated the timestamp on the destination object
599 // (PutCopy returns 200 OK if the request was received, even if the
601 func (v *S3Volume) safeCopy(dst, src string) error {
602 v.tick(&v.bucketStats.Ops, &v.bucketStats.PutOps)
603 resp, err := v.bucket.PutCopy(dst, s3ACL, s3.CopyOptions{
604 ContentType: "application/octet-stream",
605 MetadataDirective: "REPLACE",
606 }, v.bucket.Name+"/"+src)
607 err = v.translateError(v.tickErr(err))
611 if t, err := time.Parse(time.RFC3339Nano, resp.LastModified); err != nil {
612 return fmt.Errorf("PutCopy succeeded but did not return a timestamp: %q: %s", resp.LastModified, err)
613 } else if time.Now().Sub(t) > maxClockSkew {
614 return fmt.Errorf("PutCopy succeeded but returned an old timestamp: %q: %s", resp.LastModified, t)
619 // Get the LastModified header from resp, and parse it as RFC1123 or
620 // -- if it isn't valid RFC1123 -- as Amazon's variant of RFC1123.
621 func (v *S3Volume) lastModified(resp *http.Response) (t time.Time, err error) {
622 s := resp.Header.Get("Last-Modified")
623 t, err = time.Parse(time.RFC1123, s)
624 if err != nil && s != "" {
625 // AWS example is "Sun, 1 Jan 2006 12:00:00 GMT",
626 // which isn't quite "Sun, 01 Jan 2006 12:00:00 GMT"
627 // as required by HTTP spec. If it's not a valid HTTP
628 // header value, it's probably AWS (or s3test) giving
629 // us a nearly-RFC1123 timestamp.
630 t, err = time.Parse(nearlyRFC1123, s)
635 // Untrash moves block from trash back into store
636 func (v *S3Volume) Untrash(loc string) error {
637 err := v.safeCopy(loc, "trash/"+loc)
641 v.tick(&v.bucketStats.Ops, &v.bucketStats.PutOps)
642 err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
643 return v.translateError(v.tickErr(err))
646 // Status returns a *VolumeStatus representing the current in-use
647 // storage capacity and a fake available capacity that doesn't make
648 // the volume seem full or nearly-full.
649 func (v *S3Volume) Status() *VolumeStatus {
650 return &VolumeStatus{
652 BytesFree: BlockSize * 1000,
657 // IOStatus implements InternalStatser.
658 func (v *S3Volume) InternalStats() interface{} {
659 return &v.bucketStats
662 // String implements fmt.Stringer.
663 func (v *S3Volume) String() string {
664 return fmt.Sprintf("s3-bucket:%+q", v.Bucket)
667 // Writable returns false if all future Put, Mtime, and Delete calls
668 // are expected to fail.
669 func (v *S3Volume) Writable() bool {
673 // Replication returns the storage redundancy of the underlying
674 // device. Configured via command line flag.
675 func (v *S3Volume) Replication() int {
676 return v.S3Replication
679 var s3KeepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
681 func (v *S3Volume) isKeepBlock(s string) bool {
682 return s3KeepBlockRegexp.MatchString(s)
685 // fixRace(X) is called when "recent/X" exists but "X" doesn't
686 // exist. If the timestamps on "recent/"+loc and "trash/"+loc indicate
687 // there was a race between Put and Trash, fixRace recovers from the
688 // race by Untrashing the block.
689 func (v *S3Volume) fixRace(loc string) bool {
690 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
691 trash, err := v.bucket.Head("trash/"+loc, nil)
693 if !os.IsNotExist(v.translateError(v.tickErr(err))) {
694 log.Printf("error: fixRace: HEAD %q: %s", "trash/"+loc, err)
698 trashTime, err := v.lastModified(trash)
700 log.Printf("error: fixRace: parse %q: %s", trash.Header.Get("Last-Modified"), err)
704 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
705 recent, err := v.bucket.Head("recent/"+loc, nil)
708 log.Printf("error: fixRace: HEAD %q: %s", "recent/"+loc, err)
711 recentTime, err := v.lastModified(recent)
713 log.Printf("error: fixRace: parse %q: %s", recent.Header.Get("Last-Modified"), err)
717 ageWhenTrashed := trashTime.Sub(recentTime)
718 if ageWhenTrashed >= theConfig.BlobSignatureTTL.Duration() {
719 // No evidence of a race: block hasn't been written
720 // since it became eligible for Trash. No fix needed.
724 log.Printf("notice: fixRace: %q: trashed at %s but touched at %s (age when trashed = %s < %s)", loc, trashTime, recentTime, ageWhenTrashed, theConfig.BlobSignatureTTL)
725 log.Printf("notice: fixRace: copying %q to %q to recover from race between Put/Touch and Trash", "recent/"+loc, loc)
726 err = v.safeCopy(loc, "trash/"+loc)
728 log.Printf("error: fixRace: %s", err)
734 func (v *S3Volume) translateError(err error) error {
735 switch err := err.(type) {
737 if (err.StatusCode == http.StatusNotFound && err.Code == "NoSuchKey") ||
738 strings.Contains(err.Error(), "Not Found") {
739 return os.ErrNotExist
741 // Other 404 errors like NoSuchVersion and
742 // NoSuchBucket are different problems which should
743 // get called out downstream, so we don't convert them
744 // to os.ErrNotExist.
749 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
750 // and deletes them from the volume.
751 func (v *S3Volume) EmptyTrash() {
752 var bytesInTrash, blocksInTrash, bytesDeleted, blocksDeleted int64
754 // Use a merge sort to find matching sets of trash/X and recent/X.
758 PageSize: v.IndexPageSize,
760 // Define "ready to delete" as "...when EmptyTrash started".
762 for trash := trashL.First(); trash != nil; trash = trashL.Next() {
764 if !v.isKeepBlock(loc) {
767 bytesInTrash += trash.Size
770 trashT, err := time.Parse(time.RFC3339, trash.LastModified)
772 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, trash.Key, trash.LastModified, err)
775 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
776 recent, err := v.bucket.Head("recent/"+loc, nil)
777 if err != nil && os.IsNotExist(v.translateError(v.tickErr(err))) {
778 log.Printf("warning: %s: EmptyTrash: found trash marker %q but no %q (%s); calling Untrash", v, trash.Key, "recent/"+loc, err)
781 log.Printf("error: %s: EmptyTrash: Untrash(%q): %s", v, loc, err)
784 } else if err != nil {
785 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, "recent/"+loc, err)
788 recentT, err := v.lastModified(recent)
790 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, "recent/"+loc, recent.Header.Get("Last-Modified"), err)
793 if trashT.Sub(recentT) < theConfig.BlobSignatureTTL.Duration() {
794 if age := startT.Sub(recentT); age >= theConfig.BlobSignatureTTL.Duration()-time.Duration(v.RaceWindow) {
795 // recent/loc is too old to protect
796 // loc from being Trashed again during
797 // the raceWindow that starts if we
798 // delete trash/X now.
800 // Note this means (TrashCheckInterval
801 // < BlobSignatureTTL - raceWindow) is
802 // necessary to avoid starvation.
803 log.Printf("notice: %s: EmptyTrash: detected old race for %q, calling fixRace + Touch", v, loc)
808 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
809 _, err := v.bucket.Head(loc, nil)
810 if os.IsNotExist(v.tickErr(err)) {
811 log.Printf("notice: %s: EmptyTrash: detected recent race for %q, calling fixRace", v, loc)
814 } else if err != nil {
815 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, loc, err)
819 if startT.Sub(trashT) < theConfig.TrashLifetime.Duration() {
822 v.tick(&v.bucketStats.Ops, &v.bucketStats.DelOps)
823 err = v.bucket.Del(trash.Key)
826 log.Printf("warning: %s: EmptyTrash: deleting %q: %s", v, trash.Key, err)
829 bytesDeleted += trash.Size
832 v.tick(&v.bucketStats.Ops, &v.bucketStats.HeadOps)
833 _, err = v.bucket.Head(loc, nil)
834 if os.IsNotExist(v.tickErr(err)) {
835 v.tick(&v.bucketStats.Ops, &v.bucketStats.DelOps)
836 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 func (v *S3Volume) tick(counters ...*uint64) {
852 for _, counter := range counters {
853 atomic.AddUint64(counter, 1)
857 func (v *S3Volume) tickErr(err error) error {
861 atomic.AddUint64(&v.bucketStats.Errors, 1)
862 errStr := fmt.Sprintf("%T", err)
863 if err, ok := err.(*s3.Error); ok {
864 errStr = errStr + fmt.Sprintf(" %d %s", err.StatusCode, err.Code)
866 v.bucketStats.lock.Lock()
867 if v.bucketStats.ErrorCodes == nil {
868 v.bucketStats.ErrorCodes = make(map[string]uint64)
870 v.bucketStats.ErrorCodes[errStr]++
871 v.bucketStats.lock.Unlock()
875 func (v *S3Volume) tickInBytes(n uint64) {
876 atomic.AddUint64(&v.bucketStats.InBytes, n)
879 func (v *S3Volume) tickOutBytes(n uint64) {
880 atomic.AddUint64(&v.bucketStats.OutBytes, n)
883 type s3Lister struct {
892 // First fetches the first page and returns the first item. It returns
893 // nil if the response is the empty set or an error occurs.
894 func (lister *s3Lister) First() *s3.Key {
899 // Next returns the next item, fetching the next page if necessary. It
900 // returns nil if the last available item has already been fetched, or
902 func (lister *s3Lister) Next() *s3.Key {
903 if len(lister.buf) == 0 && lister.nextMarker != "" {
909 // Return the most recent error encountered by First or Next.
910 func (lister *s3Lister) Error() error {
914 func (lister *s3Lister) getPage() {
915 resp, err := lister.Bucket.List(lister.Prefix, "", lister.nextMarker, lister.PageSize)
916 lister.nextMarker = ""
921 if resp.IsTruncated {
922 lister.nextMarker = resp.NextMarker
924 lister.buf = make([]s3.Key, 0, len(resp.Contents))
925 for _, key := range resp.Contents {
926 if !strings.HasPrefix(key.Key, lister.Prefix) {
927 log.Printf("warning: s3Lister: S3 Bucket.List(prefix=%q) returned key %q", lister.Prefix, key.Key)
930 lister.buf = append(lister.buf, key)
934 func (lister *s3Lister) pop() (k *s3.Key) {
935 if len(lister.buf) > 0 {
937 lister.buf = lister.buf[1:]