16 "github.com/AdRoll/goamz/aws"
17 "github.com/AdRoll/goamz/s3"
21 // Returned by Trash if that operation is impossible with the
23 ErrS3TrashDisabled = fmt.Errorf("trash function is disabled because -trash-lifetime=0 and -s3-unsafe-delete=false")
25 s3AccessKeyFile string
26 s3SecretKeyFile string
31 s3RaceWindow time.Duration
37 maxClockSkew = 600 * time.Second
38 nearlyRFC1123 = "Mon, 2 Jan 2006 15:04:05 GMT"
41 type s3VolumeAdder struct {
45 func (s *s3VolumeAdder) Set(bucketName string) error {
46 if trashLifetime != 0 {
47 return ErrNotImplemented
50 return fmt.Errorf("no container name given")
52 if s3AccessKeyFile == "" || s3SecretKeyFile == "" {
53 return fmt.Errorf("-s3-access-key-file and -s3-secret-key-file arguments must given before -s3-bucket-volume")
55 region, ok := aws.Regions[s3RegionName]
58 return fmt.Errorf("unrecognized region %+q; try specifying -s3-endpoint instead", s3RegionName)
62 return fmt.Errorf("refusing to use AWS region name %+q with endpoint %+q; "+
63 "specify empty endpoint (\"-s3-endpoint=\") or use a different region name", s3RegionName, s3Endpoint)
67 S3Endpoint: s3Endpoint,
72 auth.AccessKey, err = readKeyFromFile(s3AccessKeyFile)
76 auth.SecretKey, err = readKeyFromFile(s3SecretKeyFile)
81 log.Print("Notice: -serialize is not supported by s3-bucket volumes.")
83 v := NewS3Volume(auth, region, bucketName, s3RaceWindow, flagReadonly, s3Replication)
84 if err := v.Check(); err != nil {
87 *s.volumeSet = append(*s.volumeSet, v)
91 func s3regions() (okList []string) {
92 for r := range aws.Regions {
93 okList = append(okList, r)
99 flag.Var(&s3VolumeAdder{&volumes},
101 "Use the given bucket as a storage volume. Can be given multiple times.")
106 fmt.Sprintf("AWS region used for subsequent -s3-bucket-volume arguments. Allowed values are %+q.", s3regions()))
111 "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\".")
114 "s3-access-key-file",
116 "File containing the access key used for subsequent -s3-bucket-volume arguments.")
119 "s3-secret-key-file",
121 "File containing the secret key used for subsequent -s3-bucket-volume arguments.")
126 "Maximum eventual consistency latency for subsequent -s3-bucket-volume arguments.")
131 "Replication level reported to clients for subsequent -s3-bucket-volume arguments.")
136 "EXPERIMENTAL. Enable deletion (garbage collection), even though there are known race conditions that can cause data loss.")
139 // S3Volume implements Volume using an S3 bucket.
140 type S3Volume struct {
142 raceWindow time.Duration
148 // NewS3Volume returns a new S3Volume using the given auth, region,
149 // and bucket name. The replication argument specifies the replication
150 // level to report when writing data.
151 func NewS3Volume(auth aws.Auth, region aws.Region, bucket string, raceWindow time.Duration, readonly bool, replication int) *S3Volume {
154 S3: s3.New(auth, region),
157 raceWindow: raceWindow,
159 replication: replication,
164 // Check returns an error if the volume is inaccessible (e.g., config
166 func (v *S3Volume) Check() error {
170 // getReader wraps (Bucket)GetReader.
172 // In situations where (Bucket)GetReader would fail because the block
173 // disappeared in a Trash race, getReader calls fixRace to recover the
174 // data, and tries again.
175 func (v *S3Volume) getReader(loc string) (rdr io.ReadCloser, err error) {
176 rdr, err = v.Bucket.GetReader(loc)
177 err = v.translateError(err)
178 if err == nil || !os.IsNotExist(err) {
181 _, err = v.Bucket.Head("recent/"+loc, nil)
182 err = v.translateError(err)
184 // If we can't read recent/X, there's no point in
185 // trying fixRace. Give up.
192 rdr, err = v.Bucket.GetReader(loc)
194 log.Printf("warning: reading %s after successful fixRace: %s", loc, err)
195 err = v.translateError(err)
200 // Get a block: copy the block data into buf, and return the number of
202 func (v *S3Volume) Get(loc string, buf []byte) (int, error) {
203 rdr, err := v.getReader(loc)
208 n, err := io.ReadFull(rdr, buf)
210 case nil, io.EOF, io.ErrUnexpectedEOF:
213 return 0, v.translateError(err)
217 // Compare the given data with the stored data.
218 func (v *S3Volume) Compare(loc string, expect []byte) error {
219 rdr, err := v.getReader(loc)
224 return v.translateError(compareReaderWithBuf(rdr, expect, loc[:32]))
227 // Put writes a block.
228 func (v *S3Volume) Put(loc string, block []byte) error {
230 return MethodDisabledError
234 md5, err := hex.DecodeString(loc)
238 opts.ContentMD5 = base64.StdEncoding.EncodeToString(md5)
240 err := v.Bucket.Put(loc, block, "application/octet-stream", s3ACL, opts)
242 return v.translateError(err)
244 err = v.Bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
245 return v.translateError(err)
248 // Touch sets the timestamp for the given locator to the current time.
249 func (v *S3Volume) Touch(loc string) error {
251 return MethodDisabledError
253 _, err := v.Bucket.Head(loc, nil)
254 err = v.translateError(err)
255 if os.IsNotExist(err) && v.fixRace(loc) {
256 // The data object got trashed in a race, but fixRace
258 } else if err != nil {
261 err = v.Bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
262 return v.translateError(err)
265 // Mtime returns the stored timestamp for the given locator.
266 func (v *S3Volume) Mtime(loc string) (time.Time, error) {
267 _, err := v.Bucket.Head(loc, nil)
269 return zeroTime, v.translateError(err)
271 resp, err := v.Bucket.Head("recent/"+loc, nil)
272 err = v.translateError(err)
273 if os.IsNotExist(err) {
274 // The data object X exists, but recent/X is missing.
275 err = v.Bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
277 log.Printf("error: creating %q: %s", "recent/"+loc, err)
278 return zeroTime, v.translateError(err)
280 log.Printf("info: created %q to migrate existing block to new storage scheme", "recent/"+loc)
281 resp, err = v.Bucket.Head("recent/"+loc, nil)
283 log.Printf("error: created %q but HEAD failed: %s", "recent/"+loc, err)
284 return zeroTime, v.translateError(err)
286 } else if err != nil {
287 // HEAD recent/X failed for some other reason.
290 return v.lastModified(resp)
293 // IndexTo writes a complete list of locators with the given prefix
294 // for which Get() can retrieve data.
295 func (v *S3Volume) IndexTo(prefix string, writer io.Writer) error {
296 // Use a merge sort to find matching sets of X and recent/X.
300 PageSize: v.indexPageSize,
304 Prefix: "recent/" + prefix,
305 PageSize: v.indexPageSize,
307 for data, recent := dataL.First(), recentL.First(); data != nil; data = dataL.Next() {
309 // Conveniently, "recent/*" and "trash/*" are
310 // lexically greater than all hex-encoded data
311 // hashes, so stopping here avoids iterating
312 // over all of them needlessly with dataL.
315 if !v.isKeepBlock(data.Key) {
319 // stamp is the list entry we should use to report the
320 // last-modified time for this data block: it will be
321 // the recent/X entry if one exists, otherwise the
322 // entry for the data block itself.
325 // Advance to the corresponding recent/X marker, if any
327 if cmp := strings.Compare(recent.Key[7:], data.Key); cmp < 0 {
328 recent = recentL.Next()
332 recent = recentL.Next()
335 // recent/X marker is missing: we'll
336 // use the timestamp on the data
341 t, err := time.Parse(time.RFC3339, stamp.LastModified)
345 fmt.Fprintf(writer, "%s+%d %d\n", data.Key, data.Size, t.UnixNano())
350 // Trash a Keep block.
351 func (v *S3Volume) Trash(loc string) error {
353 return MethodDisabledError
355 if t, err := v.Mtime(loc); err != nil {
357 } else if time.Since(t) < blobSignatureTTL {
360 if trashLifetime == 0 {
362 return ErrS3TrashDisabled
364 return v.Bucket.Del(loc)
366 err := v.checkRaceWindow(loc)
370 err = v.safeCopy("trash/"+loc, loc)
374 return v.translateError(v.Bucket.Del(loc))
377 // checkRaceWindow returns a non-nil error if trash/loc is, or might
378 // be, in the race window (i.e., it's not safe to trash loc).
379 func (v *S3Volume) checkRaceWindow(loc string) error {
380 resp, err := v.Bucket.Head("trash/"+loc, nil)
381 err = v.translateError(err)
382 if os.IsNotExist(err) {
383 // OK, trash/X doesn't exist so we're not in the race
386 } else if err != nil {
387 // Error looking up trash/X. We don't know whether
388 // we're in the race window
391 t, err := v.lastModified(resp)
393 // Can't parse timestamp
396 safeWindow := t.Add(trashLifetime).Sub(time.Now().Add(v.raceWindow))
398 // We can't count on "touch trash/X" to prolong
399 // trash/X's lifetime. The new timestamp might not
400 // become visible until now+raceWindow, and EmptyTrash
401 // is allowed to delete trash/X before then.
402 return fmt.Errorf("same block is already in trash, and safe window ended %s ago", -safeWindow)
404 // trash/X exists, but it won't be eligible for deletion until
405 // after now+raceWindow, so it's safe to overwrite it.
409 // safeCopy calls PutCopy, and checks the response to make sure the
410 // copy succeeded and updated the timestamp on the destination object
411 // (PutCopy returns 200 OK if the request was received, even if the
413 func (v *S3Volume) safeCopy(dst, src string) error {
414 resp, err := v.Bucket.PutCopy(dst, s3ACL, s3.CopyOptions{
415 ContentType: "application/octet-stream",
416 MetadataDirective: "REPLACE",
417 }, v.Bucket.Name+"/"+src)
418 err = v.translateError(err)
422 if t, err := time.Parse(time.RFC3339Nano, resp.LastModified); err != nil {
423 return fmt.Errorf("PutCopy succeeded but did not return a timestamp: %q: %s", resp.LastModified, err)
424 } else if time.Now().Sub(t) > maxClockSkew {
425 return fmt.Errorf("PutCopy succeeded but returned an old timestamp: %q: %s", resp.LastModified, t)
430 // Get the LastModified header from resp, and parse it as RFC1123 or
431 // -- if it isn't valid RFC1123 -- as Amazon's variant of RFC1123.
432 func (v *S3Volume) lastModified(resp *http.Response) (t time.Time, err error) {
433 s := resp.Header.Get("Last-Modified")
434 t, err = time.Parse(time.RFC1123, s)
435 if err != nil && s != "" {
436 // AWS example is "Sun, 1 Jan 2006 12:00:00 GMT",
437 // which isn't quite "Sun, 01 Jan 2006 12:00:00 GMT"
438 // as required by HTTP spec. If it's not a valid HTTP
439 // header value, it's probably AWS (or s3test) giving
440 // us a nearly-RFC1123 timestamp.
441 t, err = time.Parse(nearlyRFC1123, s)
446 // Untrash moves block from trash back into store
447 func (v *S3Volume) Untrash(loc string) error {
448 err := v.safeCopy(loc, "trash/"+loc)
452 err = v.Bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
453 return v.translateError(err)
456 // Status returns a *VolumeStatus representing the current in-use
457 // storage capacity and a fake available capacity that doesn't make
458 // the volume seem full or nearly-full.
459 func (v *S3Volume) Status() *VolumeStatus {
460 return &VolumeStatus{
462 BytesFree: BlockSize * 1000,
467 // String implements fmt.Stringer.
468 func (v *S3Volume) String() string {
469 return fmt.Sprintf("s3-bucket:%+q", v.Bucket.Name)
472 // Writable returns false if all future Put, Mtime, and Delete calls
473 // are expected to fail.
474 func (v *S3Volume) Writable() bool {
478 // Replication returns the storage redundancy of the underlying
479 // device. Configured via command line flag.
480 func (v *S3Volume) Replication() int {
484 var s3KeepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
486 func (v *S3Volume) isKeepBlock(s string) bool {
487 return s3KeepBlockRegexp.MatchString(s)
490 // fixRace(X) is called when "recent/X" exists but "X" doesn't
491 // exist. If the timestamps on "recent/"+loc and "trash/"+loc indicate
492 // there was a race between Put and Trash, fixRace recovers from the
493 // race by Untrashing the block.
494 func (v *S3Volume) fixRace(loc string) bool {
495 trash, err := v.Bucket.Head("trash/"+loc, nil)
497 if !os.IsNotExist(v.translateError(err)) {
498 log.Printf("error: fixRace: HEAD %q: %s", "trash/"+loc, err)
502 trashTime, err := v.lastModified(trash)
504 log.Printf("error: fixRace: parse %q: %s", trash.Header.Get("Last-Modified"), err)
508 recent, err := v.Bucket.Head("recent/"+loc, nil)
510 log.Printf("error: fixRace: HEAD %q: %s", "recent/"+loc, err)
513 recentTime, err := v.lastModified(recent)
515 log.Printf("error: fixRace: parse %q: %s", recent.Header.Get("Last-Modified"), err)
519 ageWhenTrashed := trashTime.Sub(recentTime)
520 if ageWhenTrashed >= blobSignatureTTL {
521 // No evidence of a race: block hasn't been written
522 // since it became eligible for Trash. No fix needed.
526 log.Printf("notice: fixRace: %q: trashed at %s but touched at %s (age when trashed = %s < %s)", loc, trashTime, recentTime, ageWhenTrashed, blobSignatureTTL)
527 log.Printf("notice: fixRace: copying %q to %q to recover from race between Put/Touch and Trash", "recent/"+loc, loc)
528 err = v.safeCopy(loc, "trash/"+loc)
530 log.Printf("error: fixRace: %s", err)
536 func (v *S3Volume) translateError(err error) error {
537 switch err := err.(type) {
539 if (err.StatusCode == http.StatusNotFound && err.Code == "NoSuchKey") ||
540 strings.Contains(err.Error(), "Not Found") {
541 return os.ErrNotExist
543 // Other 404 errors like NoSuchVersion and
544 // NoSuchBucket are different problems which should
545 // get called out downstream, so we don't convert them
546 // to os.ErrNotExist.
551 // EmptyTrash looks for trashed blocks that exceeded trashLifetime
552 // and deletes them from the volume.
553 func (v *S3Volume) EmptyTrash() {
554 var bytesInTrash, blocksInTrash, bytesDeleted, blocksDeleted int64
556 // Use a merge sort to find matching sets of trash/X and recent/X.
560 PageSize: v.indexPageSize,
562 // Define "ready to delete" as "...when EmptyTrash started".
564 for trash := trashL.First(); trash != nil; trash = trashL.Next() {
566 if !v.isKeepBlock(loc) {
569 bytesInTrash += trash.Size
572 trashT, err := time.Parse(time.RFC3339, trash.LastModified)
574 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, trash.Key, trash.LastModified, err)
577 recent, err := v.Bucket.Head("recent/"+loc, nil)
578 if err != nil && os.IsNotExist(v.translateError(err)) {
579 log.Printf("warning: %s: EmptyTrash: found trash marker %q but no %q (%s); calling Untrash", v, trash.Key, "recent/"+loc, err)
582 log.Printf("error: %s: EmptyTrash: Untrash(%q): %s", v, loc, err)
585 } else if err != nil {
586 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, "recent/"+loc, err)
589 recentT, err := v.lastModified(recent)
591 log.Printf("warning: %s: EmptyTrash: %q: parse %q: %s", v, "recent/"+loc, recent.Header.Get("Last-Modified"), err)
594 if trashT.Sub(recentT) < blobSignatureTTL {
595 if age := startT.Sub(recentT); age >= blobSignatureTTL-v.raceWindow {
596 // recent/loc is too old to protect
597 // loc from being Trashed again during
598 // the raceWindow that starts if we
599 // delete trash/X now.
601 // Note this means (trashCheckInterval
602 // < blobSignatureTTL - raceWindow) is
603 // necessary to avoid starvation.
604 log.Printf("notice: %s: EmptyTrash: detected old race for %q, calling fixRace + Touch", v, loc)
608 } else if _, err := v.Bucket.Head(loc, nil); os.IsNotExist(err) {
609 log.Printf("notice: %s: EmptyTrash: detected recent race for %q, calling fixRace", v, loc)
612 } else if err != nil {
613 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, loc, err)
617 if startT.Sub(trashT) < trashLifetime {
620 err = v.Bucket.Del(trash.Key)
622 log.Printf("warning: %s: EmptyTrash: deleting %q: %s", v, trash.Key, err)
625 bytesDeleted += trash.Size
628 _, err = v.Bucket.Head(loc, nil)
629 if os.IsNotExist(err) {
630 err = v.Bucket.Del("recent/" + loc)
632 log.Printf("warning: %s: EmptyTrash: deleting %q: %s", v, "recent/"+loc, err)
634 } else if err != nil {
635 log.Printf("warning: %s: EmptyTrash: HEAD %q: %s", v, "recent/"+loc, err)
638 if err := trashL.Error(); err != nil {
639 log.Printf("error: %s: EmptyTrash: lister: %s", v, err)
641 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)
644 type s3Lister struct {
653 // First fetches the first page and returns the first item. It returns
654 // nil if the response is the empty set or an error occurs.
655 func (lister *s3Lister) First() *s3.Key {
660 // Next returns the next item, fetching the next page if necessary. It
661 // returns nil if the last available item has already been fetched, or
663 func (lister *s3Lister) Next() *s3.Key {
664 if len(lister.buf) == 0 && lister.nextMarker != "" {
670 // Return the most recent error encountered by First or Next.
671 func (lister *s3Lister) Error() error {
675 func (lister *s3Lister) getPage() {
676 resp, err := lister.Bucket.List(lister.Prefix, "", lister.nextMarker, lister.PageSize)
677 lister.nextMarker = ""
682 if resp.IsTruncated {
683 lister.nextMarker = resp.NextMarker
685 lister.buf = make([]s3.Key, 0, len(resp.Contents))
686 for _, key := range resp.Contents {
687 if !strings.HasPrefix(key.Key, lister.Prefix) {
688 log.Printf("warning: s3Lister: S3 Bucket.List(prefix=%q) returned key %q", lister.Prefix, key.Key)
691 lister.buf = append(lister.buf, key)
695 func (lister *s3Lister) pop() (k *s3.Key) {
696 if len(lister.buf) > 0 {
698 lister.buf = lister.buf[1:]