1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 "git.curoverse.com/arvados.git/sdk/go/arvados"
26 "github.com/AdRoll/goamz/aws"
27 "github.com/AdRoll/goamz/s3"
28 "github.com/prometheus/client_golang/prometheus"
32 s3DefaultReadTimeout = arvados.Duration(10 * time.Minute)
33 s3DefaultConnectTimeout = arvados.Duration(time.Minute)
37 // ErrS3TrashDisabled is returned by Trash if that operation
38 // is impossible with the current config.
39 ErrS3TrashDisabled = fmt.Errorf("trash function is disabled because -trash-lifetime=0 and -s3-unsafe-delete=false")
41 s3AccessKeyFile string
42 s3SecretKeyFile string
47 s3RaceWindow time.Duration
55 maxClockSkew = 600 * time.Second
56 nearlyRFC1123 = "Mon, 2 Jan 2006 15:04:05 GMT"
59 type s3VolumeAdder struct {
63 // String implements flag.Value
64 func (s *s3VolumeAdder) String() string {
68 func (s *s3VolumeAdder) Set(bucketName string) error {
70 return fmt.Errorf("no container name given")
72 if s3AccessKeyFile == "" || s3SecretKeyFile == "" {
73 return fmt.Errorf("-s3-access-key-file and -s3-secret-key-file arguments must given before -s3-bucket-volume")
75 if deprecated.flagSerializeIO {
76 log.Print("Notice: -serialize is not supported by s3-bucket volumes.")
78 s.Config.Volumes = append(s.Config.Volumes, &S3Volume{
80 AccessKeyFile: s3AccessKeyFile,
81 SecretKeyFile: s3SecretKeyFile,
84 RaceWindow: arvados.Duration(s3RaceWindow),
85 S3Replication: s3Replication,
86 UnsafeDelete: s3UnsafeDelete,
87 ReadOnly: deprecated.flagReadonly,
93 func s3regions() (okList []string) {
94 for r := range aws.Regions {
95 okList = append(okList, r)
101 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &S3Volume{} })
103 flag.Var(&s3VolumeAdder{theConfig},
105 "Use the given bucket as a storage volume. Can be given multiple times.")
110 fmt.Sprintf("AWS region used for subsequent -s3-bucket-volume arguments. Allowed values are %+q.", s3regions()))
115 "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\".")
118 "s3-access-key-file",
120 "`File` containing the access key used for subsequent -s3-bucket-volume arguments.")
123 "s3-secret-key-file",
125 "`File` containing the secret key used for subsequent -s3-bucket-volume arguments.")
130 "Maximum eventual consistency latency for subsequent -s3-bucket-volume arguments.")
135 "Replication level reported to clients for subsequent -s3-bucket-volume arguments.")
140 "EXPERIMENTAL. Enable deletion (garbage collection) even when trash lifetime is zero, even though there are known race conditions that can cause data loss.")
143 // S3Volume implements Volume using an S3 bucket.
144 type S3Volume struct {
150 LocationConstraint bool
153 ConnectTimeout arvados.Duration
154 ReadTimeout arvados.Duration
155 RaceWindow arvados.Duration
158 StorageClasses []string
165 // Examples implements VolumeWithExamples.
166 func (*S3Volume) Examples() []Volume {
169 AccessKeyFile: "/etc/aws_s3_access_key.txt",
170 SecretKeyFile: "/etc/aws_s3_secret_key.txt",
173 Bucket: "example-bucket-name",
176 RaceWindow: arvados.Duration(24 * time.Hour),
177 ConnectTimeout: arvados.Duration(time.Minute),
178 ReadTimeout: arvados.Duration(5 * time.Minute),
181 AccessKeyFile: "/etc/gce_s3_access_key.txt",
182 SecretKeyFile: "/etc/gce_s3_secret_key.txt",
183 Endpoint: "https://storage.googleapis.com",
185 Bucket: "example-bucket-name",
188 RaceWindow: arvados.Duration(24 * time.Hour),
189 ConnectTimeout: arvados.Duration(time.Minute),
190 ReadTimeout: arvados.Duration(5 * time.Minute),
195 // Type implements Volume.
196 func (*S3Volume) Type() string {
200 // Start populates private fields and verifies the configuration is
202 func (v *S3Volume) Start(opsCounters, errCounters, ioBytes *prometheus.CounterVec) error {
203 region, ok := aws.Regions[v.Region]
204 if v.Endpoint == "" {
206 return fmt.Errorf("unrecognized region %+q; try specifying -s3-endpoint instead", v.Region)
209 return fmt.Errorf("refusing to use AWS region name %+q with endpoint %+q; "+
210 "specify empty endpoint (\"-s3-endpoint=\") or use a different region name", v.Region, v.Endpoint)
214 S3Endpoint: v.Endpoint,
215 S3LocationConstraint: v.LocationConstraint,
221 auth.AccessKey, err = readKeyFromFile(v.AccessKeyFile)
225 auth.SecretKey, err = readKeyFromFile(v.SecretKeyFile)
230 // Zero timeouts mean "wait forever", which is a bad
231 // default. Default to long timeouts instead.
232 if v.ConnectTimeout == 0 {
233 v.ConnectTimeout = s3DefaultConnectTimeout
235 if v.ReadTimeout == 0 {
236 v.ReadTimeout = s3DefaultReadTimeout
239 client := s3.New(auth, region)
240 if region.EC2Endpoint.Signer == aws.V4Signature {
241 // Currently affects only eu-central-1
242 client.Signature = aws.V4Signature
244 client.ConnectTimeout = time.Duration(v.ConnectTimeout)
245 client.ReadTimeout = time.Duration(v.ReadTimeout)
246 v.bucket = &s3bucket{
255 // DeviceID returns a globally unique ID for the storage bucket.
256 func (v *S3Volume) DeviceID() string {
257 return "s3://" + v.Endpoint + "/" + v.Bucket
260 func (v *S3Volume) getReaderWithContext(ctx context.Context, loc string) (rdr io.ReadCloser, err error) {
261 ready := make(chan bool)
263 rdr, err = v.getReader(loc)
270 theConfig.debugLogf("s3: abandoning getReader(): %s", ctx.Err())
277 return nil, ctx.Err()
281 // getReader wraps (Bucket)GetReader.
283 // In situations where (Bucket)GetReader would fail because the block
284 // disappeared in a Trash race, getReader calls fixRace to recover the
285 // data, and tries again.
286 func (v *S3Volume) getReader(loc string) (rdr io.ReadCloser, err error) {
287 rdr, err = v.bucket.GetReader(loc)
288 err = v.translateError(err)
289 if err == nil || !os.IsNotExist(err) {
293 _, err = v.bucket.Head("recent/"+loc, nil)
294 err = v.translateError(err)
296 // If we can't read recent/X, there's no point in
297 // trying fixRace. Give up.
305 rdr, err = v.bucket.GetReader(loc)
307 log.Printf("warning: reading %s after successful fixRace: %s", loc, err)
308 err = v.translateError(err)
313 // Get a block: copy the block data into buf, and return the number of
315 func (v *S3Volume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
316 rdr, err := v.getReaderWithContext(ctx, loc)
322 ready := make(chan bool)
327 n, err = io.ReadFull(rdr, buf)
330 case nil, io.EOF, io.ErrUnexpectedEOF:
333 err = v.translateError(err)
338 theConfig.debugLogf("s3: interrupting ReadFull() with Close() because %s", ctx.Err())
340 // Must wait for ReadFull to return, to ensure it
341 // doesn't write to buf after we return.
342 theConfig.debugLogf("s3: waiting for ReadFull() to fail")
350 // Compare the given data with the stored data.
351 func (v *S3Volume) Compare(ctx context.Context, loc string, expect []byte) error {
352 errChan := make(chan error, 1)
354 _, err := v.bucket.Head("recent/"+loc, nil)
361 case err = <-errChan:
364 // Checking for "loc" itself here would interfere with
365 // future GET requests.
367 // On AWS, if X doesn't exist, a HEAD or GET request
368 // for X causes X's non-existence to be cached. Thus,
369 // if we test for X, then create X and return a
370 // signature to our client, the client might still get
371 // 404 from all keepstores when trying to read it.
373 // To avoid this, we avoid doing HEAD X or GET X until
374 // we know X has been written.
376 // Note that X might exist even though recent/X
377 // doesn't: for example, the response to HEAD recent/X
378 // might itself come from a stale cache. In such
379 // cases, we will return a false negative and
380 // PutHandler might needlessly create another replica
381 // on a different volume. That's not ideal, but it's
382 // better than passing the eventually-consistent
383 // problem on to our clients.
384 return v.translateError(err)
386 rdr, err := v.getReaderWithContext(ctx, loc)
391 return v.translateError(compareReaderWithBuf(ctx, rdr, expect, loc[:32]))
394 // Put writes a block.
395 func (v *S3Volume) Put(ctx context.Context, loc string, block []byte) error {
397 return MethodDisabledError
402 md5, err := hex.DecodeString(loc)
406 opts.ContentMD5 = base64.StdEncoding.EncodeToString(md5)
407 // In AWS regions that use V4 signatures, we need to
408 // provide ContentSHA256 up front. Otherwise, the S3
409 // library reads the request body (from our buffer)
410 // into another new buffer in order to compute the
411 // SHA256 before sending the request -- which would
412 // mean consuming 128 MiB of memory for the duration
413 // of a 64 MiB write.
414 opts.ContentSHA256 = fmt.Sprintf("%x", sha256.Sum256(block))
417 // Send the block data through a pipe, so that (if we need to)
418 // we can close the pipe early and abandon our PutReader()
419 // goroutine, without worrying about PutReader() accessing our
420 // block buffer after we release it.
421 bufr, bufw := io.Pipe()
423 io.Copy(bufw, bytes.NewReader(block))
428 ready := make(chan bool)
431 if ctx.Err() != nil {
432 theConfig.debugLogf("%s: abandoned PutReader goroutine finished with err: %s", v, err)
436 err = v.bucket.PutReader(loc, bufr, int64(size), "application/octet-stream", s3ACL, opts)
440 err = v.bucket.PutReader("recent/"+loc, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
444 theConfig.debugLogf("%s: taking PutReader's input away: %s", v, ctx.Err())
445 // Our pipe might be stuck in Write(), waiting for
446 // PutReader() to read. If so, un-stick it. This means
447 // PutReader will get corrupt data, but that's OK: the
448 // size and MD5 won't match, so the write will fail.
449 go io.Copy(ioutil.Discard, bufr)
450 // CloseWithError() will return once pending I/O is done.
451 bufw.CloseWithError(ctx.Err())
452 theConfig.debugLogf("%s: abandoning PutReader goroutine", v)
455 // Unblock pipe in case PutReader did not consume it.
456 io.Copy(ioutil.Discard, bufr)
457 return v.translateError(err)
461 // Touch sets the timestamp for the given locator to the current time.
462 func (v *S3Volume) Touch(loc string) error {
464 return MethodDisabledError
466 _, err := v.bucket.Head(loc, nil)
467 err = v.translateError(err)
468 if os.IsNotExist(err) && v.fixRace(loc) {
469 // The data object got trashed in a race, but fixRace
471 } else if err != nil {
474 err = v.bucket.PutReader("recent/"+loc, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
475 return v.translateError(err)
478 // Mtime returns the stored timestamp for the given locator.
479 func (v *S3Volume) Mtime(loc string) (time.Time, error) {
480 _, err := v.bucket.Head(loc, nil)
482 return zeroTime, v.translateError(err)
484 resp, err := v.bucket.Head("recent/"+loc, nil)
485 err = v.translateError(err)
486 if os.IsNotExist(err) {
487 // The data object X exists, but recent/X is missing.
488 err = v.bucket.PutReader("recent/"+loc, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
490 log.Printf("error: creating %q: %s", "recent/"+loc, err)
491 return zeroTime, v.translateError(err)
493 log.Printf("info: created %q to migrate existing block to new storage scheme", "recent/"+loc)
494 resp, err = v.bucket.Head("recent/"+loc, nil)
496 log.Printf("error: created %q but HEAD failed: %s", "recent/"+loc, err)
497 return zeroTime, v.translateError(err)
499 } else if err != nil {
500 // HEAD recent/X failed for some other reason.
503 return v.lastModified(resp)
506 // IndexTo writes a complete list of locators with the given prefix
507 // for which Get() can retrieve data.
508 func (v *S3Volume) IndexTo(prefix string, writer io.Writer) error {
509 // Use a merge sort to find matching sets of X and recent/X.
511 Bucket: v.bucket.Bucket,
513 PageSize: v.IndexPageSize,
514 Stats: &v.bucket.stats,
517 Bucket: v.bucket.Bucket,
518 Prefix: "recent/" + prefix,
519 PageSize: v.IndexPageSize,
520 Stats: &v.bucket.stats,
522 for data, recent := dataL.First(), recentL.First(); data != nil && dataL.Error() == nil; data = dataL.Next() {
524 // Conveniently, "recent/*" and "trash/*" are
525 // lexically greater than all hex-encoded data
526 // hashes, so stopping here avoids iterating
527 // over all of them needlessly with dataL.
530 if !v.isKeepBlock(data.Key) {
534 // stamp is the list entry we should use to report the
535 // last-modified time for this data block: it will be
536 // the recent/X entry if one exists, otherwise the
537 // entry for the data block itself.
540 // Advance to the corresponding recent/X marker, if any
541 for recent != nil && recentL.Error() == nil {
542 if cmp := strings.Compare(recent.Key[7:], data.Key); cmp < 0 {
543 recent = recentL.Next()
547 recent = recentL.Next()
550 // recent/X marker is missing: we'll
551 // use the timestamp on the data
556 if err := recentL.Error(); err != nil {
559 t, err := time.Parse(time.RFC3339, stamp.LastModified)
563 fmt.Fprintf(writer, "%s+%d %d\n", data.Key, data.Size, t.UnixNano())
568 // Trash a Keep block.
569 func (v *S3Volume) Trash(loc string) error {
571 return MethodDisabledError
573 if t, err := v.Mtime(loc); err != nil {
575 } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
578 if theConfig.TrashLifetime == 0 {
580 return ErrS3TrashDisabled
582 return v.translateError(v.bucket.Del(loc))
584 err := v.checkRaceWindow(loc)
588 err = v.safeCopy("trash/"+loc, loc)
592 return v.translateError(v.bucket.Del(loc))
595 // checkRaceWindow returns a non-nil error if trash/loc is, or might
596 // be, in the race window (i.e., it's not safe to trash loc).
597 func (v *S3Volume) checkRaceWindow(loc string) error {
598 resp, err := v.bucket.Head("trash/"+loc, nil)
599 err = v.translateError(err)
600 if os.IsNotExist(err) {
601 // OK, trash/X doesn't exist so we're not in the race
604 } else if err != nil {
605 // Error looking up trash/X. We don't know whether
606 // we're in the race window
609 t, err := v.lastModified(resp)
611 // Can't parse timestamp
614 safeWindow := t.Add(theConfig.TrashLifetime.Duration()).Sub(time.Now().Add(time.Duration(v.RaceWindow)))
616 // We can't count on "touch trash/X" to prolong
617 // trash/X's lifetime. The new timestamp might not
618 // become visible until now+raceWindow, and EmptyTrash
619 // is allowed to delete trash/X before then.
620 return fmt.Errorf("same block is already in trash, and safe window ended %s ago", -safeWindow)
622 // trash/X exists, but it won't be eligible for deletion until
623 // after now+raceWindow, so it's safe to overwrite it.
627 // safeCopy calls PutCopy, and checks the response to make sure the
628 // copy succeeded and updated the timestamp on the destination object
629 // (PutCopy returns 200 OK if the request was received, even if the
631 func (v *S3Volume) safeCopy(dst, src string) error {
632 resp, err := v.bucket.PutCopy(dst, s3ACL, s3.CopyOptions{
633 ContentType: "application/octet-stream",
634 MetadataDirective: "REPLACE",
635 }, v.bucket.Name+"/"+src)
636 err = v.translateError(err)
637 if os.IsNotExist(err) {
639 } else if err != nil {
640 return fmt.Errorf("PutCopy(%q ← %q): %s", dst, v.bucket.Name+"/"+src, err)
642 if t, err := time.Parse(time.RFC3339Nano, resp.LastModified); err != nil {
643 return fmt.Errorf("PutCopy succeeded but did not return a timestamp: %q: %s", resp.LastModified, err)
644 } else if time.Now().Sub(t) > maxClockSkew {
645 return fmt.Errorf("PutCopy succeeded but returned an old timestamp: %q: %s", resp.LastModified, t)
650 // Get the LastModified header from resp, and parse it as RFC1123 or
651 // -- if it isn't valid RFC1123 -- as Amazon's variant of RFC1123.
652 func (v *S3Volume) lastModified(resp *http.Response) (t time.Time, err error) {
653 s := resp.Header.Get("Last-Modified")
654 t, err = time.Parse(time.RFC1123, s)
655 if err != nil && s != "" {
656 // AWS example is "Sun, 1 Jan 2006 12:00:00 GMT",
657 // which isn't quite "Sun, 01 Jan 2006 12:00:00 GMT"
658 // as required by HTTP spec. If it's not a valid HTTP
659 // header value, it's probably AWS (or s3test) giving
660 // us a nearly-RFC1123 timestamp.
661 t, err = time.Parse(nearlyRFC1123, s)
666 // Untrash moves block from trash back into store
667 func (v *S3Volume) Untrash(loc string) error {
668 err := v.safeCopy(loc, "trash/"+loc)
672 err = v.bucket.PutReader("recent/"+loc, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
673 return v.translateError(err)
676 // Status returns a *VolumeStatus representing the current in-use
677 // storage capacity and a fake available capacity that doesn't make
678 // the volume seem full or nearly-full.
679 func (v *S3Volume) Status() *VolumeStatus {
680 return &VolumeStatus{
682 BytesFree: BlockSize * 1000,
687 // InternalStats returns bucket I/O and API call counters.
688 func (v *S3Volume) InternalStats() interface{} {
689 return &v.bucket.stats
692 // String implements fmt.Stringer.
693 func (v *S3Volume) String() string {
694 return fmt.Sprintf("s3-bucket:%+q", v.Bucket)
697 // Writable returns false if all future Put, Mtime, and Delete calls
698 // are expected to fail.
699 func (v *S3Volume) Writable() bool {
703 // Replication returns the storage redundancy of the underlying
704 // device. Configured via command line flag.
705 func (v *S3Volume) Replication() int {
706 return v.S3Replication
709 // GetStorageClasses implements Volume
710 func (v *S3Volume) GetStorageClasses() []string {
711 return v.StorageClasses
714 var s3KeepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
716 func (v *S3Volume) isKeepBlock(s string) bool {
717 return s3KeepBlockRegexp.MatchString(s)
720 // fixRace(X) is called when "recent/X" exists but "X" doesn't
721 // exist. If the timestamps on "recent/"+loc and "trash/"+loc indicate
722 // there was a race between Put and Trash, fixRace recovers from the
723 // race by Untrashing the block.
724 func (v *S3Volume) fixRace(loc string) bool {
725 trash, err := v.bucket.Head("trash/"+loc, nil)
727 if !os.IsNotExist(v.translateError(err)) {
728 log.Printf("error: fixRace: HEAD %q: %s", "trash/"+loc, err)
732 trashTime, err := v.lastModified(trash)
734 log.Printf("error: fixRace: parse %q: %s", trash.Header.Get("Last-Modified"), err)
738 recent, err := v.bucket.Head("recent/"+loc, nil)
740 log.Printf("error: fixRace: HEAD %q: %s", "recent/"+loc, err)
743 recentTime, err := v.lastModified(recent)
745 log.Printf("error: fixRace: parse %q: %s", recent.Header.Get("Last-Modified"), err)
749 ageWhenTrashed := trashTime.Sub(recentTime)
750 if ageWhenTrashed >= theConfig.BlobSignatureTTL.Duration() {
751 // No evidence of a race: block hasn't been written
752 // since it became eligible for Trash. No fix needed.
756 log.Printf("notice: fixRace: %q: trashed at %s but touched at %s (age when trashed = %s < %s)", loc, trashTime, recentTime, ageWhenTrashed, theConfig.BlobSignatureTTL)
757 log.Printf("notice: fixRace: copying %q to %q to recover from race between Put/Touch and Trash", "recent/"+loc, loc)
758 err = v.safeCopy(loc, "trash/"+loc)
760 log.Printf("error: fixRace: %s", err)
766 func (v *S3Volume) translateError(err error) error {
767 switch err := err.(type) {
769 if (err.StatusCode == http.StatusNotFound && err.Code == "NoSuchKey") ||
770 strings.Contains(err.Error(), "Not Found") {
771 return os.ErrNotExist
773 // Other 404 errors like NoSuchVersion and
774 // NoSuchBucket are different problems which should
775 // get called out downstream, so we don't convert them
776 // to os.ErrNotExist.
781 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
782 // and deletes them from the volume.
783 func (v *S3Volume) EmptyTrash() {
784 var bytesInTrash, blocksInTrash, bytesDeleted, blocksDeleted int64
786 // Define "ready to delete" as "...when EmptyTrash started".
789 emptyOneKey := func(trash *s3.Key) {
791 if !v.isKeepBlock(loc) {
794 atomic.AddInt64(&bytesInTrash, trash.Size)
795 atomic.AddInt64(&blocksInTrash, 1)
797 trashT, err := time.Parse(time.RFC3339, trash.LastModified)
799 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, trash.Key, trash.LastModified, err)
802 recent, err := v.bucket.Head("recent/"+loc, nil)
803 if err != nil && os.IsNotExist(v.translateError(err)) {
804 log.Printf("warning: %s: EmptyTrash: found trash marker %q but no %q (%s); calling Untrash", v, trash.Key, "recent/"+loc, err)
807 log.Printf("error: %s: EmptyTrash: Untrash(%q): %s", v, loc, err)
810 } else if err != nil {
811 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, "recent/"+loc, err)
814 recentT, err := v.lastModified(recent)
816 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, "recent/"+loc, recent.Header.Get("Last-Modified"), err)
819 if trashT.Sub(recentT) < theConfig.BlobSignatureTTL.Duration() {
820 if age := startT.Sub(recentT); age >= theConfig.BlobSignatureTTL.Duration()-time.Duration(v.RaceWindow) {
821 // recent/loc is too old to protect
822 // loc from being Trashed again during
823 // the raceWindow that starts if we
824 // delete trash/X now.
826 // Note this means (TrashCheckInterval
827 // < BlobSignatureTTL - raceWindow) is
828 // necessary to avoid starvation.
829 log.Printf("notice: %s: EmptyTrash: detected old race for %q, calling fixRace + Touch", v, loc)
834 _, err := v.bucket.Head(loc, nil)
835 if os.IsNotExist(err) {
836 log.Printf("notice: %s: EmptyTrash: detected recent race for %q, calling fixRace", v, loc)
839 } else if err != nil {
840 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, loc, err)
844 if startT.Sub(trashT) < theConfig.TrashLifetime.Duration() {
847 err = v.bucket.Del(trash.Key)
849 log.Printf("warning: %s: EmptyTrash: deleting %q: %s", v, trash.Key, err)
852 atomic.AddInt64(&bytesDeleted, trash.Size)
853 atomic.AddInt64(&blocksDeleted, 1)
855 _, err = v.bucket.Head(loc, nil)
857 log.Printf("warning: %s: EmptyTrash: HEAD %q succeeded immediately after deleting %q", v, loc, loc)
860 if !os.IsNotExist(v.translateError(err)) {
861 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, loc, err)
864 err = v.bucket.Del("recent/" + loc)
866 log.Printf("warning: %s: EmptyTrash: deleting %q: %s", v, "recent/"+loc, err)
870 var wg sync.WaitGroup
871 todo := make(chan *s3.Key, theConfig.EmptyTrashWorkers)
872 for i := 0; i < 1 || i < theConfig.EmptyTrashWorkers; i++ {
876 for key := range todo {
883 Bucket: v.bucket.Bucket,
885 PageSize: v.IndexPageSize,
886 Stats: &v.bucket.stats,
888 for trash := trashL.First(); trash != nil; trash = trashL.Next() {
894 if err := trashL.Error(); err != nil {
895 log.Printf("error: %s: EmptyTrash: lister: %s", v, err)
897 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)
900 type s3Lister struct {
910 // First fetches the first page and returns the first item. It returns
911 // nil if the response is the empty set or an error occurs.
912 func (lister *s3Lister) First() *s3.Key {
917 // Next returns the next item, fetching the next page if necessary. It
918 // returns nil if the last available item has already been fetched, or
920 func (lister *s3Lister) Next() *s3.Key {
921 if len(lister.buf) == 0 && lister.nextMarker != "" {
927 // Return the most recent error encountered by First or Next.
928 func (lister *s3Lister) Error() error {
932 func (lister *s3Lister) getPage() {
933 lister.Stats.Tick(&lister.Stats.Ops, &lister.Stats.ListOps)
934 resp, err := lister.Bucket.List(lister.Prefix, "", lister.nextMarker, lister.PageSize)
935 lister.nextMarker = ""
940 if resp.IsTruncated {
941 lister.nextMarker = resp.NextMarker
943 lister.buf = make([]s3.Key, 0, len(resp.Contents))
944 for _, key := range resp.Contents {
945 if !strings.HasPrefix(key.Key, lister.Prefix) {
946 log.Printf("warning: s3Lister: S3 Bucket.List(prefix=%q) returned key %q", lister.Prefix, key.Key)
949 lister.buf = append(lister.buf, key)
953 func (lister *s3Lister) pop() (k *s3.Key) {
954 if len(lister.buf) > 0 {
956 lister.buf = lister.buf[1:]
961 // s3bucket wraps s3.bucket and counts I/O and API usage stats.
962 type s3bucket struct {
967 func (b *s3bucket) GetReader(path string) (io.ReadCloser, error) {
968 rdr, err := b.Bucket.GetReader(path)
969 b.stats.Tick(&b.stats.Ops, &b.stats.GetOps)
971 return NewCountingReader(rdr, b.stats.TickInBytes), err
974 func (b *s3bucket) Head(path string, headers map[string][]string) (*http.Response, error) {
975 resp, err := b.Bucket.Head(path, headers)
976 b.stats.Tick(&b.stats.Ops, &b.stats.HeadOps)
981 func (b *s3bucket) PutReader(path string, r io.Reader, length int64, contType string, perm s3.ACL, options s3.Options) error {
983 // goamz will only send Content-Length: 0 when reader
984 // is nil due to net.http.Request.ContentLength
985 // behavior. Otherwise, Content-Length header is
986 // omitted which will cause some S3 services
987 // (including AWS and Ceph RadosGW) to fail to create
991 r = NewCountingReader(r, b.stats.TickOutBytes)
993 err := b.Bucket.PutReader(path, r, length, contType, perm, options)
994 b.stats.Tick(&b.stats.Ops, &b.stats.PutOps)
999 func (b *s3bucket) Del(path string) error {
1000 err := b.Bucket.Del(path)
1001 b.stats.Tick(&b.stats.Ops, &b.stats.DelOps)
1002 b.stats.TickErr(err)
1006 type s3bucketStats struct {
1016 func (s *s3bucketStats) TickErr(err error) {
1020 errType := fmt.Sprintf("%T", err)
1021 if err, ok := err.(*s3.Error); ok {
1022 errType = errType + fmt.Sprintf(" %d %s", err.StatusCode, err.Code)
1024 s.statsTicker.TickErr(err, errType)