10671: Merge branch 'master' into 10671-pipeline-instance-finish-time
[arvados.git] / services / keepstore / azure_blob_volume.go
1 package main
2
3 import (
4         "bytes"
5         "context"
6         "errors"
7         "flag"
8         "fmt"
9         "io"
10         "io/ioutil"
11         "net/http"
12         "os"
13         "regexp"
14         "strconv"
15         "strings"
16         "sync"
17         "time"
18
19         "git.curoverse.com/arvados.git/sdk/go/arvados"
20         log "github.com/Sirupsen/logrus"
21         "github.com/curoverse/azure-sdk-for-go/storage"
22 )
23
24 const azureDefaultRequestTimeout = arvados.Duration(10 * time.Minute)
25
26 var (
27         azureMaxGetBytes           int
28         azureStorageAccountName    string
29         azureStorageAccountKeyFile string
30         azureStorageReplication    int
31         azureWriteRaceInterval     = 15 * time.Second
32         azureWriteRacePollTime     = time.Second
33 )
34
35 func readKeyFromFile(file string) (string, error) {
36         buf, err := ioutil.ReadFile(file)
37         if err != nil {
38                 return "", errors.New("reading key from " + file + ": " + err.Error())
39         }
40         accountKey := strings.TrimSpace(string(buf))
41         if accountKey == "" {
42                 return "", errors.New("empty account key in " + file)
43         }
44         return accountKey, nil
45 }
46
47 type azureVolumeAdder struct {
48         *Config
49 }
50
51 // String implements flag.Value
52 func (s *azureVolumeAdder) String() string {
53         return "-"
54 }
55
56 func (s *azureVolumeAdder) Set(containerName string) error {
57         s.Config.Volumes = append(s.Config.Volumes, &AzureBlobVolume{
58                 ContainerName:         containerName,
59                 StorageAccountName:    azureStorageAccountName,
60                 StorageAccountKeyFile: azureStorageAccountKeyFile,
61                 AzureReplication:      azureStorageReplication,
62                 ReadOnly:              deprecated.flagReadonly,
63         })
64         return nil
65 }
66
67 func init() {
68         VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &AzureBlobVolume{} })
69
70         flag.Var(&azureVolumeAdder{theConfig},
71                 "azure-storage-container-volume",
72                 "Use the given container as a storage volume. Can be given multiple times.")
73         flag.StringVar(
74                 &azureStorageAccountName,
75                 "azure-storage-account-name",
76                 "",
77                 "Azure storage account name used for subsequent --azure-storage-container-volume arguments.")
78         flag.StringVar(
79                 &azureStorageAccountKeyFile,
80                 "azure-storage-account-key-file",
81                 "",
82                 "`File` containing the account key used for subsequent --azure-storage-container-volume arguments.")
83         flag.IntVar(
84                 &azureStorageReplication,
85                 "azure-storage-replication",
86                 3,
87                 "Replication level to report to clients when data is stored in an Azure container.")
88         flag.IntVar(
89                 &azureMaxGetBytes,
90                 "azure-max-get-bytes",
91                 BlockSize,
92                 fmt.Sprintf("Maximum bytes to request in a single GET request. If smaller than %d, use multiple concurrent range requests to retrieve a block.", BlockSize))
93 }
94
95 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
96 // container.
97 type AzureBlobVolume struct {
98         StorageAccountName    string
99         StorageAccountKeyFile string
100         ContainerName         string
101         AzureReplication      int
102         ReadOnly              bool
103         RequestTimeout        arvados.Duration
104
105         azClient storage.Client
106         bsClient storage.BlobStorageClient
107 }
108
109 // Examples implements VolumeWithExamples.
110 func (*AzureBlobVolume) Examples() []Volume {
111         return []Volume{
112                 &AzureBlobVolume{
113                         StorageAccountName:    "example-account-name",
114                         StorageAccountKeyFile: "/etc/azure_storage_account_key.txt",
115                         ContainerName:         "example-container-name",
116                         AzureReplication:      3,
117                         RequestTimeout:        azureDefaultRequestTimeout,
118                 },
119         }
120 }
121
122 // Type implements Volume.
123 func (v *AzureBlobVolume) Type() string {
124         return "Azure"
125 }
126
127 // Start implements Volume.
128 func (v *AzureBlobVolume) Start() error {
129         if v.ContainerName == "" {
130                 return errors.New("no container name given")
131         }
132         if v.StorageAccountName == "" || v.StorageAccountKeyFile == "" {
133                 return errors.New("StorageAccountName and StorageAccountKeyFile must be given")
134         }
135         accountKey, err := readKeyFromFile(v.StorageAccountKeyFile)
136         if err != nil {
137                 return err
138         }
139         v.azClient, err = storage.NewBasicClient(v.StorageAccountName, accountKey)
140         if err != nil {
141                 return fmt.Errorf("creating Azure storage client: %s", err)
142         }
143
144         if v.RequestTimeout == 0 {
145                 v.RequestTimeout = azureDefaultRequestTimeout
146         }
147         v.azClient.HTTPClient = &http.Client{
148                 Timeout: time.Duration(v.RequestTimeout),
149         }
150         v.bsClient = v.azClient.GetBlobService()
151
152         ok, err := v.bsClient.ContainerExists(v.ContainerName)
153         if err != nil {
154                 return err
155         }
156         if !ok {
157                 return fmt.Errorf("Azure container %q does not exist", v.ContainerName)
158         }
159         return nil
160 }
161
162 // Return true if expires_at metadata attribute is found on the block
163 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
164         metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
165         if err != nil {
166                 return false, metadata, v.translateError(err)
167         }
168         if metadata["expires_at"] != "" {
169                 return true, metadata, nil
170         }
171         return false, metadata, nil
172 }
173
174 // Get reads a Keep block that has been stored as a block blob in the
175 // container.
176 //
177 // If the block is younger than azureWriteRaceInterval and is
178 // unexpectedly empty, assume a PutBlob operation is in progress, and
179 // wait for it to finish writing.
180 func (v *AzureBlobVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
181         trashed, _, err := v.checkTrashed(loc)
182         if err != nil {
183                 return 0, err
184         }
185         if trashed {
186                 return 0, os.ErrNotExist
187         }
188         var deadline time.Time
189         haveDeadline := false
190         size, err := v.get(ctx, loc, buf)
191         for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
192                 // Seeing a brand new empty block probably means we're
193                 // in a race with CreateBlob, which under the hood
194                 // (apparently) does "CreateEmpty" and "CommitData"
195                 // with no additional transaction locking.
196                 if !haveDeadline {
197                         t, err := v.Mtime(loc)
198                         if err != nil {
199                                 log.Print("Got empty block (possible race) but Mtime failed: ", err)
200                                 break
201                         }
202                         deadline = t.Add(azureWriteRaceInterval)
203                         if time.Now().After(deadline) {
204                                 break
205                         }
206                         log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
207                         haveDeadline = true
208                 } else if time.Now().After(deadline) {
209                         break
210                 }
211                 select {
212                 case <-ctx.Done():
213                         return 0, ctx.Err()
214                 case <-time.After(azureWriteRacePollTime):
215                 }
216                 size, err = v.get(ctx, loc, buf)
217         }
218         if haveDeadline {
219                 log.Printf("Race ended with size==%d", size)
220         }
221         return size, err
222 }
223
224 func (v *AzureBlobVolume) get(ctx context.Context, loc string, buf []byte) (int, error) {
225         ctx, cancel := context.WithCancel(ctx)
226         defer cancel()
227         expectSize := len(buf)
228         if azureMaxGetBytes < BlockSize {
229                 // Unfortunately the handler doesn't tell us how long the blob
230                 // is expected to be, so we have to ask Azure.
231                 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
232                 if err != nil {
233                         return 0, v.translateError(err)
234                 }
235                 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
236                         return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
237                 }
238                 expectSize = int(props.ContentLength)
239         }
240
241         if expectSize == 0 {
242                 return 0, nil
243         }
244
245         // We'll update this actualSize if/when we get the last piece.
246         actualSize := -1
247         pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
248         errors := make(chan error, pieces)
249         var wg sync.WaitGroup
250         wg.Add(pieces)
251         for p := 0; p < pieces; p++ {
252                 // Each goroutine retrieves one piece. If we hit an
253                 // error, it is sent to the errors chan so get() can
254                 // return it -- but only if the error happens before
255                 // ctx is done. This way, if ctx is done before we hit
256                 // any other error (e.g., requesting client has hung
257                 // up), we return the original ctx.Err() instead of
258                 // the secondary errors from the transfers that got
259                 // interrupted as a result.
260                 go func(p int) {
261                         defer wg.Done()
262                         startPos := p * azureMaxGetBytes
263                         endPos := startPos + azureMaxGetBytes
264                         if endPos > expectSize {
265                                 endPos = expectSize
266                         }
267                         var rdr io.ReadCloser
268                         var err error
269                         gotRdr := make(chan struct{})
270                         go func() {
271                                 defer close(gotRdr)
272                                 if startPos == 0 && endPos == expectSize {
273                                         rdr, err = v.bsClient.GetBlob(v.ContainerName, loc)
274                                 } else {
275                                         rdr, err = v.bsClient.GetBlobRange(v.ContainerName, loc, fmt.Sprintf("%d-%d", startPos, endPos-1), nil)
276                                 }
277                         }()
278                         select {
279                         case <-ctx.Done():
280                                 go func() {
281                                         <-gotRdr
282                                         if err == nil {
283                                                 rdr.Close()
284                                         }
285                                 }()
286                                 return
287                         case <-gotRdr:
288                         }
289                         if err != nil {
290                                 errors <- err
291                                 cancel()
292                                 return
293                         }
294                         go func() {
295                                 // Close the reader when the client
296                                 // hangs up or another piece fails
297                                 // (possibly interrupting ReadFull())
298                                 // or when all pieces succeed and
299                                 // get() returns.
300                                 <-ctx.Done()
301                                 rdr.Close()
302                         }()
303                         n, err := io.ReadFull(rdr, buf[startPos:endPos])
304                         if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
305                                 // If we don't know the actual size,
306                                 // and just tried reading 64 MiB, it's
307                                 // normal to encounter EOF.
308                         } else if err != nil {
309                                 if ctx.Err() == nil {
310                                         errors <- err
311                                 }
312                                 cancel()
313                                 return
314                         }
315                         if p == pieces-1 {
316                                 actualSize = startPos + n
317                         }
318                 }(p)
319         }
320         wg.Wait()
321         close(errors)
322         if len(errors) > 0 {
323                 return 0, v.translateError(<-errors)
324         }
325         if ctx.Err() != nil {
326                 return 0, ctx.Err()
327         }
328         return actualSize, nil
329 }
330
331 // Compare the given data with existing stored data.
332 func (v *AzureBlobVolume) Compare(ctx context.Context, loc string, expect []byte) error {
333         trashed, _, err := v.checkTrashed(loc)
334         if err != nil {
335                 return err
336         }
337         if trashed {
338                 return os.ErrNotExist
339         }
340         var rdr io.ReadCloser
341         gotRdr := make(chan struct{})
342         go func() {
343                 defer close(gotRdr)
344                 rdr, err = v.bsClient.GetBlob(v.ContainerName, loc)
345         }()
346         select {
347         case <-ctx.Done():
348                 go func() {
349                         <-gotRdr
350                         if err == nil {
351                                 rdr.Close()
352                         }
353                 }()
354                 return ctx.Err()
355         case <-gotRdr:
356         }
357         if err != nil {
358                 return v.translateError(err)
359         }
360         defer rdr.Close()
361         return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
362 }
363
364 // Put stores a Keep block as a block blob in the container.
365 func (v *AzureBlobVolume) Put(ctx context.Context, loc string, block []byte) error {
366         if v.ReadOnly {
367                 return MethodDisabledError
368         }
369         // Send the block data through a pipe, so that (if we need to)
370         // we can close the pipe early and abandon our
371         // CreateBlockBlobFromReader() goroutine, without worrying
372         // about CreateBlockBlobFromReader() accessing our block
373         // buffer after we release it.
374         bufr, bufw := io.Pipe()
375         go func() {
376                 io.Copy(bufw, bytes.NewReader(block))
377                 bufw.Close()
378         }()
379         errChan := make(chan error)
380         go func() {
381                 errChan <- v.bsClient.CreateBlockBlobFromReader(v.ContainerName, loc, uint64(len(block)), bufr, nil)
382         }()
383         select {
384         case <-ctx.Done():
385                 theConfig.debugLogf("%s: taking CreateBlockBlobFromReader's input away: %s", v, ctx.Err())
386                 // Our pipe might be stuck in Write(), waiting for
387                 // io.Copy() to read. If so, un-stick it. This means
388                 // CreateBlockBlobFromReader will get corrupt data,
389                 // but that's OK: the size won't match, so the write
390                 // will fail.
391                 go io.Copy(ioutil.Discard, bufr)
392                 // CloseWithError() will return once pending I/O is done.
393                 bufw.CloseWithError(ctx.Err())
394                 theConfig.debugLogf("%s: abandoning CreateBlockBlobFromReader goroutine", v)
395                 return ctx.Err()
396         case err := <-errChan:
397                 return err
398         }
399 }
400
401 // Touch updates the last-modified property of a block blob.
402 func (v *AzureBlobVolume) Touch(loc string) error {
403         if v.ReadOnly {
404                 return MethodDisabledError
405         }
406         trashed, metadata, err := v.checkTrashed(loc)
407         if err != nil {
408                 return err
409         }
410         if trashed {
411                 return os.ErrNotExist
412         }
413
414         metadata["touch"] = fmt.Sprintf("%d", time.Now())
415         return v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
416 }
417
418 // Mtime returns the last-modified property of a block blob.
419 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
420         trashed, _, err := v.checkTrashed(loc)
421         if err != nil {
422                 return time.Time{}, err
423         }
424         if trashed {
425                 return time.Time{}, os.ErrNotExist
426         }
427
428         props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
429         if err != nil {
430                 return time.Time{}, err
431         }
432         return time.Parse(time.RFC1123, props.LastModified)
433 }
434
435 // IndexTo writes a list of Keep blocks that are stored in the
436 // container.
437 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
438         params := storage.ListBlobsParameters{
439                 Prefix:  prefix,
440                 Include: "metadata",
441         }
442         for {
443                 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
444                 if err != nil {
445                         return err
446                 }
447                 for _, b := range resp.Blobs {
448                         t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
449                         if err != nil {
450                                 return err
451                         }
452                         if !v.isKeepBlock(b.Name) {
453                                 continue
454                         }
455                         if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
456                                 // A new zero-length blob is probably
457                                 // just a new non-empty blob that
458                                 // hasn't committed its data yet (see
459                                 // Get()), and in any case has no
460                                 // value.
461                                 continue
462                         }
463                         if b.Metadata["expires_at"] != "" {
464                                 // Trashed blob; exclude it from response
465                                 continue
466                         }
467                         fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.UnixNano())
468                 }
469                 if resp.NextMarker == "" {
470                         return nil
471                 }
472                 params.Marker = resp.NextMarker
473         }
474 }
475
476 // Trash a Keep block.
477 func (v *AzureBlobVolume) Trash(loc string) error {
478         if v.ReadOnly {
479                 return MethodDisabledError
480         }
481
482         // Ideally we would use If-Unmodified-Since, but that
483         // particular condition seems to be ignored by Azure. Instead,
484         // we get the Etag before checking Mtime, and use If-Match to
485         // ensure we don't delete data if Put() or Touch() happens
486         // between our calls to Mtime() and DeleteBlob().
487         props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
488         if err != nil {
489                 return err
490         }
491         if t, err := v.Mtime(loc); err != nil {
492                 return err
493         } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
494                 return nil
495         }
496
497         // If TrashLifetime == 0, just delete it
498         if theConfig.TrashLifetime == 0 {
499                 return v.bsClient.DeleteBlob(v.ContainerName, loc, map[string]string{
500                         "If-Match": props.Etag,
501                 })
502         }
503
504         // Otherwise, mark as trash
505         return v.bsClient.SetBlobMetadata(v.ContainerName, loc, map[string]string{
506                 "expires_at": fmt.Sprintf("%d", time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()),
507         }, map[string]string{
508                 "If-Match": props.Etag,
509         })
510 }
511
512 // Untrash a Keep block.
513 // Delete the expires_at metadata attribute
514 func (v *AzureBlobVolume) Untrash(loc string) error {
515         // if expires_at does not exist, return NotFoundError
516         metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
517         if err != nil {
518                 return v.translateError(err)
519         }
520         if metadata["expires_at"] == "" {
521                 return os.ErrNotExist
522         }
523
524         // reset expires_at metadata attribute
525         metadata["expires_at"] = ""
526         err = v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
527         return v.translateError(err)
528 }
529
530 // Status returns a VolumeStatus struct with placeholder data.
531 func (v *AzureBlobVolume) Status() *VolumeStatus {
532         return &VolumeStatus{
533                 DeviceNum: 1,
534                 BytesFree: BlockSize * 1000,
535                 BytesUsed: 1,
536         }
537 }
538
539 // String returns a volume label, including the container name.
540 func (v *AzureBlobVolume) String() string {
541         return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
542 }
543
544 // Writable returns true, unless the -readonly flag was on when the
545 // volume was added.
546 func (v *AzureBlobVolume) Writable() bool {
547         return !v.ReadOnly
548 }
549
550 // Replication returns the replication level of the container, as
551 // specified by the -azure-storage-replication argument.
552 func (v *AzureBlobVolume) Replication() int {
553         return v.AzureReplication
554 }
555
556 // If possible, translate an Azure SDK error to a recognizable error
557 // like os.ErrNotExist.
558 func (v *AzureBlobVolume) translateError(err error) error {
559         switch {
560         case err == nil:
561                 return err
562         case strings.Contains(err.Error(), "Not Found"):
563                 // "storage: service returned without a response body (404 Not Found)"
564                 return os.ErrNotExist
565         default:
566                 return err
567         }
568 }
569
570 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
571
572 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
573         return keepBlockRegexp.MatchString(s)
574 }
575
576 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
577 // and deletes them from the volume.
578 func (v *AzureBlobVolume) EmptyTrash() {
579         var bytesDeleted, bytesInTrash int64
580         var blocksDeleted, blocksInTrash int
581         params := storage.ListBlobsParameters{Include: "metadata"}
582
583         for {
584                 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
585                 if err != nil {
586                         log.Printf("EmptyTrash: ListBlobs: %v", err)
587                         break
588                 }
589                 for _, b := range resp.Blobs {
590                         // Check if the block is expired
591                         if b.Metadata["expires_at"] == "" {
592                                 continue
593                         }
594
595                         blocksInTrash++
596                         bytesInTrash += b.Properties.ContentLength
597
598                         expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
599                         if err != nil {
600                                 log.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
601                                 continue
602                         }
603
604                         if expiresAt > time.Now().Unix() {
605                                 continue
606                         }
607
608                         err = v.bsClient.DeleteBlob(v.ContainerName, b.Name, map[string]string{
609                                 "If-Match": b.Properties.Etag,
610                         })
611                         if err != nil {
612                                 log.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
613                                 continue
614                         }
615                         blocksDeleted++
616                         bytesDeleted += b.Properties.ContentLength
617                 }
618                 if resp.NextMarker == "" {
619                         break
620                 }
621                 params.Marker = resp.NextMarker
622         }
623
624         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)
625 }