17 "git.curoverse.com/arvados.git/sdk/go/arvados"
18 "github.com/AdRoll/goamz/aws"
19 "github.com/AdRoll/goamz/s3"
23 // ErrS3TrashDisabled is returned by Trash if that operation
24 // is impossible with the current config.
25 ErrS3TrashDisabled = fmt.Errorf("trash function is disabled because -trash-lifetime=0 and -s3-unsafe-delete=false")
27 s3AccessKeyFile string
28 s3SecretKeyFile string
33 s3RaceWindow time.Duration
39 maxClockSkew = 600 * time.Second
40 nearlyRFC1123 = "Mon, 2 Jan 2006 15:04:05 GMT"
43 type s3VolumeAdder struct {
47 // String implements flag.Value
48 func (s *s3VolumeAdder) String() string {
52 func (s *s3VolumeAdder) Set(bucketName string) error {
54 return fmt.Errorf("no container name given")
56 if s3AccessKeyFile == "" || s3SecretKeyFile == "" {
57 return fmt.Errorf("-s3-access-key-file and -s3-secret-key-file arguments must given before -s3-bucket-volume")
59 if deprecated.flagSerializeIO {
60 log.Print("Notice: -serialize is not supported by s3-bucket volumes.")
62 s.Config.Volumes = append(s.Config.Volumes, &S3Volume{
64 AccessKeyFile: s3AccessKeyFile,
65 SecretKeyFile: s3SecretKeyFile,
68 RaceWindow: arvados.Duration(s3RaceWindow),
69 S3Replication: s3Replication,
70 UnsafeDelete: s3UnsafeDelete,
71 ReadOnly: deprecated.flagReadonly,
77 func s3regions() (okList []string) {
78 for r := range aws.Regions {
79 okList = append(okList, r)
85 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &S3Volume{} })
87 flag.Var(&s3VolumeAdder{theConfig},
89 "Use the given bucket as a storage volume. Can be given multiple times.")
94 fmt.Sprintf("AWS region used for subsequent -s3-bucket-volume arguments. Allowed values are %+q.", s3regions()))
99 "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\".")
102 "s3-access-key-file",
104 "`File` containing the access key used for subsequent -s3-bucket-volume arguments.")
107 "s3-secret-key-file",
109 "`File` containing the secret key used for subsequent -s3-bucket-volume arguments.")
114 "Maximum eventual consistency latency for subsequent -s3-bucket-volume arguments.")
119 "Replication level reported to clients for subsequent -s3-bucket-volume arguments.")
124 "EXPERIMENTAL. Enable deletion (garbage collection), even though there are known race conditions that can cause data loss.")
127 // S3Volume implements Volume using an S3 bucket.
128 type S3Volume struct {
134 LocationConstraint bool
137 RaceWindow arvados.Duration
146 // Examples implements VolumeWithExamples.
147 func (*S3Volume) Examples() []Volume {
150 AccessKeyFile: "/etc/aws_s3_access_key.txt",
151 SecretKeyFile: "/etc/aws_s3_secret_key.txt",
154 Bucket: "example-bucket-name",
157 RaceWindow: arvados.Duration(24 * time.Hour),
160 AccessKeyFile: "/etc/gce_s3_access_key.txt",
161 SecretKeyFile: "/etc/gce_s3_secret_key.txt",
162 Endpoint: "https://storage.googleapis.com",
164 Bucket: "example-bucket-name",
167 RaceWindow: arvados.Duration(24 * time.Hour),
172 // Type implements Volume.
173 func (*S3Volume) Type() string {
177 // Start populates private fields and verifies the configuration is
179 func (v *S3Volume) Start() error {
180 region, ok := aws.Regions[v.Region]
181 if v.Endpoint == "" {
183 return fmt.Errorf("unrecognized region %+q; try specifying -s3-endpoint instead", v.Region)
186 return fmt.Errorf("refusing to use AWS region name %+q with endpoint %+q; "+
187 "specify empty endpoint (\"-s3-endpoint=\") or use a different region name", v.Region, v.Endpoint)
191 S3Endpoint: v.Endpoint,
192 S3LocationConstraint: v.LocationConstraint,
198 auth.AccessKey, err = readKeyFromFile(v.AccessKeyFile)
202 auth.SecretKey, err = readKeyFromFile(v.SecretKeyFile)
206 v.bucket = &s3.Bucket{
207 S3: s3.New(auth, region),
213 // getReader wraps (Bucket)GetReader.
215 // In situations where (Bucket)GetReader would fail because the block
216 // disappeared in a Trash race, getReader calls fixRace to recover the
217 // data, and tries again.
218 func (v *S3Volume) getReader(loc string) (rdr io.ReadCloser, err error) {
219 rdr, err = v.bucket.GetReader(loc)
220 err = v.translateError(err)
221 if err == nil || !os.IsNotExist(err) {
224 _, err = v.bucket.Head("recent/"+loc, nil)
225 err = v.translateError(err)
227 // If we can't read recent/X, there's no point in
228 // trying fixRace. Give up.
235 rdr, err = v.bucket.GetReader(loc)
237 log.Printf("warning: reading %s after successful fixRace: %s", loc, err)
238 err = v.translateError(err)
243 // Get a block: copy the block data into buf, and return the number of
245 func (v *S3Volume) Get(loc string, buf []byte) (int, error) {
246 rdr, err := v.getReader(loc)
251 n, err := io.ReadFull(rdr, buf)
253 case nil, io.EOF, io.ErrUnexpectedEOF:
256 return 0, v.translateError(err)
260 // Compare the given data with the stored data.
261 func (v *S3Volume) Compare(loc string, expect []byte) error {
262 rdr, err := v.getReader(loc)
267 return v.translateError(compareReaderWithBuf(rdr, expect, loc[:32]))
270 // Put writes a block.
271 func (v *S3Volume) Put(loc string, block []byte) error {
273 return MethodDisabledError
277 md5, err := hex.DecodeString(loc)
281 opts.ContentMD5 = base64.StdEncoding.EncodeToString(md5)
283 err := v.bucket.Put(loc, block, "application/octet-stream", s3ACL, opts)
285 return v.translateError(err)
287 err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
288 return v.translateError(err)
291 // Touch sets the timestamp for the given locator to the current time.
292 func (v *S3Volume) Touch(loc string) error {
294 return MethodDisabledError
296 _, err := v.bucket.Head(loc, nil)
297 err = v.translateError(err)
298 if os.IsNotExist(err) && v.fixRace(loc) {
299 // The data object got trashed in a race, but fixRace
301 } else if err != nil {
304 err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
305 return v.translateError(err)
308 // Mtime returns the stored timestamp for the given locator.
309 func (v *S3Volume) Mtime(loc string) (time.Time, error) {
310 _, err := v.bucket.Head(loc, nil)
312 return zeroTime, v.translateError(err)
314 resp, err := v.bucket.Head("recent/"+loc, nil)
315 err = v.translateError(err)
316 if os.IsNotExist(err) {
317 // The data object X exists, but recent/X is missing.
318 err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
320 log.Printf("error: creating %q: %s", "recent/"+loc, err)
321 return zeroTime, v.translateError(err)
323 log.Printf("info: created %q to migrate existing block to new storage scheme", "recent/"+loc)
324 resp, err = v.bucket.Head("recent/"+loc, nil)
326 log.Printf("error: created %q but HEAD failed: %s", "recent/"+loc, err)
327 return zeroTime, v.translateError(err)
329 } else if err != nil {
330 // HEAD recent/X failed for some other reason.
333 return v.lastModified(resp)
336 // IndexTo writes a complete list of locators with the given prefix
337 // for which Get() can retrieve data.
338 func (v *S3Volume) IndexTo(prefix string, writer io.Writer) error {
339 // Use a merge sort to find matching sets of X and recent/X.
343 PageSize: v.IndexPageSize,
347 Prefix: "recent/" + prefix,
348 PageSize: v.IndexPageSize,
350 for data, recent := dataL.First(), recentL.First(); data != nil; data = dataL.Next() {
352 // Conveniently, "recent/*" and "trash/*" are
353 // lexically greater than all hex-encoded data
354 // hashes, so stopping here avoids iterating
355 // over all of them needlessly with dataL.
358 if !v.isKeepBlock(data.Key) {
362 // stamp is the list entry we should use to report the
363 // last-modified time for this data block: it will be
364 // the recent/X entry if one exists, otherwise the
365 // entry for the data block itself.
368 // Advance to the corresponding recent/X marker, if any
370 if cmp := strings.Compare(recent.Key[7:], data.Key); cmp < 0 {
371 recent = recentL.Next()
375 recent = recentL.Next()
378 // recent/X marker is missing: we'll
379 // use the timestamp on the data
384 t, err := time.Parse(time.RFC3339, stamp.LastModified)
388 fmt.Fprintf(writer, "%s+%d %d\n", data.Key, data.Size, t.UnixNano())
393 // Trash a Keep block.
394 func (v *S3Volume) Trash(loc string) error {
396 return MethodDisabledError
398 if t, err := v.Mtime(loc); err != nil {
400 } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
403 if theConfig.TrashLifetime == 0 {
405 return ErrS3TrashDisabled
407 return v.bucket.Del(loc)
409 err := v.checkRaceWindow(loc)
413 err = v.safeCopy("trash/"+loc, loc)
417 return v.translateError(v.bucket.Del(loc))
420 // checkRaceWindow returns a non-nil error if trash/loc is, or might
421 // be, in the race window (i.e., it's not safe to trash loc).
422 func (v *S3Volume) checkRaceWindow(loc string) error {
423 resp, err := v.bucket.Head("trash/"+loc, nil)
424 err = v.translateError(err)
425 if os.IsNotExist(err) {
426 // OK, trash/X doesn't exist so we're not in the race
429 } else if err != nil {
430 // Error looking up trash/X. We don't know whether
431 // we're in the race window
434 t, err := v.lastModified(resp)
436 // Can't parse timestamp
439 safeWindow := t.Add(theConfig.TrashLifetime.Duration()).Sub(time.Now().Add(time.Duration(v.RaceWindow)))
441 // We can't count on "touch trash/X" to prolong
442 // trash/X's lifetime. The new timestamp might not
443 // become visible until now+raceWindow, and EmptyTrash
444 // is allowed to delete trash/X before then.
445 return fmt.Errorf("same block is already in trash, and safe window ended %s ago", -safeWindow)
447 // trash/X exists, but it won't be eligible for deletion until
448 // after now+raceWindow, so it's safe to overwrite it.
452 // safeCopy calls PutCopy, and checks the response to make sure the
453 // copy succeeded and updated the timestamp on the destination object
454 // (PutCopy returns 200 OK if the request was received, even if the
456 func (v *S3Volume) safeCopy(dst, src string) error {
457 resp, err := v.bucket.PutCopy(dst, s3ACL, s3.CopyOptions{
458 ContentType: "application/octet-stream",
459 MetadataDirective: "REPLACE",
460 }, v.bucket.Name+"/"+src)
461 err = v.translateError(err)
465 if t, err := time.Parse(time.RFC3339Nano, resp.LastModified); err != nil {
466 return fmt.Errorf("PutCopy succeeded but did not return a timestamp: %q: %s", resp.LastModified, err)
467 } else if time.Now().Sub(t) > maxClockSkew {
468 return fmt.Errorf("PutCopy succeeded but returned an old timestamp: %q: %s", resp.LastModified, t)
473 // Get the LastModified header from resp, and parse it as RFC1123 or
474 // -- if it isn't valid RFC1123 -- as Amazon's variant of RFC1123.
475 func (v *S3Volume) lastModified(resp *http.Response) (t time.Time, err error) {
476 s := resp.Header.Get("Last-Modified")
477 t, err = time.Parse(time.RFC1123, s)
478 if err != nil && s != "" {
479 // AWS example is "Sun, 1 Jan 2006 12:00:00 GMT",
480 // which isn't quite "Sun, 01 Jan 2006 12:00:00 GMT"
481 // as required by HTTP spec. If it's not a valid HTTP
482 // header value, it's probably AWS (or s3test) giving
483 // us a nearly-RFC1123 timestamp.
484 t, err = time.Parse(nearlyRFC1123, s)
489 // Untrash moves block from trash back into store
490 func (v *S3Volume) Untrash(loc string) error {
491 err := v.safeCopy(loc, "trash/"+loc)
495 err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
496 return v.translateError(err)
499 // Status returns a *VolumeStatus representing the current in-use
500 // storage capacity and a fake available capacity that doesn't make
501 // the volume seem full or nearly-full.
502 func (v *S3Volume) Status() *VolumeStatus {
503 return &VolumeStatus{
505 BytesFree: BlockSize * 1000,
510 // String implements fmt.Stringer.
511 func (v *S3Volume) String() string {
512 return fmt.Sprintf("s3-bucket:%+q", v.bucket.Name)
515 // Writable returns false if all future Put, Mtime, and Delete calls
516 // are expected to fail.
517 func (v *S3Volume) Writable() bool {
521 // Replication returns the storage redundancy of the underlying
522 // device. Configured via command line flag.
523 func (v *S3Volume) Replication() int {
524 return v.S3Replication
527 var s3KeepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
529 func (v *S3Volume) isKeepBlock(s string) bool {
530 return s3KeepBlockRegexp.MatchString(s)
533 // fixRace(X) is called when "recent/X" exists but "X" doesn't
534 // exist. If the timestamps on "recent/"+loc and "trash/"+loc indicate
535 // there was a race between Put and Trash, fixRace recovers from the
536 // race by Untrashing the block.
537 func (v *S3Volume) fixRace(loc string) bool {
538 trash, err := v.bucket.Head("trash/"+loc, nil)
540 if !os.IsNotExist(v.translateError(err)) {
541 log.Printf("error: fixRace: HEAD %q: %s", "trash/"+loc, err)
545 trashTime, err := v.lastModified(trash)
547 log.Printf("error: fixRace: parse %q: %s", trash.Header.Get("Last-Modified"), err)
551 recent, err := v.bucket.Head("recent/"+loc, nil)
553 log.Printf("error: fixRace: HEAD %q: %s", "recent/"+loc, err)
556 recentTime, err := v.lastModified(recent)
558 log.Printf("error: fixRace: parse %q: %s", recent.Header.Get("Last-Modified"), err)
562 ageWhenTrashed := trashTime.Sub(recentTime)
563 if ageWhenTrashed >= theConfig.BlobSignatureTTL.Duration() {
564 // No evidence of a race: block hasn't been written
565 // since it became eligible for Trash. No fix needed.
569 log.Printf("notice: fixRace: %q: trashed at %s but touched at %s (age when trashed = %s < %s)", loc, trashTime, recentTime, ageWhenTrashed, theConfig.BlobSignatureTTL)
570 log.Printf("notice: fixRace: copying %q to %q to recover from race between Put/Touch and Trash", "recent/"+loc, loc)
571 err = v.safeCopy(loc, "trash/"+loc)
573 log.Printf("error: fixRace: %s", err)
579 func (v *S3Volume) translateError(err error) error {
580 switch err := err.(type) {
582 if (err.StatusCode == http.StatusNotFound && err.Code == "NoSuchKey") ||
583 strings.Contains(err.Error(), "Not Found") {
584 return os.ErrNotExist
586 // Other 404 errors like NoSuchVersion and
587 // NoSuchBucket are different problems which should
588 // get called out downstream, so we don't convert them
589 // to os.ErrNotExist.
594 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
595 // and deletes them from the volume.
596 func (v *S3Volume) EmptyTrash() {
597 var bytesInTrash, blocksInTrash, bytesDeleted, blocksDeleted int64
599 // Use a merge sort to find matching sets of trash/X and recent/X.
603 PageSize: v.IndexPageSize,
605 // Define "ready to delete" as "...when EmptyTrash started".
607 for trash := trashL.First(); trash != nil; trash = trashL.Next() {
609 if !v.isKeepBlock(loc) {
612 bytesInTrash += trash.Size
615 trashT, err := time.Parse(time.RFC3339, trash.LastModified)
617 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, trash.Key, trash.LastModified, err)
620 recent, err := v.bucket.Head("recent/"+loc, nil)
621 if err != nil && os.IsNotExist(v.translateError(err)) {
622 log.Printf("warning: %s: EmptyTrash: found trash marker %q but no %q (%s); calling Untrash", v, trash.Key, "recent/"+loc, err)
625 log.Printf("error: %s: EmptyTrash: Untrash(%q): %s", v, loc, err)
628 } else if err != nil {
629 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, "recent/"+loc, err)
632 recentT, err := v.lastModified(recent)
634 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, "recent/"+loc, recent.Header.Get("Last-Modified"), err)
637 if trashT.Sub(recentT) < theConfig.BlobSignatureTTL.Duration() {
638 if age := startT.Sub(recentT); age >= theConfig.BlobSignatureTTL.Duration()-time.Duration(v.RaceWindow) {
639 // recent/loc is too old to protect
640 // loc from being Trashed again during
641 // the raceWindow that starts if we
642 // delete trash/X now.
644 // Note this means (TrashCheckInterval
645 // < BlobSignatureTTL - raceWindow) is
646 // necessary to avoid starvation.
647 log.Printf("notice: %s: EmptyTrash: detected old race for %q, calling fixRace + Touch", v, loc)
651 } else if _, err := v.bucket.Head(loc, nil); os.IsNotExist(err) {
652 log.Printf("notice: %s: EmptyTrash: detected recent race for %q, calling fixRace", v, loc)
655 } else if err != nil {
656 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, loc, err)
660 if startT.Sub(trashT) < theConfig.TrashLifetime.Duration() {
663 err = v.bucket.Del(trash.Key)
665 log.Printf("warning: %s: EmptyTrash: deleting %q: %s", v, trash.Key, err)
668 bytesDeleted += trash.Size
671 _, err = v.bucket.Head(loc, nil)
672 if os.IsNotExist(err) {
673 err = v.bucket.Del("recent/" + loc)
675 log.Printf("warning: %s: EmptyTrash: deleting %q: %s", v, "recent/"+loc, err)
677 } else if err != nil {
678 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, "recent/"+loc, err)
681 if err := trashL.Error(); err != nil {
682 log.Printf("error: %s: EmptyTrash: lister: %s", v, err)
684 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)
687 type s3Lister struct {
696 // First fetches the first page and returns the first item. It returns
697 // nil if the response is the empty set or an error occurs.
698 func (lister *s3Lister) First() *s3.Key {
703 // Next returns the next item, fetching the next page if necessary. It
704 // returns nil if the last available item has already been fetched, or
706 func (lister *s3Lister) Next() *s3.Key {
707 if len(lister.buf) == 0 && lister.nextMarker != "" {
713 // Return the most recent error encountered by First or Next.
714 func (lister *s3Lister) Error() error {
718 func (lister *s3Lister) getPage() {
719 resp, err := lister.Bucket.List(lister.Prefix, "", lister.nextMarker, lister.PageSize)
720 lister.nextMarker = ""
725 if resp.IsTruncated {
726 lister.nextMarker = resp.NextMarker
728 lister.buf = make([]s3.Key, 0, len(resp.Contents))
729 for _, key := range resp.Contents {
730 if !strings.HasPrefix(key.Key, lister.Prefix) {
731 log.Printf("warning: s3Lister: S3 Bucket.List(prefix=%q) returned key %q", lister.Prefix, key.Key)
734 lister.buf = append(lister.buf, key)
738 func (lister *s3Lister) pop() (k *s3.Key) {
739 if len(lister.buf) > 0 {
741 lister.buf = lister.buf[1:]