Refactor the multi-host salt install page.
[arvados.git] / services / keepstore / s3_volume.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package keepstore
6
7 import (
8         "bufio"
9         "bytes"
10         "context"
11         "crypto/sha256"
12         "encoding/base64"
13         "encoding/hex"
14         "encoding/json"
15         "errors"
16         "fmt"
17         "io"
18         "io/ioutil"
19         "net/http"
20         "os"
21         "regexp"
22         "strings"
23         "sync"
24         "sync/atomic"
25         "time"
26
27         "git.arvados.org/arvados.git/sdk/go/arvados"
28         "github.com/AdRoll/goamz/aws"
29         "github.com/AdRoll/goamz/s3"
30         "github.com/prometheus/client_golang/prometheus"
31         "github.com/sirupsen/logrus"
32 )
33
34 func init() {
35         driver["S3"] = chooseS3VolumeDriver
36 }
37
38 func newS3Volume(cluster *arvados.Cluster, volume arvados.Volume, logger logrus.FieldLogger, metrics *volumeMetricsVecs) (Volume, error) {
39         v := &S3Volume{cluster: cluster, volume: volume, metrics: metrics}
40         err := json.Unmarshal(volume.DriverParameters, v)
41         if err != nil {
42                 return nil, err
43         }
44         v.logger = logger.WithField("Volume", v.String())
45         return v, v.check()
46 }
47
48 func (v *S3Volume) check() error {
49         if v.Bucket == "" {
50                 return errors.New("DriverParameters: Bucket must be provided")
51         }
52         if v.IndexPageSize == 0 {
53                 v.IndexPageSize = 1000
54         }
55         if v.RaceWindow < 0 {
56                 return errors.New("DriverParameters: RaceWindow must not be negative")
57         }
58
59         var ok bool
60         v.region, ok = aws.Regions[v.Region]
61         if v.Endpoint == "" {
62                 if !ok {
63                         return fmt.Errorf("unrecognized region %+q; try specifying endpoint instead", v.Region)
64                 }
65         } else if ok {
66                 return fmt.Errorf("refusing to use AWS region name %+q with endpoint %+q; "+
67                         "specify empty endpoint or use a different region name", v.Region, v.Endpoint)
68         } else {
69                 v.region = aws.Region{
70                         Name:                 v.Region,
71                         S3Endpoint:           v.Endpoint,
72                         S3LocationConstraint: v.LocationConstraint,
73                 }
74         }
75
76         // Zero timeouts mean "wait forever", which is a bad
77         // default. Default to long timeouts instead.
78         if v.ConnectTimeout == 0 {
79                 v.ConnectTimeout = s3DefaultConnectTimeout
80         }
81         if v.ReadTimeout == 0 {
82                 v.ReadTimeout = s3DefaultReadTimeout
83         }
84
85         v.bucket = &s3bucket{
86                 bucket: &s3.Bucket{
87                         S3:   v.newS3Client(),
88                         Name: v.Bucket,
89                 },
90         }
91         // Set up prometheus metrics
92         lbls := prometheus.Labels{"device_id": v.GetDeviceID()}
93         v.bucket.stats.opsCounters, v.bucket.stats.errCounters, v.bucket.stats.ioBytes = v.metrics.getCounterVecsFor(lbls)
94
95         err := v.bootstrapIAMCredentials()
96         if err != nil {
97                 return fmt.Errorf("error getting IAM credentials: %s", err)
98         }
99
100         return nil
101 }
102
103 const (
104         s3DefaultReadTimeout    = arvados.Duration(10 * time.Minute)
105         s3DefaultConnectTimeout = arvados.Duration(time.Minute)
106 )
107
108 var (
109         // ErrS3TrashDisabled is returned by Trash if that operation
110         // is impossible with the current config.
111         ErrS3TrashDisabled = fmt.Errorf("trash function is disabled because Collections.BlobTrashLifetime=0 and DriverParameters.UnsafeDelete=false")
112
113         s3ACL = s3.Private
114
115         zeroTime time.Time
116 )
117
118 const (
119         maxClockSkew  = 600 * time.Second
120         nearlyRFC1123 = "Mon, 2 Jan 2006 15:04:05 GMT"
121 )
122
123 func s3regions() (okList []string) {
124         for r := range aws.Regions {
125                 okList = append(okList, r)
126         }
127         return
128 }
129
130 // S3Volume implements Volume using an S3 bucket.
131 type S3Volume struct {
132         arvados.S3VolumeDriverParameters
133         AuthToken      string    // populated automatically when IAMRole is used
134         AuthExpiration time.Time // populated automatically when IAMRole is used
135
136         cluster   *arvados.Cluster
137         volume    arvados.Volume
138         logger    logrus.FieldLogger
139         metrics   *volumeMetricsVecs
140         bucket    *s3bucket
141         region    aws.Region
142         startOnce sync.Once
143 }
144
145 // GetDeviceID returns a globally unique ID for the storage bucket.
146 func (v *S3Volume) GetDeviceID() string {
147         return "s3://" + v.Endpoint + "/" + v.Bucket
148 }
149
150 func (v *S3Volume) bootstrapIAMCredentials() error {
151         if v.AccessKeyID != "" || v.SecretAccessKey != "" {
152                 if v.IAMRole != "" {
153                         return errors.New("invalid DriverParameters: AccessKeyID and SecretAccessKey must be blank if IAMRole is specified")
154                 }
155                 return nil
156         }
157         ttl, err := v.updateIAMCredentials()
158         if err != nil {
159                 return err
160         }
161         go func() {
162                 for {
163                         time.Sleep(ttl)
164                         ttl, err = v.updateIAMCredentials()
165                         if err != nil {
166                                 v.logger.WithError(err).Warnf("failed to update credentials for IAM role %q", v.IAMRole)
167                                 ttl = time.Second
168                         } else if ttl < time.Second {
169                                 v.logger.WithField("TTL", ttl).Warnf("received stale credentials for IAM role %q", v.IAMRole)
170                                 ttl = time.Second
171                         }
172                 }
173         }()
174         return nil
175 }
176
177 func (v *S3Volume) newS3Client() *s3.S3 {
178         auth := aws.NewAuth(v.AccessKeyID, v.SecretAccessKey, v.AuthToken, v.AuthExpiration)
179         client := s3.New(*auth, v.region)
180         if !v.V2Signature {
181                 client.Signature = aws.V4Signature
182         }
183         client.ConnectTimeout = time.Duration(v.ConnectTimeout)
184         client.ReadTimeout = time.Duration(v.ReadTimeout)
185         return client
186 }
187
188 // returned by AWS metadata endpoint .../security-credentials/${rolename}
189 type iamCredentials struct {
190         Code            string
191         LastUpdated     time.Time
192         Type            string
193         AccessKeyID     string
194         SecretAccessKey string
195         Token           string
196         Expiration      time.Time
197 }
198
199 // Returns TTL of updated credentials, i.e., time to sleep until next
200 // update.
201 func (v *S3Volume) updateIAMCredentials() (time.Duration, error) {
202         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
203         defer cancel()
204
205         metadataBaseURL := "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
206
207         var url string
208         if strings.Contains(v.IAMRole, "://") {
209                 // Configuration provides complete URL (used by tests)
210                 url = v.IAMRole
211         } else if v.IAMRole != "" {
212                 // Configuration provides IAM role name and we use the
213                 // AWS metadata endpoint
214                 url = metadataBaseURL + v.IAMRole
215         } else {
216                 url = metadataBaseURL
217                 v.logger.WithField("URL", url).Debug("looking up IAM role name")
218                 req, err := http.NewRequest("GET", url, nil)
219                 if err != nil {
220                         return 0, fmt.Errorf("error setting up request %s: %s", url, err)
221                 }
222                 resp, err := http.DefaultClient.Do(req.WithContext(ctx))
223                 if err != nil {
224                         return 0, fmt.Errorf("error getting %s: %s", url, err)
225                 }
226                 defer resp.Body.Close()
227                 if resp.StatusCode == http.StatusNotFound {
228                         return 0, fmt.Errorf("this instance does not have an IAM role assigned -- either assign a role, or configure AccessKeyID and SecretAccessKey explicitly in DriverParameters (error getting %s: HTTP status %s)", url, resp.Status)
229                 } else if resp.StatusCode != http.StatusOK {
230                         return 0, fmt.Errorf("error getting %s: HTTP status %s", url, resp.Status)
231                 }
232                 body := bufio.NewReader(resp.Body)
233                 var role string
234                 _, err = fmt.Fscanf(body, "%s\n", &role)
235                 if err != nil {
236                         return 0, fmt.Errorf("error reading response from %s: %s", url, err)
237                 }
238                 if n, _ := body.Read(make([]byte, 64)); n > 0 {
239                         v.logger.Warnf("ignoring additional data returned by metadata endpoint %s after the single role name that we expected", url)
240                 }
241                 v.logger.WithField("Role", role).Debug("looked up IAM role name")
242                 url = url + role
243         }
244
245         v.logger.WithField("URL", url).Debug("getting credentials")
246         req, err := http.NewRequest("GET", url, nil)
247         if err != nil {
248                 return 0, fmt.Errorf("error setting up request %s: %s", url, err)
249         }
250         resp, err := http.DefaultClient.Do(req.WithContext(ctx))
251         if err != nil {
252                 return 0, fmt.Errorf("error getting %s: %s", url, err)
253         }
254         defer resp.Body.Close()
255         if resp.StatusCode != http.StatusOK {
256                 return 0, fmt.Errorf("error getting %s: HTTP status %s", url, resp.Status)
257         }
258         var cred iamCredentials
259         err = json.NewDecoder(resp.Body).Decode(&cred)
260         if err != nil {
261                 return 0, fmt.Errorf("error decoding credentials from %s: %s", url, err)
262         }
263         v.AccessKeyID, v.SecretAccessKey, v.AuthToken, v.AuthExpiration = cred.AccessKeyID, cred.SecretAccessKey, cred.Token, cred.Expiration
264         v.bucket.SetBucket(&s3.Bucket{
265                 S3:   v.newS3Client(),
266                 Name: v.Bucket,
267         })
268         // TTL is time from now to expiration, minus 5m.  "We make new
269         // credentials available at least five minutes before the
270         // expiration of the old credentials."  --
271         // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials
272         // (If that's not true, the returned ttl might be zero or
273         // negative, which the caller can handle.)
274         ttl := cred.Expiration.Sub(time.Now()) - 5*time.Minute
275         v.logger.WithFields(logrus.Fields{
276                 "AccessKeyID": cred.AccessKeyID,
277                 "LastUpdated": cred.LastUpdated,
278                 "Expiration":  cred.Expiration,
279                 "TTL":         arvados.Duration(ttl),
280         }).Debug("updated credentials")
281         return ttl, nil
282 }
283
284 func (v *S3Volume) getReaderWithContext(ctx context.Context, key string) (rdr io.ReadCloser, err error) {
285         ready := make(chan bool)
286         go func() {
287                 rdr, err = v.getReader(key)
288                 close(ready)
289         }()
290         select {
291         case <-ready:
292                 return
293         case <-ctx.Done():
294                 v.logger.Debugf("s3: abandoning getReader(%s): %s", key, ctx.Err())
295                 go func() {
296                         <-ready
297                         if err == nil {
298                                 rdr.Close()
299                         }
300                 }()
301                 return nil, ctx.Err()
302         }
303 }
304
305 // getReader wraps (Bucket)GetReader.
306 //
307 // In situations where (Bucket)GetReader would fail because the block
308 // disappeared in a Trash race, getReader calls fixRace to recover the
309 // data, and tries again.
310 func (v *S3Volume) getReader(key string) (rdr io.ReadCloser, err error) {
311         rdr, err = v.bucket.GetReader(key)
312         err = v.translateError(err)
313         if err == nil || !os.IsNotExist(err) {
314                 return
315         }
316
317         _, err = v.bucket.Head("recent/"+key, nil)
318         err = v.translateError(err)
319         if err != nil {
320                 // If we can't read recent/X, there's no point in
321                 // trying fixRace. Give up.
322                 return
323         }
324         if !v.fixRace(key) {
325                 err = os.ErrNotExist
326                 return
327         }
328
329         rdr, err = v.bucket.GetReader(key)
330         if err != nil {
331                 v.logger.Warnf("reading %s after successful fixRace: %s", key, err)
332                 err = v.translateError(err)
333         }
334         return
335 }
336
337 // Get a block: copy the block data into buf, and return the number of
338 // bytes copied.
339 func (v *S3Volume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
340         key := v.key(loc)
341         rdr, err := v.getReaderWithContext(ctx, key)
342         if err != nil {
343                 return 0, err
344         }
345
346         var n int
347         ready := make(chan bool)
348         go func() {
349                 defer close(ready)
350
351                 defer rdr.Close()
352                 n, err = io.ReadFull(rdr, buf)
353
354                 switch err {
355                 case nil, io.EOF, io.ErrUnexpectedEOF:
356                         err = nil
357                 default:
358                         err = v.translateError(err)
359                 }
360         }()
361         select {
362         case <-ctx.Done():
363                 v.logger.Debugf("s3: interrupting ReadFull() with Close() because %s", ctx.Err())
364                 rdr.Close()
365                 // Must wait for ReadFull to return, to ensure it
366                 // doesn't write to buf after we return.
367                 v.logger.Debug("s3: waiting for ReadFull() to fail")
368                 <-ready
369                 return 0, ctx.Err()
370         case <-ready:
371                 return n, err
372         }
373 }
374
375 // Compare the given data with the stored data.
376 func (v *S3Volume) Compare(ctx context.Context, loc string, expect []byte) error {
377         key := v.key(loc)
378         errChan := make(chan error, 1)
379         go func() {
380                 _, err := v.bucket.Head("recent/"+key, nil)
381                 errChan <- err
382         }()
383         var err error
384         select {
385         case <-ctx.Done():
386                 return ctx.Err()
387         case err = <-errChan:
388         }
389         if err != nil {
390                 // Checking for "loc" itself here would interfere with
391                 // future GET requests.
392                 //
393                 // On AWS, if X doesn't exist, a HEAD or GET request
394                 // for X causes X's non-existence to be cached. Thus,
395                 // if we test for X, then create X and return a
396                 // signature to our client, the client might still get
397                 // 404 from all keepstores when trying to read it.
398                 //
399                 // To avoid this, we avoid doing HEAD X or GET X until
400                 // we know X has been written.
401                 //
402                 // Note that X might exist even though recent/X
403                 // doesn't: for example, the response to HEAD recent/X
404                 // might itself come from a stale cache. In such
405                 // cases, we will return a false negative and
406                 // PutHandler might needlessly create another replica
407                 // on a different volume. That's not ideal, but it's
408                 // better than passing the eventually-consistent
409                 // problem on to our clients.
410                 return v.translateError(err)
411         }
412         rdr, err := v.getReaderWithContext(ctx, key)
413         if err != nil {
414                 return err
415         }
416         defer rdr.Close()
417         return v.translateError(compareReaderWithBuf(ctx, rdr, expect, loc[:32]))
418 }
419
420 // Put writes a block.
421 func (v *S3Volume) Put(ctx context.Context, loc string, block []byte) error {
422         if v.volume.ReadOnly {
423                 return MethodDisabledError
424         }
425         var opts s3.Options
426         size := len(block)
427         if size > 0 {
428                 md5, err := hex.DecodeString(loc)
429                 if err != nil {
430                         return err
431                 }
432                 opts.ContentMD5 = base64.StdEncoding.EncodeToString(md5)
433                 // In AWS regions that use V4 signatures, we need to
434                 // provide ContentSHA256 up front. Otherwise, the S3
435                 // library reads the request body (from our buffer)
436                 // into another new buffer in order to compute the
437                 // SHA256 before sending the request -- which would
438                 // mean consuming 128 MiB of memory for the duration
439                 // of a 64 MiB write.
440                 opts.ContentSHA256 = fmt.Sprintf("%x", sha256.Sum256(block))
441         }
442
443         key := v.key(loc)
444
445         // Send the block data through a pipe, so that (if we need to)
446         // we can close the pipe early and abandon our PutReader()
447         // goroutine, without worrying about PutReader() accessing our
448         // block buffer after we release it.
449         bufr, bufw := io.Pipe()
450         go func() {
451                 io.Copy(bufw, bytes.NewReader(block))
452                 bufw.Close()
453         }()
454
455         var err error
456         ready := make(chan bool)
457         go func() {
458                 defer func() {
459                         if ctx.Err() != nil {
460                                 v.logger.Debugf("abandoned PutReader goroutine finished with err: %s", err)
461                         }
462                 }()
463                 defer close(ready)
464                 err = v.bucket.PutReader(key, bufr, int64(size), "application/octet-stream", s3ACL, opts)
465                 if err != nil {
466                         return
467                 }
468                 err = v.bucket.PutReader("recent/"+key, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
469         }()
470         select {
471         case <-ctx.Done():
472                 v.logger.Debugf("taking PutReader's input away: %s", ctx.Err())
473                 // Our pipe might be stuck in Write(), waiting for
474                 // PutReader() to read. If so, un-stick it. This means
475                 // PutReader will get corrupt data, but that's OK: the
476                 // size and MD5 won't match, so the write will fail.
477                 go io.Copy(ioutil.Discard, bufr)
478                 // CloseWithError() will return once pending I/O is done.
479                 bufw.CloseWithError(ctx.Err())
480                 v.logger.Debugf("abandoning PutReader goroutine")
481                 return ctx.Err()
482         case <-ready:
483                 // Unblock pipe in case PutReader did not consume it.
484                 io.Copy(ioutil.Discard, bufr)
485                 return v.translateError(err)
486         }
487 }
488
489 // Touch sets the timestamp for the given locator to the current time.
490 func (v *S3Volume) Touch(loc string) error {
491         if v.volume.ReadOnly {
492                 return MethodDisabledError
493         }
494         key := v.key(loc)
495         _, err := v.bucket.Head(key, nil)
496         err = v.translateError(err)
497         if os.IsNotExist(err) && v.fixRace(key) {
498                 // The data object got trashed in a race, but fixRace
499                 // rescued it.
500         } else if err != nil {
501                 return err
502         }
503         err = v.bucket.PutReader("recent/"+key, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
504         return v.translateError(err)
505 }
506
507 // Mtime returns the stored timestamp for the given locator.
508 func (v *S3Volume) Mtime(loc string) (time.Time, error) {
509         key := v.key(loc)
510         _, err := v.bucket.Head(key, nil)
511         if err != nil {
512                 return zeroTime, v.translateError(err)
513         }
514         resp, err := v.bucket.Head("recent/"+key, nil)
515         err = v.translateError(err)
516         if os.IsNotExist(err) {
517                 // The data object X exists, but recent/X is missing.
518                 err = v.bucket.PutReader("recent/"+key, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
519                 if err != nil {
520                         v.logger.WithError(err).Errorf("error creating %q", "recent/"+key)
521                         return zeroTime, v.translateError(err)
522                 }
523                 v.logger.Infof("created %q to migrate existing block to new storage scheme", "recent/"+key)
524                 resp, err = v.bucket.Head("recent/"+key, nil)
525                 if err != nil {
526                         v.logger.WithError(err).Errorf("HEAD failed after creating %q", "recent/"+key)
527                         return zeroTime, v.translateError(err)
528                 }
529         } else if err != nil {
530                 // HEAD recent/X failed for some other reason.
531                 return zeroTime, err
532         }
533         return v.lastModified(resp)
534 }
535
536 // IndexTo writes a complete list of locators with the given prefix
537 // for which Get() can retrieve data.
538 func (v *S3Volume) IndexTo(prefix string, writer io.Writer) error {
539         // Use a merge sort to find matching sets of X and recent/X.
540         dataL := s3Lister{
541                 Logger:   v.logger,
542                 Bucket:   v.bucket.Bucket(),
543                 Prefix:   v.key(prefix),
544                 PageSize: v.IndexPageSize,
545                 Stats:    &v.bucket.stats,
546         }
547         recentL := s3Lister{
548                 Logger:   v.logger,
549                 Bucket:   v.bucket.Bucket(),
550                 Prefix:   "recent/" + v.key(prefix),
551                 PageSize: v.IndexPageSize,
552                 Stats:    &v.bucket.stats,
553         }
554         for data, recent := dataL.First(), recentL.First(); data != nil && dataL.Error() == nil; data = dataL.Next() {
555                 if data.Key >= "g" {
556                         // Conveniently, "recent/*" and "trash/*" are
557                         // lexically greater than all hex-encoded data
558                         // hashes, so stopping here avoids iterating
559                         // over all of them needlessly with dataL.
560                         break
561                 }
562                 loc, isBlk := v.isKeepBlock(data.Key)
563                 if !isBlk {
564                         continue
565                 }
566
567                 // stamp is the list entry we should use to report the
568                 // last-modified time for this data block: it will be
569                 // the recent/X entry if one exists, otherwise the
570                 // entry for the data block itself.
571                 stamp := data
572
573                 // Advance to the corresponding recent/X marker, if any
574                 for recent != nil && recentL.Error() == nil {
575                         if cmp := strings.Compare(recent.Key[7:], data.Key); cmp < 0 {
576                                 recent = recentL.Next()
577                                 continue
578                         } else if cmp == 0 {
579                                 stamp = recent
580                                 recent = recentL.Next()
581                                 break
582                         } else {
583                                 // recent/X marker is missing: we'll
584                                 // use the timestamp on the data
585                                 // object.
586                                 break
587                         }
588                 }
589                 if err := recentL.Error(); err != nil {
590                         return err
591                 }
592                 t, err := time.Parse(time.RFC3339, stamp.LastModified)
593                 if err != nil {
594                         return err
595                 }
596                 // We truncate sub-second precision here. Otherwise
597                 // timestamps will never match the RFC1123-formatted
598                 // Last-Modified values parsed by Mtime().
599                 fmt.Fprintf(writer, "%s+%d %d\n", loc, data.Size, t.Unix()*1000000000)
600         }
601         return dataL.Error()
602 }
603
604 // Trash a Keep block.
605 func (v *S3Volume) Trash(loc string) error {
606         if v.volume.ReadOnly {
607                 return MethodDisabledError
608         }
609         if t, err := v.Mtime(loc); err != nil {
610                 return err
611         } else if time.Since(t) < v.cluster.Collections.BlobSigningTTL.Duration() {
612                 return nil
613         }
614         key := v.key(loc)
615         if v.cluster.Collections.BlobTrashLifetime == 0 {
616                 if !v.UnsafeDelete {
617                         return ErrS3TrashDisabled
618                 }
619                 return v.translateError(v.bucket.Del(key))
620         }
621         err := v.checkRaceWindow(key)
622         if err != nil {
623                 return err
624         }
625         err = v.safeCopy("trash/"+key, key)
626         if err != nil {
627                 return err
628         }
629         return v.translateError(v.bucket.Del(key))
630 }
631
632 // checkRaceWindow returns a non-nil error if trash/key is, or might
633 // be, in the race window (i.e., it's not safe to trash key).
634 func (v *S3Volume) checkRaceWindow(key string) error {
635         resp, err := v.bucket.Head("trash/"+key, nil)
636         err = v.translateError(err)
637         if os.IsNotExist(err) {
638                 // OK, trash/X doesn't exist so we're not in the race
639                 // window
640                 return nil
641         } else if err != nil {
642                 // Error looking up trash/X. We don't know whether
643                 // we're in the race window
644                 return err
645         }
646         t, err := v.lastModified(resp)
647         if err != nil {
648                 // Can't parse timestamp
649                 return err
650         }
651         safeWindow := t.Add(v.cluster.Collections.BlobTrashLifetime.Duration()).Sub(time.Now().Add(time.Duration(v.RaceWindow)))
652         if safeWindow <= 0 {
653                 // We can't count on "touch trash/X" to prolong
654                 // trash/X's lifetime. The new timestamp might not
655                 // become visible until now+raceWindow, and EmptyTrash
656                 // is allowed to delete trash/X before then.
657                 return fmt.Errorf("%s: same block is already in trash, and safe window ended %s ago", key, -safeWindow)
658         }
659         // trash/X exists, but it won't be eligible for deletion until
660         // after now+raceWindow, so it's safe to overwrite it.
661         return nil
662 }
663
664 // safeCopy calls PutCopy, and checks the response to make sure the
665 // copy succeeded and updated the timestamp on the destination object
666 // (PutCopy returns 200 OK if the request was received, even if the
667 // copy failed).
668 func (v *S3Volume) safeCopy(dst, src string) error {
669         resp, err := v.bucket.Bucket().PutCopy(dst, s3ACL, s3.CopyOptions{
670                 ContentType:       "application/octet-stream",
671                 MetadataDirective: "REPLACE",
672         }, v.bucket.Bucket().Name+"/"+src)
673         err = v.translateError(err)
674         if os.IsNotExist(err) {
675                 return err
676         } else if err != nil {
677                 return fmt.Errorf("PutCopy(%q ← %q): %s", dst, v.bucket.Bucket().Name+"/"+src, err)
678         }
679         if t, err := time.Parse(time.RFC3339Nano, resp.LastModified); err != nil {
680                 return fmt.Errorf("PutCopy succeeded but did not return a timestamp: %q: %s", resp.LastModified, err)
681         } else if time.Now().Sub(t) > maxClockSkew {
682                 return fmt.Errorf("PutCopy succeeded but returned an old timestamp: %q: %s", resp.LastModified, t)
683         }
684         return nil
685 }
686
687 // Get the LastModified header from resp, and parse it as RFC1123 or
688 // -- if it isn't valid RFC1123 -- as Amazon's variant of RFC1123.
689 func (v *S3Volume) lastModified(resp *http.Response) (t time.Time, err error) {
690         s := resp.Header.Get("Last-Modified")
691         t, err = time.Parse(time.RFC1123, s)
692         if err != nil && s != "" {
693                 // AWS example is "Sun, 1 Jan 2006 12:00:00 GMT",
694                 // which isn't quite "Sun, 01 Jan 2006 12:00:00 GMT"
695                 // as required by HTTP spec. If it's not a valid HTTP
696                 // header value, it's probably AWS (or s3test) giving
697                 // us a nearly-RFC1123 timestamp.
698                 t, err = time.Parse(nearlyRFC1123, s)
699         }
700         return
701 }
702
703 // Untrash moves block from trash back into store
704 func (v *S3Volume) Untrash(loc string) error {
705         key := v.key(loc)
706         err := v.safeCopy(key, "trash/"+key)
707         if err != nil {
708                 return err
709         }
710         err = v.bucket.PutReader("recent/"+key, nil, 0, "application/octet-stream", s3ACL, s3.Options{})
711         return v.translateError(err)
712 }
713
714 // Status returns a *VolumeStatus representing the current in-use
715 // storage capacity and a fake available capacity that doesn't make
716 // the volume seem full or nearly-full.
717 func (v *S3Volume) Status() *VolumeStatus {
718         return &VolumeStatus{
719                 DeviceNum: 1,
720                 BytesFree: BlockSize * 1000,
721                 BytesUsed: 1,
722         }
723 }
724
725 // InternalStats returns bucket I/O and API call counters.
726 func (v *S3Volume) InternalStats() interface{} {
727         return &v.bucket.stats
728 }
729
730 // String implements fmt.Stringer.
731 func (v *S3Volume) String() string {
732         return fmt.Sprintf("s3-bucket:%+q", v.Bucket)
733 }
734
735 var s3KeepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
736
737 func (v *S3Volume) isKeepBlock(s string) (string, bool) {
738         if v.PrefixLength > 0 && len(s) == v.PrefixLength+33 && s[:v.PrefixLength] == s[v.PrefixLength+1:v.PrefixLength*2+1] {
739                 s = s[v.PrefixLength+1:]
740         }
741         return s, s3KeepBlockRegexp.MatchString(s)
742 }
743
744 // Return the key used for a given loc. If PrefixLength==0 then
745 // key("abcdef0123") is "abcdef0123", if PrefixLength==3 then key is
746 // "abc/abcdef0123", etc.
747 func (v *S3Volume) key(loc string) string {
748         if v.PrefixLength > 0 && v.PrefixLength < len(loc)-1 {
749                 return loc[:v.PrefixLength] + "/" + loc
750         } else {
751                 return loc
752         }
753 }
754
755 // fixRace(X) is called when "recent/X" exists but "X" doesn't
756 // exist. If the timestamps on "recent/X" and "trash/X" indicate there
757 // was a race between Put and Trash, fixRace recovers from the race by
758 // Untrashing the block.
759 func (v *S3Volume) fixRace(key string) bool {
760         trash, err := v.bucket.Head("trash/"+key, nil)
761         if err != nil {
762                 if !os.IsNotExist(v.translateError(err)) {
763                         v.logger.WithError(err).Errorf("fixRace: HEAD %q failed", "trash/"+key)
764                 }
765                 return false
766         }
767         trashTime, err := v.lastModified(trash)
768         if err != nil {
769                 v.logger.WithError(err).Errorf("fixRace: error parsing time %q", trash.Header.Get("Last-Modified"))
770                 return false
771         }
772
773         recent, err := v.bucket.Head("recent/"+key, nil)
774         if err != nil {
775                 v.logger.WithError(err).Errorf("fixRace: HEAD %q failed", "recent/"+key)
776                 return false
777         }
778         recentTime, err := v.lastModified(recent)
779         if err != nil {
780                 v.logger.WithError(err).Errorf("fixRace: error parsing time %q", recent.Header.Get("Last-Modified"))
781                 return false
782         }
783
784         ageWhenTrashed := trashTime.Sub(recentTime)
785         if ageWhenTrashed >= v.cluster.Collections.BlobSigningTTL.Duration() {
786                 // No evidence of a race: block hasn't been written
787                 // since it became eligible for Trash. No fix needed.
788                 return false
789         }
790
791         v.logger.Infof("fixRace: %q: trashed at %s but touched at %s (age when trashed = %s < %s)", key, trashTime, recentTime, ageWhenTrashed, v.cluster.Collections.BlobSigningTTL)
792         v.logger.Infof("fixRace: copying %q to %q to recover from race between Put/Touch and Trash", "recent/"+key, key)
793         err = v.safeCopy(key, "trash/"+key)
794         if err != nil {
795                 v.logger.WithError(err).Error("fixRace: copy failed")
796                 return false
797         }
798         return true
799 }
800
801 func (v *S3Volume) translateError(err error) error {
802         switch err := err.(type) {
803         case *s3.Error:
804                 if (err.StatusCode == http.StatusNotFound && err.Code == "NoSuchKey") ||
805                         strings.Contains(err.Error(), "Not Found") {
806                         return os.ErrNotExist
807                 }
808                 // Other 404 errors like NoSuchVersion and
809                 // NoSuchBucket are different problems which should
810                 // get called out downstream, so we don't convert them
811                 // to os.ErrNotExist.
812         }
813         return err
814 }
815
816 // EmptyTrash looks for trashed blocks that exceeded BlobTrashLifetime
817 // and deletes them from the volume.
818 func (v *S3Volume) EmptyTrash() {
819         if v.cluster.Collections.BlobDeleteConcurrency < 1 {
820                 return
821         }
822
823         var bytesInTrash, blocksInTrash, bytesDeleted, blocksDeleted int64
824
825         // Define "ready to delete" as "...when EmptyTrash started".
826         startT := time.Now()
827
828         emptyOneKey := func(trash *s3.Key) {
829                 key := trash.Key[6:]
830                 loc, isBlk := v.isKeepBlock(key)
831                 if !isBlk {
832                         return
833                 }
834                 atomic.AddInt64(&bytesInTrash, trash.Size)
835                 atomic.AddInt64(&blocksInTrash, 1)
836
837                 trashT, err := time.Parse(time.RFC3339, trash.LastModified)
838                 if err != nil {
839                         v.logger.Warnf("EmptyTrash: %q: parse %q: %s", trash.Key, trash.LastModified, err)
840                         return
841                 }
842                 recent, err := v.bucket.Head("recent/"+key, nil)
843                 if err != nil && os.IsNotExist(v.translateError(err)) {
844                         v.logger.Warnf("EmptyTrash: found trash marker %q but no %q (%s); calling Untrash", trash.Key, "recent/"+loc, err)
845                         err = v.Untrash(loc)
846                         if err != nil {
847                                 v.logger.WithError(err).Errorf("EmptyTrash: Untrash(%q) failed", loc)
848                         }
849                         return
850                 } else if err != nil {
851                         v.logger.WithError(err).Warnf("EmptyTrash: HEAD %q failed", "recent/"+key)
852                         return
853                 }
854                 recentT, err := v.lastModified(recent)
855                 if err != nil {
856                         v.logger.WithError(err).Warnf("EmptyTrash: %q: error parsing %q", "recent/"+key, recent.Header.Get("Last-Modified"))
857                         return
858                 }
859                 if trashT.Sub(recentT) < v.cluster.Collections.BlobSigningTTL.Duration() {
860                         if age := startT.Sub(recentT); age >= v.cluster.Collections.BlobSigningTTL.Duration()-time.Duration(v.RaceWindow) {
861                                 // recent/loc is too old to protect
862                                 // loc from being Trashed again during
863                                 // the raceWindow that starts if we
864                                 // delete trash/X now.
865                                 //
866                                 // Note this means (TrashSweepInterval
867                                 // < BlobSigningTTL - raceWindow) is
868                                 // necessary to avoid starvation.
869                                 v.logger.Infof("EmptyTrash: detected old race for %q, calling fixRace + Touch", loc)
870                                 v.fixRace(key)
871                                 v.Touch(loc)
872                                 return
873                         }
874                         _, err := v.bucket.Head(key, nil)
875                         if os.IsNotExist(err) {
876                                 v.logger.Infof("EmptyTrash: detected recent race for %q, calling fixRace", loc)
877                                 v.fixRace(key)
878                                 return
879                         } else if err != nil {
880                                 v.logger.WithError(err).Warnf("EmptyTrash: HEAD %q failed", loc)
881                                 return
882                         }
883                 }
884                 if startT.Sub(trashT) < v.cluster.Collections.BlobTrashLifetime.Duration() {
885                         return
886                 }
887                 err = v.bucket.Del(trash.Key)
888                 if err != nil {
889                         v.logger.WithError(err).Errorf("EmptyTrash: error deleting %q", trash.Key)
890                         return
891                 }
892                 atomic.AddInt64(&bytesDeleted, trash.Size)
893                 atomic.AddInt64(&blocksDeleted, 1)
894
895                 _, err = v.bucket.Head(key, nil)
896                 if err == nil {
897                         v.logger.Warnf("EmptyTrash: HEAD %q succeeded immediately after deleting %q", key, key)
898                         return
899                 }
900                 if !os.IsNotExist(v.translateError(err)) {
901                         v.logger.WithError(err).Warnf("EmptyTrash: HEAD %q failed", key)
902                         return
903                 }
904                 err = v.bucket.Del("recent/" + key)
905                 if err != nil {
906                         v.logger.WithError(err).Warnf("EmptyTrash: error deleting %q", "recent/"+key)
907                 }
908         }
909
910         var wg sync.WaitGroup
911         todo := make(chan *s3.Key, v.cluster.Collections.BlobDeleteConcurrency)
912         for i := 0; i < v.cluster.Collections.BlobDeleteConcurrency; i++ {
913                 wg.Add(1)
914                 go func() {
915                         defer wg.Done()
916                         for key := range todo {
917                                 emptyOneKey(key)
918                         }
919                 }()
920         }
921
922         trashL := s3Lister{
923                 Logger:   v.logger,
924                 Bucket:   v.bucket.Bucket(),
925                 Prefix:   "trash/",
926                 PageSize: v.IndexPageSize,
927                 Stats:    &v.bucket.stats,
928         }
929         for trash := trashL.First(); trash != nil; trash = trashL.Next() {
930                 todo <- trash
931         }
932         close(todo)
933         wg.Wait()
934
935         if err := trashL.Error(); err != nil {
936                 v.logger.WithError(err).Error("EmptyTrash: lister failed")
937         }
938         v.logger.Infof("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)
939 }
940
941 type s3Lister struct {
942         Logger     logrus.FieldLogger
943         Bucket     *s3.Bucket
944         Prefix     string
945         PageSize   int
946         Stats      *s3bucketStats
947         nextMarker string
948         buf        []s3.Key
949         err        error
950 }
951
952 // First fetches the first page and returns the first item. It returns
953 // nil if the response is the empty set or an error occurs.
954 func (lister *s3Lister) First() *s3.Key {
955         lister.getPage()
956         return lister.pop()
957 }
958
959 // Next returns the next item, fetching the next page if necessary. It
960 // returns nil if the last available item has already been fetched, or
961 // an error occurs.
962 func (lister *s3Lister) Next() *s3.Key {
963         if len(lister.buf) == 0 && lister.nextMarker != "" {
964                 lister.getPage()
965         }
966         return lister.pop()
967 }
968
969 // Return the most recent error encountered by First or Next.
970 func (lister *s3Lister) Error() error {
971         return lister.err
972 }
973
974 func (lister *s3Lister) getPage() {
975         lister.Stats.TickOps("list")
976         lister.Stats.Tick(&lister.Stats.Ops, &lister.Stats.ListOps)
977         resp, err := lister.Bucket.List(lister.Prefix, "", lister.nextMarker, lister.PageSize)
978         lister.nextMarker = ""
979         if err != nil {
980                 lister.err = err
981                 return
982         }
983         if resp.IsTruncated {
984                 lister.nextMarker = resp.NextMarker
985         }
986         lister.buf = make([]s3.Key, 0, len(resp.Contents))
987         for _, key := range resp.Contents {
988                 if !strings.HasPrefix(key.Key, lister.Prefix) {
989                         lister.Logger.Warnf("s3Lister: S3 Bucket.List(prefix=%q) returned key %q", lister.Prefix, key.Key)
990                         continue
991                 }
992                 lister.buf = append(lister.buf, key)
993         }
994 }
995
996 func (lister *s3Lister) pop() (k *s3.Key) {
997         if len(lister.buf) > 0 {
998                 k = &lister.buf[0]
999                 lister.buf = lister.buf[1:]
1000         }
1001         return
1002 }
1003
1004 // s3bucket wraps s3.bucket and counts I/O and API usage stats. The
1005 // wrapped bucket can be replaced atomically with SetBucket in order
1006 // to update credentials.
1007 type s3bucket struct {
1008         bucket *s3.Bucket
1009         stats  s3bucketStats
1010         mu     sync.Mutex
1011 }
1012
1013 func (b *s3bucket) Bucket() *s3.Bucket {
1014         b.mu.Lock()
1015         defer b.mu.Unlock()
1016         return b.bucket
1017 }
1018
1019 func (b *s3bucket) SetBucket(bucket *s3.Bucket) {
1020         b.mu.Lock()
1021         defer b.mu.Unlock()
1022         b.bucket = bucket
1023 }
1024
1025 func (b *s3bucket) GetReader(path string) (io.ReadCloser, error) {
1026         rdr, err := b.Bucket().GetReader(path)
1027         b.stats.TickOps("get")
1028         b.stats.Tick(&b.stats.Ops, &b.stats.GetOps)
1029         b.stats.TickErr(err)
1030         return NewCountingReader(rdr, b.stats.TickInBytes), err
1031 }
1032
1033 func (b *s3bucket) Head(path string, headers map[string][]string) (*http.Response, error) {
1034         resp, err := b.Bucket().Head(path, headers)
1035         b.stats.TickOps("head")
1036         b.stats.Tick(&b.stats.Ops, &b.stats.HeadOps)
1037         b.stats.TickErr(err)
1038         return resp, err
1039 }
1040
1041 func (b *s3bucket) PutReader(path string, r io.Reader, length int64, contType string, perm s3.ACL, options s3.Options) error {
1042         if length == 0 {
1043                 // goamz will only send Content-Length: 0 when reader
1044                 // is nil due to net.http.Request.ContentLength
1045                 // behavior.  Otherwise, Content-Length header is
1046                 // omitted which will cause some S3 services
1047                 // (including AWS and Ceph RadosGW) to fail to create
1048                 // empty objects.
1049                 r = nil
1050         } else {
1051                 r = NewCountingReader(r, b.stats.TickOutBytes)
1052         }
1053         err := b.Bucket().PutReader(path, r, length, contType, perm, options)
1054         b.stats.TickOps("put")
1055         b.stats.Tick(&b.stats.Ops, &b.stats.PutOps)
1056         b.stats.TickErr(err)
1057         return err
1058 }
1059
1060 func (b *s3bucket) Del(path string) error {
1061         err := b.Bucket().Del(path)
1062         b.stats.TickOps("delete")
1063         b.stats.Tick(&b.stats.Ops, &b.stats.DelOps)
1064         b.stats.TickErr(err)
1065         return err
1066 }
1067
1068 type s3bucketStats struct {
1069         statsTicker
1070         Ops     uint64
1071         GetOps  uint64
1072         PutOps  uint64
1073         HeadOps uint64
1074         DelOps  uint64
1075         ListOps uint64
1076 }
1077
1078 func (s *s3bucketStats) TickErr(err error) {
1079         if err == nil {
1080                 return
1081         }
1082         errType := fmt.Sprintf("%T", err)
1083         if err, ok := err.(*s3.Error); ok {
1084                 errType = errType + fmt.Sprintf(" %d %s", err.StatusCode, err.Code)
1085         }
1086         s.statsTicker.TickErr(err, errType)
1087 }