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 {
484 return MethodDisabledError
487 // Ideally we would use If-Unmodified-Since, but that
488 // particular condition seems to be ignored by Azure. Instead,
489 // we get the Etag before checking Mtime, and use If-Match to
490 // ensure we don't delete data if Put() or Touch() happens
491 // between our calls to Mtime() and DeleteBlob().
492 props, err := v.container.GetBlobProperties(loc)
496 if t, err := v.Mtime(loc); err != nil {
498 } else if time.Since(t) < v.cluster.Collections.BlobSigningTTL.Duration() {
502 // If BlobTrashLifetime == 0, just delete it
503 if v.cluster.Collections.BlobTrashLifetime == 0 {
504 return v.container.DeleteBlob(loc, &storage.DeleteBlobOptions{
509 // Otherwise, mark as trash
510 return v.container.SetBlobMetadata(loc, storage.BlobMetadata{
511 "expires_at": fmt.Sprintf("%d", time.Now().Add(v.cluster.Collections.BlobTrashLifetime.Duration()).Unix()),
512 }, &storage.SetBlobMetadataOptions{
517 // Untrash a Keep block.
518 // Delete the expires_at metadata attribute
519 func (v *AzureBlobVolume) Untrash(loc string) error {
520 // if expires_at does not exist, return NotFoundError
521 metadata, err := v.container.GetBlobMetadata(loc)
523 return v.translateError(err)
525 if metadata["expires_at"] == "" {
526 return os.ErrNotExist
529 // reset expires_at metadata attribute
530 metadata["expires_at"] = ""
531 err = v.container.SetBlobMetadata(loc, metadata, nil)
532 return v.translateError(err)
535 // Status returns a VolumeStatus struct with placeholder data.
536 func (v *AzureBlobVolume) Status() *VolumeStatus {
537 return &VolumeStatus{
539 BytesFree: BlockSize * 1000,
544 // String returns a volume label, including the container name.
545 func (v *AzureBlobVolume) String() string {
546 return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
549 // If possible, translate an Azure SDK error to a recognizable error
550 // like os.ErrNotExist.
551 func (v *AzureBlobVolume) translateError(err error) error {
555 case strings.Contains(err.Error(), "StatusCode=503"):
556 // "storage: service returned error: StatusCode=503, ErrorCode=ServerBusy, ErrorMessage=The server is busy" (See #14804)
557 return VolumeBusyError
558 case strings.Contains(err.Error(), "Not Found"):
559 // "storage: service returned without a response body (404 Not Found)"
560 return os.ErrNotExist
561 case strings.Contains(err.Error(), "ErrorCode=BlobNotFound"):
562 // "storage: service returned error: StatusCode=404, ErrorCode=BlobNotFound, ErrorMessage=The specified blob does not exist.\n..."
563 return os.ErrNotExist
569 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
571 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
572 return keepBlockRegexp.MatchString(s)
575 // EmptyTrash looks for trashed blocks that exceeded BlobTrashLifetime
576 // and deletes them from the volume.
577 func (v *AzureBlobVolume) EmptyTrash() {
578 if v.cluster.Collections.BlobDeleteConcurrency < 1 {
582 var bytesDeleted, bytesInTrash int64
583 var blocksDeleted, blocksInTrash int64
585 doBlob := func(b storage.Blob) {
586 // Check whether the block is flagged as trash
587 if b.Metadata["expires_at"] == "" {
591 atomic.AddInt64(&blocksInTrash, 1)
592 atomic.AddInt64(&bytesInTrash, b.Properties.ContentLength)
594 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
596 v.logger.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
600 if expiresAt > time.Now().Unix() {
604 err = v.container.DeleteBlob(b.Name, &storage.DeleteBlobOptions{
605 IfMatch: b.Properties.Etag,
608 v.logger.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
611 atomic.AddInt64(&blocksDeleted, 1)
612 atomic.AddInt64(&bytesDeleted, b.Properties.ContentLength)
615 var wg sync.WaitGroup
616 todo := make(chan storage.Blob, v.cluster.Collections.BlobDeleteConcurrency)
617 for i := 0; i < v.cluster.Collections.BlobDeleteConcurrency; i++ {
621 for b := range todo {
627 params := storage.ListBlobsParameters{Include: &storage.IncludeBlobDataset{Metadata: true}}
628 for page := 1; ; page++ {
629 resp, err := v.listBlobs(page, params)
631 v.logger.Printf("EmptyTrash: ListBlobs: %v", err)
634 for _, b := range resp.Blobs {
637 if resp.NextMarker == "" {
640 params.Marker = resp.NextMarker
645 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)
648 // InternalStats returns bucket I/O and API call counters.
649 func (v *AzureBlobVolume) InternalStats() interface{} {
650 return &v.container.stats
653 type azureBlobStats struct {
658 GetMetadataOps uint64
659 GetPropertiesOps uint64
661 SetMetadataOps uint64
666 func (s *azureBlobStats) TickErr(err error) {
670 errType := fmt.Sprintf("%T", err)
671 if err, ok := err.(storage.AzureStorageServiceError); ok {
672 errType = errType + fmt.Sprintf(" %d (%s)", err.StatusCode, err.Code)
674 s.statsTicker.TickErr(err, errType)
677 // azureContainer wraps storage.Container in order to count I/O and
679 type azureContainer struct {
680 ctr *storage.Container
684 func (c *azureContainer) Exists() (bool, error) {
685 c.stats.TickOps("exists")
686 c.stats.Tick(&c.stats.Ops)
687 ok, err := c.ctr.Exists()
692 func (c *azureContainer) GetBlobMetadata(bname string) (storage.BlobMetadata, error) {
693 c.stats.TickOps("get_metadata")
694 c.stats.Tick(&c.stats.Ops, &c.stats.GetMetadataOps)
695 b := c.ctr.GetBlobReference(bname)
696 err := b.GetMetadata(nil)
698 return b.Metadata, err
701 func (c *azureContainer) GetBlobProperties(bname string) (*storage.BlobProperties, error) {
702 c.stats.TickOps("get_properties")
703 c.stats.Tick(&c.stats.Ops, &c.stats.GetPropertiesOps)
704 b := c.ctr.GetBlobReference(bname)
705 err := b.GetProperties(nil)
707 return &b.Properties, err
710 func (c *azureContainer) GetBlob(bname string) (io.ReadCloser, error) {
711 c.stats.TickOps("get")
712 c.stats.Tick(&c.stats.Ops, &c.stats.GetOps)
713 b := c.ctr.GetBlobReference(bname)
714 rdr, err := b.Get(nil)
716 return NewCountingReader(rdr, c.stats.TickInBytes), err
719 func (c *azureContainer) GetBlobRange(bname string, start, end int, opts *storage.GetBlobOptions) (io.ReadCloser, error) {
720 c.stats.TickOps("get_range")
721 c.stats.Tick(&c.stats.Ops, &c.stats.GetRangeOps)
722 b := c.ctr.GetBlobReference(bname)
723 rdr, err := b.GetRange(&storage.GetBlobRangeOptions{
724 Range: &storage.BlobRange{
725 Start: uint64(start),
728 GetBlobOptions: opts,
731 return NewCountingReader(rdr, c.stats.TickInBytes), err
734 // If we give it an io.Reader that doesn't also have a Len() int
735 // method, the Azure SDK determines data size by copying the data into
736 // a new buffer, which is not a good use of memory.
737 type readerWithAzureLen struct {
742 // Len satisfies the private lener interface in azure-sdk-for-go.
743 func (r *readerWithAzureLen) Len() int {
747 func (c *azureContainer) CreateBlockBlobFromReader(bname string, size int, rdr io.Reader, opts *storage.PutBlobOptions) error {
748 c.stats.TickOps("create")
749 c.stats.Tick(&c.stats.Ops, &c.stats.CreateOps)
751 rdr = &readerWithAzureLen{
752 Reader: NewCountingReader(rdr, c.stats.TickOutBytes),
756 b := c.ctr.GetBlobReference(bname)
757 err := b.CreateBlockBlobFromReader(rdr, opts)
762 func (c *azureContainer) SetBlobMetadata(bname string, m storage.BlobMetadata, opts *storage.SetBlobMetadataOptions) error {
763 c.stats.TickOps("set_metadata")
764 c.stats.Tick(&c.stats.Ops, &c.stats.SetMetadataOps)
765 b := c.ctr.GetBlobReference(bname)
767 err := b.SetMetadata(opts)
772 func (c *azureContainer) ListBlobs(params storage.ListBlobsParameters) (storage.BlobListResponse, error) {
773 c.stats.TickOps("list")
774 c.stats.Tick(&c.stats.Ops, &c.stats.ListOps)
775 resp, err := c.ctr.ListBlobs(params)
780 func (c *azureContainer) DeleteBlob(bname string, opts *storage.DeleteBlobOptions) error {
781 c.stats.TickOps("delete")
782 c.stats.Tick(&c.stats.Ops, &c.stats.DelOps)
783 b := c.ctr.GetBlobReference(bname)
784 err := b.Delete(opts)