1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/ctxlog"
26 "github.com/Azure/azure-sdk-for-go/storage"
27 "github.com/prometheus/client_golang/prometheus"
28 "github.com/sirupsen/logrus"
32 driver["Azure"] = newAzureBlobVolume
35 func newAzureBlobVolume(cluster *arvados.Cluster, volume arvados.Volume, logger logrus.FieldLogger, metrics *volumeMetricsVecs) (Volume, error) {
36 v := &AzureBlobVolume{
37 RequestTimeout: azureDefaultRequestTimeout,
38 WriteRaceInterval: azureDefaultWriteRaceInterval,
39 WriteRacePollTime: azureDefaultWriteRacePollTime,
45 err := json.Unmarshal(volume.DriverParameters, &v)
49 if v.ListBlobsRetryDelay == 0 {
50 v.ListBlobsRetryDelay = azureDefaultListBlobsRetryDelay
52 if v.ListBlobsMaxAttempts == 0 {
53 v.ListBlobsMaxAttempts = azureDefaultListBlobsMaxAttempts
55 if v.StorageBaseURL == "" {
56 v.StorageBaseURL = storage.DefaultBaseURL
58 if v.ContainerName == "" || v.StorageAccountName == "" || v.StorageAccountKey == "" {
59 return nil, errors.New("DriverParameters: ContainerName, StorageAccountName, and StorageAccountKey must be provided")
61 azc, err := storage.NewClient(v.StorageAccountName, v.StorageAccountKey, v.StorageBaseURL, storage.DefaultAPIVersion, true)
63 return nil, fmt.Errorf("creating Azure storage client: %s", err)
66 v.azClient.Sender = &singleSender{}
67 v.azClient.HTTPClient = &http.Client{
68 Timeout: time.Duration(v.RequestTimeout),
70 bs := v.azClient.GetBlobService()
71 v.container = &azureContainer{
72 ctr: bs.GetContainerReference(v.ContainerName),
75 if ok, err := v.container.Exists(); err != nil {
78 return nil, fmt.Errorf("Azure container %q does not exist: %s", v.ContainerName, err)
83 func (v *AzureBlobVolume) check() error {
84 lbls := prometheus.Labels{"device_id": v.GetDeviceID()}
85 v.container.stats.opsCounters, v.container.stats.errCounters, v.container.stats.ioBytes = v.metrics.getCounterVecsFor(lbls)
90 azureDefaultRequestTimeout = arvados.Duration(10 * time.Minute)
91 azureDefaultListBlobsMaxAttempts = 12
92 azureDefaultListBlobsRetryDelay = arvados.Duration(10 * time.Second)
93 azureDefaultWriteRaceInterval = arvados.Duration(15 * time.Second)
94 azureDefaultWriteRacePollTime = arvados.Duration(time.Second)
97 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
99 type AzureBlobVolume struct {
100 StorageAccountName string
101 StorageAccountKey string
102 StorageBaseURL string // "" means default, "core.windows.net"
104 RequestTimeout arvados.Duration
105 ListBlobsRetryDelay arvados.Duration
106 ListBlobsMaxAttempts int
108 WriteRaceInterval arvados.Duration
109 WriteRacePollTime arvados.Duration
111 cluster *arvados.Cluster
112 volume arvados.Volume
113 logger logrus.FieldLogger
114 metrics *volumeMetricsVecs
115 azClient storage.Client
116 container *azureContainer
119 // singleSender is a single-attempt storage.Sender.
120 type singleSender struct{}
122 // Send performs req exactly once.
123 func (*singleSender) Send(c *storage.Client, req *http.Request) (resp *http.Response, err error) {
124 return c.HTTPClient.Do(req)
127 // Type implements Volume.
128 func (v *AzureBlobVolume) Type() string {
132 // GetDeviceID returns a globally unique ID for the storage container.
133 func (v *AzureBlobVolume) GetDeviceID() string {
134 return "azure://" + v.StorageBaseURL + "/" + v.StorageAccountName + "/" + v.ContainerName
137 // Return true if expires_at metadata attribute is found on the block
138 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
139 metadata, err := v.container.GetBlobMetadata(loc)
141 return false, metadata, v.translateError(err)
143 if metadata["expires_at"] != "" {
144 return true, metadata, nil
146 return false, metadata, nil
149 // Get reads a Keep block that has been stored as a block blob in the
152 // If the block is younger than azureWriteRaceInterval and is
153 // unexpectedly empty, assume a PutBlob operation is in progress, and
154 // wait for it to finish writing.
155 func (v *AzureBlobVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
156 trashed, _, err := v.checkTrashed(loc)
161 return 0, os.ErrNotExist
163 var deadline time.Time
164 haveDeadline := false
165 size, err := v.get(ctx, loc, buf)
166 for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
167 // Seeing a brand new empty block probably means we're
168 // in a race with CreateBlob, which under the hood
169 // (apparently) does "CreateEmpty" and "CommitData"
170 // with no additional transaction locking.
172 t, err := v.Mtime(loc)
174 ctxlog.FromContext(ctx).Print("Got empty block (possible race) but Mtime failed: ", err)
177 deadline = t.Add(v.WriteRaceInterval.Duration())
178 if time.Now().After(deadline) {
181 ctxlog.FromContext(ctx).Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
183 } else if time.Now().After(deadline) {
189 case <-time.After(v.WriteRacePollTime.Duration()):
191 size, err = v.get(ctx, loc, buf)
194 ctxlog.FromContext(ctx).Printf("Race ended with size==%d", size)
199 func (v *AzureBlobVolume) get(ctx context.Context, loc string, buf []byte) (int, error) {
200 ctx, cancel := context.WithCancel(ctx)
203 pieceSize := BlockSize
204 if v.MaxGetBytes > 0 && v.MaxGetBytes < BlockSize {
205 pieceSize = v.MaxGetBytes
209 expectSize := len(buf)
210 if pieceSize < BlockSize {
211 // Unfortunately the handler doesn't tell us how long the blob
212 // is expected to be, so we have to ask Azure.
213 props, err := v.container.GetBlobProperties(loc)
215 return 0, v.translateError(err)
217 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
218 return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
220 expectSize = int(props.ContentLength)
221 pieces = (expectSize + pieceSize - 1) / pieceSize
228 // We'll update this actualSize if/when we get the last piece.
230 errors := make(chan error, pieces)
231 var wg sync.WaitGroup
233 for p := 0; p < pieces; p++ {
234 // Each goroutine retrieves one piece. If we hit an
235 // error, it is sent to the errors chan so get() can
236 // return it -- but only if the error happens before
237 // ctx is done. This way, if ctx is done before we hit
238 // any other error (e.g., requesting client has hung
239 // up), we return the original ctx.Err() instead of
240 // the secondary errors from the transfers that got
241 // interrupted as a result.
244 startPos := p * pieceSize
245 endPos := startPos + pieceSize
246 if endPos > expectSize {
249 var rdr io.ReadCloser
251 gotRdr := make(chan struct{})
254 if startPos == 0 && endPos == expectSize {
255 rdr, err = v.container.GetBlob(loc)
257 rdr, err = v.container.GetBlobRange(loc, startPos, endPos-1, nil)
277 // Close the reader when the client
278 // hangs up or another piece fails
279 // (possibly interrupting ReadFull())
280 // or when all pieces succeed and
285 n, err := io.ReadFull(rdr, buf[startPos:endPos])
286 if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
287 // If we don't know the actual size,
288 // and just tried reading 64 MiB, it's
289 // normal to encounter EOF.
290 } else if err != nil {
291 if ctx.Err() == nil {
298 actualSize = startPos + n
305 return 0, v.translateError(<-errors)
307 if ctx.Err() != nil {
310 return actualSize, nil
313 // Compare the given data with existing stored data.
314 func (v *AzureBlobVolume) Compare(ctx context.Context, loc string, expect []byte) error {
315 trashed, _, err := v.checkTrashed(loc)
320 return os.ErrNotExist
322 var rdr io.ReadCloser
323 gotRdr := make(chan struct{})
326 rdr, err = v.container.GetBlob(loc)
340 return v.translateError(err)
343 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
346 // Put stores a Keep block as a block blob in the container.
347 func (v *AzureBlobVolume) Put(ctx context.Context, loc string, block []byte) error {
348 if v.volume.ReadOnly {
349 return MethodDisabledError
351 // Send the block data through a pipe, so that (if we need to)
352 // we can close the pipe early and abandon our
353 // CreateBlockBlobFromReader() goroutine, without worrying
354 // about CreateBlockBlobFromReader() accessing our block
355 // buffer after we release it.
356 bufr, bufw := io.Pipe()
358 io.Copy(bufw, bytes.NewReader(block))
361 errChan := make(chan error)
363 var body io.Reader = bufr
365 // We must send a "Content-Length: 0" header,
366 // but the http client interprets
367 // ContentLength==0 as "unknown" unless it can
368 // confirm by introspection that Body will
373 errChan <- v.container.CreateBlockBlobFromReader(loc, len(block), body, nil)
377 ctxlog.FromContext(ctx).Debugf("%s: taking CreateBlockBlobFromReader's input away: %s", v, ctx.Err())
378 // Our pipe might be stuck in Write(), waiting for
379 // io.Copy() to read. If so, un-stick it. This means
380 // CreateBlockBlobFromReader will get corrupt data,
381 // but that's OK: the size won't match, so the write
383 go io.Copy(ioutil.Discard, bufr)
384 // CloseWithError() will return once pending I/O is done.
385 bufw.CloseWithError(ctx.Err())
386 ctxlog.FromContext(ctx).Debugf("%s: abandoning CreateBlockBlobFromReader goroutine", v)
388 case err := <-errChan:
393 // Touch updates the last-modified property of a block blob.
394 func (v *AzureBlobVolume) Touch(loc string) error {
395 if v.volume.ReadOnly {
396 return MethodDisabledError
398 trashed, metadata, err := v.checkTrashed(loc)
403 return os.ErrNotExist
406 metadata["touch"] = fmt.Sprintf("%d", time.Now().Unix())
407 return v.container.SetBlobMetadata(loc, metadata, nil)
410 // Mtime returns the last-modified property of a block blob.
411 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
412 trashed, _, err := v.checkTrashed(loc)
414 return time.Time{}, err
417 return time.Time{}, os.ErrNotExist
420 props, err := v.container.GetBlobProperties(loc)
422 return time.Time{}, err
424 return time.Time(props.LastModified), nil
427 // IndexTo writes a list of Keep blocks that are stored in the
429 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
430 params := storage.ListBlobsParameters{
432 Include: &storage.IncludeBlobDataset{Metadata: true},
434 for page := 1; ; page++ {
435 resp, err := v.listBlobs(page, params)
439 for _, b := range resp.Blobs {
440 if !v.isKeepBlock(b.Name) {
443 modtime := time.Time(b.Properties.LastModified)
444 if b.Properties.ContentLength == 0 && modtime.Add(v.WriteRaceInterval.Duration()).After(time.Now()) {
445 // A new zero-length blob is probably
446 // just a new non-empty blob that
447 // hasn't committed its data yet (see
448 // Get()), and in any case has no
452 if b.Metadata["expires_at"] != "" {
453 // Trashed blob; exclude it from response
456 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, modtime.UnixNano())
458 if resp.NextMarker == "" {
461 params.Marker = resp.NextMarker
465 // call v.container.ListBlobs, retrying if needed.
466 func (v *AzureBlobVolume) listBlobs(page int, params storage.ListBlobsParameters) (resp storage.BlobListResponse, err error) {
467 for i := 0; i < v.ListBlobsMaxAttempts; i++ {
468 resp, err = v.container.ListBlobs(params)
469 err = v.translateError(err)
470 if err == VolumeBusyError {
471 v.logger.Printf("ListBlobs: will retry page %d in %s after error: %s", page, v.ListBlobsRetryDelay, err)
472 time.Sleep(time.Duration(v.ListBlobsRetryDelay))
481 // Trash a Keep block.
482 func (v *AzureBlobVolume) Trash(loc string) error {
483 if v.volume.ReadOnly && !v.volume.AllowTrashWhenReadOnly {
484 return MethodDisabledError
486 // Ideally we would use If-Unmodified-Since, but that
487 // particular condition seems to be ignored by Azure. Instead,
488 // we get the Etag before checking Mtime, and use If-Match to
489 // ensure we don't delete data if Put() or Touch() happens
490 // between our calls to Mtime() and DeleteBlob().
491 props, err := v.container.GetBlobProperties(loc)
495 if t, err := v.Mtime(loc); err != nil {
497 } else if time.Since(t) < v.cluster.Collections.BlobSigningTTL.Duration() {
501 // If BlobTrashLifetime == 0, just delete it
502 if v.cluster.Collections.BlobTrashLifetime == 0 {
503 return v.container.DeleteBlob(loc, &storage.DeleteBlobOptions{
508 // Otherwise, mark as trash
509 return v.container.SetBlobMetadata(loc, storage.BlobMetadata{
510 "expires_at": fmt.Sprintf("%d", time.Now().Add(v.cluster.Collections.BlobTrashLifetime.Duration()).Unix()),
511 }, &storage.SetBlobMetadataOptions{
516 // Untrash a Keep block.
517 // Delete the expires_at metadata attribute
518 func (v *AzureBlobVolume) Untrash(loc string) error {
519 // if expires_at does not exist, return NotFoundError
520 metadata, err := v.container.GetBlobMetadata(loc)
522 return v.translateError(err)
524 if metadata["expires_at"] == "" {
525 return os.ErrNotExist
528 // reset expires_at metadata attribute
529 metadata["expires_at"] = ""
530 err = v.container.SetBlobMetadata(loc, metadata, nil)
531 return v.translateError(err)
534 // Status returns a VolumeStatus struct with placeholder data.
535 func (v *AzureBlobVolume) Status() *VolumeStatus {
536 return &VolumeStatus{
538 BytesFree: BlockSize * 1000,
543 // String returns a volume label, including the container name.
544 func (v *AzureBlobVolume) String() string {
545 return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
548 // If possible, translate an Azure SDK error to a recognizable error
549 // like os.ErrNotExist.
550 func (v *AzureBlobVolume) translateError(err error) error {
554 case strings.Contains(err.Error(), "StatusCode=503"):
555 // "storage: service returned error: StatusCode=503, ErrorCode=ServerBusy, ErrorMessage=The server is busy" (See #14804)
556 return VolumeBusyError
557 case strings.Contains(err.Error(), "Not Found"):
558 // "storage: service returned without a response body (404 Not Found)"
559 return os.ErrNotExist
560 case strings.Contains(err.Error(), "ErrorCode=BlobNotFound"):
561 // "storage: service returned error: StatusCode=404, ErrorCode=BlobNotFound, ErrorMessage=The specified blob does not exist.\n..."
562 return os.ErrNotExist
568 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
570 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
571 return keepBlockRegexp.MatchString(s)
574 // EmptyTrash looks for trashed blocks that exceeded BlobTrashLifetime
575 // and deletes them from the volume.
576 func (v *AzureBlobVolume) EmptyTrash() {
577 var bytesDeleted, bytesInTrash int64
578 var blocksDeleted, blocksInTrash int64
580 doBlob := func(b storage.Blob) {
581 // Check whether the block is flagged as trash
582 if b.Metadata["expires_at"] == "" {
586 atomic.AddInt64(&blocksInTrash, 1)
587 atomic.AddInt64(&bytesInTrash, b.Properties.ContentLength)
589 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
591 v.logger.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
595 if expiresAt > time.Now().Unix() {
599 err = v.container.DeleteBlob(b.Name, &storage.DeleteBlobOptions{
600 IfMatch: b.Properties.Etag,
603 v.logger.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
606 atomic.AddInt64(&blocksDeleted, 1)
607 atomic.AddInt64(&bytesDeleted, b.Properties.ContentLength)
610 var wg sync.WaitGroup
611 todo := make(chan storage.Blob, v.cluster.Collections.BlobDeleteConcurrency)
612 for i := 0; i < v.cluster.Collections.BlobDeleteConcurrency; i++ {
616 for b := range todo {
622 params := storage.ListBlobsParameters{Include: &storage.IncludeBlobDataset{Metadata: true}}
623 for page := 1; ; page++ {
624 resp, err := v.listBlobs(page, params)
626 v.logger.Printf("EmptyTrash: ListBlobs: %v", err)
629 for _, b := range resp.Blobs {
632 if resp.NextMarker == "" {
635 params.Marker = resp.NextMarker
640 v.logger.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)
643 // InternalStats returns bucket I/O and API call counters.
644 func (v *AzureBlobVolume) InternalStats() interface{} {
645 return &v.container.stats
648 type azureBlobStats struct {
653 GetMetadataOps uint64
654 GetPropertiesOps uint64
656 SetMetadataOps uint64
661 func (s *azureBlobStats) TickErr(err error) {
665 errType := fmt.Sprintf("%T", err)
666 if err, ok := err.(storage.AzureStorageServiceError); ok {
667 errType = errType + fmt.Sprintf(" %d (%s)", err.StatusCode, err.Code)
669 s.statsTicker.TickErr(err, errType)
672 // azureContainer wraps storage.Container in order to count I/O and
674 type azureContainer struct {
675 ctr *storage.Container
679 func (c *azureContainer) Exists() (bool, error) {
680 c.stats.TickOps("exists")
681 c.stats.Tick(&c.stats.Ops)
682 ok, err := c.ctr.Exists()
687 func (c *azureContainer) GetBlobMetadata(bname string) (storage.BlobMetadata, error) {
688 c.stats.TickOps("get_metadata")
689 c.stats.Tick(&c.stats.Ops, &c.stats.GetMetadataOps)
690 b := c.ctr.GetBlobReference(bname)
691 err := b.GetMetadata(nil)
693 return b.Metadata, err
696 func (c *azureContainer) GetBlobProperties(bname string) (*storage.BlobProperties, error) {
697 c.stats.TickOps("get_properties")
698 c.stats.Tick(&c.stats.Ops, &c.stats.GetPropertiesOps)
699 b := c.ctr.GetBlobReference(bname)
700 err := b.GetProperties(nil)
702 return &b.Properties, err
705 func (c *azureContainer) GetBlob(bname string) (io.ReadCloser, error) {
706 c.stats.TickOps("get")
707 c.stats.Tick(&c.stats.Ops, &c.stats.GetOps)
708 b := c.ctr.GetBlobReference(bname)
709 rdr, err := b.Get(nil)
711 return NewCountingReader(rdr, c.stats.TickInBytes), err
714 func (c *azureContainer) GetBlobRange(bname string, start, end int, opts *storage.GetBlobOptions) (io.ReadCloser, error) {
715 c.stats.TickOps("get_range")
716 c.stats.Tick(&c.stats.Ops, &c.stats.GetRangeOps)
717 b := c.ctr.GetBlobReference(bname)
718 rdr, err := b.GetRange(&storage.GetBlobRangeOptions{
719 Range: &storage.BlobRange{
720 Start: uint64(start),
723 GetBlobOptions: opts,
726 return NewCountingReader(rdr, c.stats.TickInBytes), err
729 // If we give it an io.Reader that doesn't also have a Len() int
730 // method, the Azure SDK determines data size by copying the data into
731 // a new buffer, which is not a good use of memory.
732 type readerWithAzureLen struct {
737 // Len satisfies the private lener interface in azure-sdk-for-go.
738 func (r *readerWithAzureLen) Len() int {
742 func (c *azureContainer) CreateBlockBlobFromReader(bname string, size int, rdr io.Reader, opts *storage.PutBlobOptions) error {
743 c.stats.TickOps("create")
744 c.stats.Tick(&c.stats.Ops, &c.stats.CreateOps)
746 rdr = &readerWithAzureLen{
747 Reader: NewCountingReader(rdr, c.stats.TickOutBytes),
751 b := c.ctr.GetBlobReference(bname)
752 err := b.CreateBlockBlobFromReader(rdr, opts)
757 func (c *azureContainer) SetBlobMetadata(bname string, m storage.BlobMetadata, opts *storage.SetBlobMetadataOptions) error {
758 c.stats.TickOps("set_metadata")
759 c.stats.Tick(&c.stats.Ops, &c.stats.SetMetadataOps)
760 b := c.ctr.GetBlobReference(bname)
762 err := b.SetMetadata(opts)
767 func (c *azureContainer) ListBlobs(params storage.ListBlobsParameters) (storage.BlobListResponse, error) {
768 c.stats.TickOps("list")
769 c.stats.Tick(&c.stats.Ops, &c.stats.ListOps)
770 resp, err := c.ctr.ListBlobs(params)
775 func (c *azureContainer) DeleteBlob(bname string, opts *storage.DeleteBlobOptions) error {
776 c.stats.TickOps("delete")
777 c.stats.Tick(&c.stats.Ops, &c.stats.DelOps)
778 b := c.ctr.GetBlobReference(bname)
779 err := b.Delete(opts)