1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "git.arvados.org/arvados.git/sdk/go/ctxlog"
24 "github.com/Azure/azure-sdk-for-go/storage"
25 "github.com/prometheus/client_golang/prometheus"
26 "github.com/sirupsen/logrus"
30 driver["Azure"] = newAzureBlobVolume
33 func newAzureBlobVolume(params newVolumeParams) (volume, error) {
34 v := &azureBlobVolume{
35 RequestTimeout: azureDefaultRequestTimeout,
36 WriteRaceInterval: azureDefaultWriteRaceInterval,
37 WriteRacePollTime: azureDefaultWriteRacePollTime,
38 cluster: params.Cluster,
39 volume: params.ConfigVolume,
40 logger: params.Logger,
41 metrics: params.MetricsVecs,
42 bufferPool: params.BufferPool,
44 err := json.Unmarshal(params.ConfigVolume.DriverParameters, &v)
48 if v.ListBlobsRetryDelay == 0 {
49 v.ListBlobsRetryDelay = azureDefaultListBlobsRetryDelay
51 if v.ListBlobsMaxAttempts == 0 {
52 v.ListBlobsMaxAttempts = azureDefaultListBlobsMaxAttempts
54 if v.StorageBaseURL == "" {
55 v.StorageBaseURL = storage.DefaultBaseURL
57 if v.ContainerName == "" || v.StorageAccountName == "" || v.StorageAccountKey == "" {
58 return nil, errors.New("DriverParameters: ContainerName, StorageAccountName, and StorageAccountKey must be provided")
60 azc, err := storage.NewClient(v.StorageAccountName, v.StorageAccountKey, v.StorageBaseURL, storage.DefaultAPIVersion, true)
62 return nil, fmt.Errorf("creating Azure storage client: %s", err)
65 v.azClient.Sender = &singleSender{}
66 v.azClient.HTTPClient = &http.Client{
67 Timeout: time.Duration(v.RequestTimeout),
69 bs := v.azClient.GetBlobService()
70 v.container = &azureContainer{
71 ctr: bs.GetContainerReference(v.ContainerName),
74 if ok, err := v.container.Exists(); err != nil {
77 return nil, fmt.Errorf("Azure container %q does not exist: %s", v.ContainerName, err)
82 func (v *azureBlobVolume) check() error {
83 lbls := prometheus.Labels{"device_id": v.DeviceID()}
84 v.container.stats.opsCounters, v.container.stats.errCounters, v.container.stats.ioBytes = v.metrics.getCounterVecsFor(lbls)
89 azureDefaultRequestTimeout = arvados.Duration(10 * time.Minute)
90 azureDefaultListBlobsMaxAttempts = 12
91 azureDefaultListBlobsRetryDelay = arvados.Duration(10 * time.Second)
92 azureDefaultWriteRaceInterval = arvados.Duration(15 * time.Second)
93 azureDefaultWriteRacePollTime = arvados.Duration(time.Second)
96 // An azureBlobVolume stores and retrieves blocks in an Azure Blob
98 type azureBlobVolume struct {
99 StorageAccountName string
100 StorageAccountKey string
101 StorageBaseURL string // "" means default, "core.windows.net"
103 RequestTimeout arvados.Duration
104 ListBlobsRetryDelay arvados.Duration
105 ListBlobsMaxAttempts int
107 WriteRaceInterval arvados.Duration
108 WriteRacePollTime arvados.Duration
110 cluster *arvados.Cluster
111 volume arvados.Volume
112 logger logrus.FieldLogger
113 metrics *volumeMetricsVecs
114 bufferPool *bufferPool
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 // DeviceID returns a globally unique ID for the storage container.
128 func (v *azureBlobVolume) DeviceID() string {
129 return "azure://" + v.StorageBaseURL + "/" + v.StorageAccountName + "/" + v.ContainerName
132 // Return true if expires_at metadata attribute is found on the block
133 func (v *azureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
134 metadata, err := v.container.GetBlobMetadata(loc)
136 return false, metadata, v.translateError(err)
138 if metadata["expires_at"] != "" {
139 return true, metadata, nil
141 return false, metadata, nil
144 // BlockRead reads a Keep block that has been stored as a block blob
147 // If the block is younger than azureWriteRaceInterval and is
148 // unexpectedly empty, assume a BlockWrite operation is in progress,
149 // and wait for it to finish writing.
150 func (v *azureBlobVolume) BlockRead(ctx context.Context, hash string, w io.WriterAt) error {
151 trashed, _, err := v.checkTrashed(hash)
156 return os.ErrNotExist
158 buf, err := v.bufferPool.GetContext(ctx)
162 defer v.bufferPool.Put(buf)
163 var deadline time.Time
164 wrote, err := v.get(ctx, hash, w)
165 for err == nil && wrote == 0 && hash != "d41d8cd98f00b204e9800998ecf8427e" {
166 // Seeing a brand new empty block probably means we're
167 // in a race with CreateBlob, which under the hood
168 // (apparently) does "CreateEmpty" and "CommitData"
169 // with no additional transaction locking.
170 if deadline.IsZero() {
171 t, err := v.Mtime(hash)
173 ctxlog.FromContext(ctx).Print("Got empty block (possible race) but Mtime failed: ", err)
176 deadline = t.Add(v.WriteRaceInterval.Duration())
177 if time.Now().After(deadline) {
180 ctxlog.FromContext(ctx).Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", hash, time.Since(t), deadline)
181 } else if time.Now().After(deadline) {
187 case <-time.After(v.WriteRacePollTime.Duration()):
189 wrote, err = v.get(ctx, hash, w)
191 if !deadline.IsZero() {
192 ctxlog.FromContext(ctx).Printf("Race ended with size==%d", wrote)
197 func (v *azureBlobVolume) get(ctx context.Context, hash string, dst io.WriterAt) (int, error) {
198 ctx, cancel := context.WithCancel(ctx)
201 pieceSize := BlockSize
202 if v.MaxGetBytes > 0 && v.MaxGetBytes < BlockSize {
203 pieceSize = v.MaxGetBytes
207 expectSize := BlockSize
209 if pieceSize < BlockSize {
210 // Unfortunately the handler doesn't tell us how long
211 // the blob is expected to be, so we have to ask
213 props, err := v.container.GetBlobProperties(hash)
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)", hash, props.ContentLength, BlockSize)
220 expectSize = int(props.ContentLength)
221 pieces = (expectSize + pieceSize - 1) / pieceSize
229 errors := make(chan error, pieces)
230 var wrote atomic.Int64
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(hash)
257 rdr, err = v.container.GetBlobRange(hash, 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.CopyN(io.NewOffsetWriter(dst, int64(startPos)), rdr, int64(endPos-startPos))
287 if pieces == 1 && !sizeKnown && (err == io.ErrUnexpectedEOF || err == io.EOF) {
288 // If we don't know the actual size,
289 // and just tried reading 64 MiB, it's
290 // normal to encounter EOF.
291 } else if err != nil {
301 return int(wrote.Load()), v.translateError(<-errors)
303 return int(wrote.Load()), ctx.Err()
306 // BlockWrite stores a block on the volume. If it already exists, its
307 // timestamp is updated.
308 func (v *azureBlobVolume) BlockWrite(ctx context.Context, hash string, data []byte) error {
309 // Send the block data through a pipe, so that (if we need to)
310 // we can close the pipe early and abandon our
311 // CreateBlockBlobFromReader() goroutine, without worrying
312 // about CreateBlockBlobFromReader() accessing our data
313 // buffer after we release it.
314 bufr, bufw := io.Pipe()
319 errChan := make(chan error, 1)
321 var body io.Reader = bufr
323 // We must send a "Content-Length: 0" header,
324 // but the http client interprets
325 // ContentLength==0 as "unknown" unless it can
326 // confirm by introspection that Body will
331 errChan <- v.container.CreateBlockBlobFromReader(hash, len(data), body, nil)
335 ctxlog.FromContext(ctx).Debugf("%s: taking CreateBlockBlobFromReader's input away: %s", v, ctx.Err())
336 // bufw.CloseWithError() interrupts bufw.Write() if
337 // necessary, ensuring CreateBlockBlobFromReader can't
338 // read any more of our data slice via bufr after we
340 bufw.CloseWithError(ctx.Err())
341 ctxlog.FromContext(ctx).Debugf("%s: abandoning CreateBlockBlobFromReader goroutine", v)
343 case err := <-errChan:
348 // BlockTouch updates the last-modified property of a block blob.
349 func (v *azureBlobVolume) BlockTouch(hash string) error {
350 trashed, metadata, err := v.checkTrashed(hash)
355 return os.ErrNotExist
358 metadata["touch"] = fmt.Sprintf("%d", time.Now().Unix())
359 return v.container.SetBlobMetadata(hash, metadata, nil)
362 // Mtime returns the last-modified property of a block blob.
363 func (v *azureBlobVolume) Mtime(hash string) (time.Time, error) {
364 trashed, _, err := v.checkTrashed(hash)
366 return time.Time{}, err
369 return time.Time{}, os.ErrNotExist
372 props, err := v.container.GetBlobProperties(hash)
374 return time.Time{}, err
376 return time.Time(props.LastModified), nil
379 // Index writes a list of Keep blocks that are stored in the
381 func (v *azureBlobVolume) Index(ctx context.Context, prefix string, writer io.Writer) error {
382 params := storage.ListBlobsParameters{
384 Include: &storage.IncludeBlobDataset{Metadata: true},
386 for page := 1; ; page++ {
391 resp, err := v.listBlobs(page, params)
395 for _, b := range resp.Blobs {
396 if !v.isKeepBlock(b.Name) {
399 modtime := time.Time(b.Properties.LastModified)
400 if b.Properties.ContentLength == 0 && modtime.Add(v.WriteRaceInterval.Duration()).After(time.Now()) {
401 // A new zero-length blob is probably
402 // just a new non-empty blob that
403 // hasn't committed its data yet (see
404 // Get()), and in any case has no
408 if b.Metadata["expires_at"] != "" {
409 // Trashed blob; exclude it from response
412 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, modtime.UnixNano())
414 if resp.NextMarker == "" {
417 params.Marker = resp.NextMarker
421 // call v.container.ListBlobs, retrying if needed.
422 func (v *azureBlobVolume) listBlobs(page int, params storage.ListBlobsParameters) (resp storage.BlobListResponse, err error) {
423 for i := 0; i < v.ListBlobsMaxAttempts; i++ {
424 resp, err = v.container.ListBlobs(params)
425 err = v.translateError(err)
426 if err == errVolumeUnavailable {
427 v.logger.Printf("ListBlobs: will retry page %d in %s after error: %s", page, v.ListBlobsRetryDelay, err)
428 time.Sleep(time.Duration(v.ListBlobsRetryDelay))
437 // Trash a Keep block.
438 func (v *azureBlobVolume) BlockTrash(loc string) error {
439 // Ideally we would use If-Unmodified-Since, but that
440 // particular condition seems to be ignored by Azure. Instead,
441 // we get the Etag before checking Mtime, and use If-Match to
442 // ensure we don't delete data if Put() or Touch() happens
443 // between our calls to Mtime() and DeleteBlob().
444 props, err := v.container.GetBlobProperties(loc)
448 if t, err := v.Mtime(loc); err != nil {
450 } else if time.Since(t) < v.cluster.Collections.BlobSigningTTL.Duration() {
454 // If BlobTrashLifetime == 0, just delete it
455 if v.cluster.Collections.BlobTrashLifetime == 0 {
456 return v.container.DeleteBlob(loc, &storage.DeleteBlobOptions{
461 // Otherwise, mark as trash
462 return v.container.SetBlobMetadata(loc, storage.BlobMetadata{
463 "expires_at": fmt.Sprintf("%d", time.Now().Add(v.cluster.Collections.BlobTrashLifetime.Duration()).Unix()),
464 }, &storage.SetBlobMetadataOptions{
469 // BlockUntrash deletes the expires_at metadata attribute for the
470 // specified block blob.
471 func (v *azureBlobVolume) BlockUntrash(hash string) error {
472 // if expires_at does not exist, return NotFoundError
473 metadata, err := v.container.GetBlobMetadata(hash)
475 return v.translateError(err)
477 if metadata["expires_at"] == "" {
478 return os.ErrNotExist
481 // reset expires_at metadata attribute
482 metadata["expires_at"] = ""
483 err = v.container.SetBlobMetadata(hash, metadata, nil)
484 return v.translateError(err)
487 // If possible, translate an Azure SDK error to a recognizable error
488 // like os.ErrNotExist.
489 func (v *azureBlobVolume) translateError(err error) error {
493 case strings.Contains(err.Error(), "StatusCode=503"):
494 // "storage: service returned error: StatusCode=503, ErrorCode=ServerBusy, ErrorMessage=The server is busy" (See #14804)
495 return errVolumeUnavailable
496 case strings.Contains(err.Error(), "Not Found"):
497 // "storage: service returned without a response body (404 Not Found)"
498 return os.ErrNotExist
499 case strings.Contains(err.Error(), "ErrorCode=BlobNotFound"):
500 // "storage: service returned error: StatusCode=404, ErrorCode=BlobNotFound, ErrorMessage=The specified blob does not exist.\n..."
501 return os.ErrNotExist
507 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
509 func (v *azureBlobVolume) isKeepBlock(s string) bool {
510 return keepBlockRegexp.MatchString(s)
513 // EmptyTrash looks for trashed blocks that exceeded BlobTrashLifetime
514 // and deletes them from the volume.
515 func (v *azureBlobVolume) EmptyTrash() {
516 var bytesDeleted, bytesInTrash int64
517 var blocksDeleted, blocksInTrash int64
519 doBlob := func(b storage.Blob) {
520 // Check whether the block is flagged as trash
521 if b.Metadata["expires_at"] == "" {
525 atomic.AddInt64(&blocksInTrash, 1)
526 atomic.AddInt64(&bytesInTrash, b.Properties.ContentLength)
528 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
530 v.logger.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
534 if expiresAt > time.Now().Unix() {
538 err = v.container.DeleteBlob(b.Name, &storage.DeleteBlobOptions{
539 IfMatch: b.Properties.Etag,
542 v.logger.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
545 atomic.AddInt64(&blocksDeleted, 1)
546 atomic.AddInt64(&bytesDeleted, b.Properties.ContentLength)
549 var wg sync.WaitGroup
550 todo := make(chan storage.Blob, v.cluster.Collections.BlobDeleteConcurrency)
551 for i := 0; i < v.cluster.Collections.BlobDeleteConcurrency; i++ {
555 for b := range todo {
561 params := storage.ListBlobsParameters{Include: &storage.IncludeBlobDataset{Metadata: true}}
562 for page := 1; ; page++ {
563 resp, err := v.listBlobs(page, params)
565 v.logger.Printf("EmptyTrash: ListBlobs: %v", err)
568 for _, b := range resp.Blobs {
571 if resp.NextMarker == "" {
574 params.Marker = resp.NextMarker
579 v.logger.Printf("EmptyTrash stats for %v: Deleted %v bytes in %v blocks. Remaining in trash: %v bytes in %v blocks.", v.DeviceID(), bytesDeleted, blocksDeleted, bytesInTrash-bytesDeleted, blocksInTrash-blocksDeleted)
582 // InternalStats returns bucket I/O and API call counters.
583 func (v *azureBlobVolume) InternalStats() interface{} {
584 return &v.container.stats
587 type azureBlobStats struct {
592 GetMetadataOps uint64
593 GetPropertiesOps uint64
595 SetMetadataOps uint64
600 func (s *azureBlobStats) TickErr(err error) {
604 errType := fmt.Sprintf("%T", err)
605 if err, ok := err.(storage.AzureStorageServiceError); ok {
606 errType = errType + fmt.Sprintf(" %d (%s)", err.StatusCode, err.Code)
608 s.statsTicker.TickErr(err, errType)
611 // azureContainer wraps storage.Container in order to count I/O and
613 type azureContainer struct {
614 ctr *storage.Container
618 func (c *azureContainer) Exists() (bool, error) {
619 c.stats.TickOps("exists")
620 c.stats.Tick(&c.stats.Ops)
621 ok, err := c.ctr.Exists()
626 func (c *azureContainer) GetBlobMetadata(bname string) (storage.BlobMetadata, error) {
627 c.stats.TickOps("get_metadata")
628 c.stats.Tick(&c.stats.Ops, &c.stats.GetMetadataOps)
629 b := c.ctr.GetBlobReference(bname)
630 err := b.GetMetadata(nil)
632 return b.Metadata, err
635 func (c *azureContainer) GetBlobProperties(bname string) (*storage.BlobProperties, error) {
636 c.stats.TickOps("get_properties")
637 c.stats.Tick(&c.stats.Ops, &c.stats.GetPropertiesOps)
638 b := c.ctr.GetBlobReference(bname)
639 err := b.GetProperties(nil)
641 return &b.Properties, err
644 func (c *azureContainer) GetBlob(bname string) (io.ReadCloser, error) {
645 c.stats.TickOps("get")
646 c.stats.Tick(&c.stats.Ops, &c.stats.GetOps)
647 b := c.ctr.GetBlobReference(bname)
648 rdr, err := b.Get(nil)
650 return newCountingReader(rdr, c.stats.TickInBytes), err
653 func (c *azureContainer) GetBlobRange(bname string, start, end int, opts *storage.GetBlobOptions) (io.ReadCloser, error) {
654 c.stats.TickOps("get_range")
655 c.stats.Tick(&c.stats.Ops, &c.stats.GetRangeOps)
656 b := c.ctr.GetBlobReference(bname)
657 rdr, err := b.GetRange(&storage.GetBlobRangeOptions{
658 Range: &storage.BlobRange{
659 Start: uint64(start),
662 GetBlobOptions: opts,
665 return newCountingReader(rdr, c.stats.TickInBytes), err
668 // If we give it an io.Reader that doesn't also have a Len() int
669 // method, the Azure SDK determines data size by copying the data into
670 // a new buffer, which is not a good use of memory.
671 type readerWithAzureLen struct {
676 // Len satisfies the private lener interface in azure-sdk-for-go.
677 func (r *readerWithAzureLen) Len() int {
681 func (c *azureContainer) CreateBlockBlobFromReader(bname string, size int, rdr io.Reader, opts *storage.PutBlobOptions) error {
682 c.stats.TickOps("create")
683 c.stats.Tick(&c.stats.Ops, &c.stats.CreateOps)
685 rdr = &readerWithAzureLen{
686 Reader: newCountingReader(rdr, c.stats.TickOutBytes),
690 b := c.ctr.GetBlobReference(bname)
691 err := b.CreateBlockBlobFromReader(rdr, opts)
696 func (c *azureContainer) SetBlobMetadata(bname string, m storage.BlobMetadata, opts *storage.SetBlobMetadataOptions) error {
697 c.stats.TickOps("set_metadata")
698 c.stats.Tick(&c.stats.Ops, &c.stats.SetMetadataOps)
699 b := c.ctr.GetBlobReference(bname)
701 err := b.SetMetadata(opts)
706 func (c *azureContainer) ListBlobs(params storage.ListBlobsParameters) (storage.BlobListResponse, error) {
707 c.stats.TickOps("list")
708 c.stats.Tick(&c.stats.Ops, &c.stats.ListOps)
709 resp, err := c.ctr.ListBlobs(params)
714 func (c *azureContainer) DeleteBlob(bname string, opts *storage.DeleteBlobOptions) error {
715 c.stats.TickOps("delete")
716 c.stats.Tick(&c.stats.Ops, &c.stats.DelOps)
717 b := c.ctr.GetBlobReference(bname)
718 err := b.Delete(opts)