1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.curoverse.com/arvados.git/sdk/go/arvados"
24 "github.com/curoverse/azure-sdk-for-go/storage"
27 const azureDefaultRequestTimeout = arvados.Duration(10 * time.Minute)
31 azureStorageAccountName string
32 azureStorageAccountKeyFile string
33 azureStorageReplication int
34 azureWriteRaceInterval = 15 * time.Second
35 azureWriteRacePollTime = time.Second
38 func readKeyFromFile(file string) (string, error) {
39 buf, err := ioutil.ReadFile(file)
41 return "", errors.New("reading key from " + file + ": " + err.Error())
43 accountKey := strings.TrimSpace(string(buf))
45 return "", errors.New("empty account key in " + file)
47 return accountKey, nil
50 type azureVolumeAdder struct {
54 // String implements flag.Value
55 func (s *azureVolumeAdder) String() string {
59 func (s *azureVolumeAdder) Set(containerName string) error {
60 s.Config.Volumes = append(s.Config.Volumes, &AzureBlobVolume{
61 ContainerName: containerName,
62 StorageAccountName: azureStorageAccountName,
63 StorageAccountKeyFile: azureStorageAccountKeyFile,
64 AzureReplication: azureStorageReplication,
65 ReadOnly: deprecated.flagReadonly,
71 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &AzureBlobVolume{} })
73 flag.Var(&azureVolumeAdder{theConfig},
74 "azure-storage-container-volume",
75 "Use the given container as a storage volume. Can be given multiple times.")
77 &azureStorageAccountName,
78 "azure-storage-account-name",
80 "Azure storage account name used for subsequent --azure-storage-container-volume arguments.")
82 &azureStorageAccountKeyFile,
83 "azure-storage-account-key-file",
85 "`File` containing the account key used for subsequent --azure-storage-container-volume arguments.")
87 &azureStorageReplication,
88 "azure-storage-replication",
90 "Replication level to report to clients when data is stored in an Azure container.")
93 "azure-max-get-bytes",
95 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))
98 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
100 type AzureBlobVolume struct {
101 StorageAccountName string
102 StorageAccountKeyFile string
103 StorageBaseURL string // "" means default, "core.windows.net"
107 RequestTimeout arvados.Duration
109 azClient storage.Client
110 bsClient *azureBlobClient
113 // Examples implements VolumeWithExamples.
114 func (*AzureBlobVolume) Examples() []Volume {
117 StorageAccountName: "example-account-name",
118 StorageAccountKeyFile: "/etc/azure_storage_account_key.txt",
119 ContainerName: "example-container-name",
121 RequestTimeout: azureDefaultRequestTimeout,
124 StorageAccountName: "cn-account-name",
125 StorageAccountKeyFile: "/etc/azure_cn_storage_account_key.txt",
126 StorageBaseURL: "core.chinacloudapi.cn",
127 ContainerName: "cn-container-name",
129 RequestTimeout: azureDefaultRequestTimeout,
134 // Type implements Volume.
135 func (v *AzureBlobVolume) Type() string {
139 // Start implements Volume.
140 func (v *AzureBlobVolume) Start() error {
141 if v.ContainerName == "" {
142 return errors.New("no container name given")
144 if v.StorageAccountName == "" || v.StorageAccountKeyFile == "" {
145 return errors.New("StorageAccountName and StorageAccountKeyFile must be given")
147 accountKey, err := readKeyFromFile(v.StorageAccountKeyFile)
151 if v.StorageBaseURL == "" {
152 v.StorageBaseURL = storage.DefaultBaseURL
154 v.azClient, err = storage.NewClient(v.StorageAccountName, accountKey, v.StorageBaseURL, storage.DefaultAPIVersion, true)
156 return fmt.Errorf("creating Azure storage client: %s", err)
159 if v.RequestTimeout == 0 {
160 v.RequestTimeout = azureDefaultRequestTimeout
162 v.azClient.HTTPClient = &http.Client{
163 Timeout: time.Duration(v.RequestTimeout),
165 bs := v.azClient.GetBlobService()
166 v.bsClient = &azureBlobClient{
170 ok, err := v.bsClient.ContainerExists(v.ContainerName)
175 return fmt.Errorf("Azure container %q does not exist", v.ContainerName)
180 // DeviceID returns a globally unique ID for the storage container.
181 func (v *AzureBlobVolume) DeviceID() string {
182 return "azure://" + v.StorageBaseURL + "/" + v.StorageAccountName + "/" + v.ContainerName
185 // Return true if expires_at metadata attribute is found on the block
186 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
187 metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
189 return false, metadata, v.translateError(err)
191 if metadata["expires_at"] != "" {
192 return true, metadata, nil
194 return false, metadata, nil
197 // Get reads a Keep block that has been stored as a block blob in the
200 // If the block is younger than azureWriteRaceInterval and is
201 // unexpectedly empty, assume a PutBlob operation is in progress, and
202 // wait for it to finish writing.
203 func (v *AzureBlobVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
204 trashed, _, err := v.checkTrashed(loc)
209 return 0, os.ErrNotExist
211 var deadline time.Time
212 haveDeadline := false
213 size, err := v.get(ctx, loc, buf)
214 for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
215 // Seeing a brand new empty block probably means we're
216 // in a race with CreateBlob, which under the hood
217 // (apparently) does "CreateEmpty" and "CommitData"
218 // with no additional transaction locking.
220 t, err := v.Mtime(loc)
222 log.Print("Got empty block (possible race) but Mtime failed: ", err)
225 deadline = t.Add(azureWriteRaceInterval)
226 if time.Now().After(deadline) {
229 log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
231 } else if time.Now().After(deadline) {
237 case <-time.After(azureWriteRacePollTime):
239 size, err = v.get(ctx, loc, buf)
242 log.Printf("Race ended with size==%d", size)
247 func (v *AzureBlobVolume) get(ctx context.Context, loc string, buf []byte) (int, error) {
248 ctx, cancel := context.WithCancel(ctx)
250 expectSize := len(buf)
251 if azureMaxGetBytes < BlockSize {
252 // Unfortunately the handler doesn't tell us how long the blob
253 // is expected to be, so we have to ask Azure.
254 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
256 return 0, v.translateError(err)
258 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
259 return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
261 expectSize = int(props.ContentLength)
268 // We'll update this actualSize if/when we get the last piece.
270 pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
271 errors := make(chan error, pieces)
272 var wg sync.WaitGroup
274 for p := 0; p < pieces; p++ {
275 // Each goroutine retrieves one piece. If we hit an
276 // error, it is sent to the errors chan so get() can
277 // return it -- but only if the error happens before
278 // ctx is done. This way, if ctx is done before we hit
279 // any other error (e.g., requesting client has hung
280 // up), we return the original ctx.Err() instead of
281 // the secondary errors from the transfers that got
282 // interrupted as a result.
285 startPos := p * azureMaxGetBytes
286 endPos := startPos + azureMaxGetBytes
287 if endPos > expectSize {
290 var rdr io.ReadCloser
292 gotRdr := make(chan struct{})
295 if startPos == 0 && endPos == expectSize {
296 rdr, err = v.bsClient.GetBlob(v.ContainerName, loc)
298 rdr, err = v.bsClient.GetBlobRange(v.ContainerName, loc, fmt.Sprintf("%d-%d", startPos, endPos-1), nil)
318 // Close the reader when the client
319 // hangs up or another piece fails
320 // (possibly interrupting ReadFull())
321 // or when all pieces succeed and
326 n, err := io.ReadFull(rdr, buf[startPos:endPos])
327 if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
328 // If we don't know the actual size,
329 // and just tried reading 64 MiB, it's
330 // normal to encounter EOF.
331 } else if err != nil {
332 if ctx.Err() == nil {
339 actualSize = startPos + n
346 return 0, v.translateError(<-errors)
348 if ctx.Err() != nil {
351 return actualSize, nil
354 // Compare the given data with existing stored data.
355 func (v *AzureBlobVolume) Compare(ctx context.Context, loc string, expect []byte) error {
356 trashed, _, err := v.checkTrashed(loc)
361 return os.ErrNotExist
363 var rdr io.ReadCloser
364 gotRdr := make(chan struct{})
367 rdr, err = v.bsClient.GetBlob(v.ContainerName, loc)
381 return v.translateError(err)
384 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
387 // Put stores a Keep block as a block blob in the container.
388 func (v *AzureBlobVolume) Put(ctx context.Context, loc string, block []byte) error {
390 return MethodDisabledError
392 // Send the block data through a pipe, so that (if we need to)
393 // we can close the pipe early and abandon our
394 // CreateBlockBlobFromReader() goroutine, without worrying
395 // about CreateBlockBlobFromReader() accessing our block
396 // buffer after we release it.
397 bufr, bufw := io.Pipe()
399 io.Copy(bufw, bytes.NewReader(block))
402 errChan := make(chan error)
404 var body io.Reader = bufr
406 // We must send a "Content-Length: 0" header,
407 // but the http client interprets
408 // ContentLength==0 as "unknown" unless it can
409 // confirm by introspection that Body will
414 errChan <- v.bsClient.CreateBlockBlobFromReader(v.ContainerName, loc, uint64(len(block)), body, nil)
418 theConfig.debugLogf("%s: taking CreateBlockBlobFromReader's input away: %s", v, ctx.Err())
419 // Our pipe might be stuck in Write(), waiting for
420 // io.Copy() to read. If so, un-stick it. This means
421 // CreateBlockBlobFromReader will get corrupt data,
422 // but that's OK: the size won't match, so the write
424 go io.Copy(ioutil.Discard, bufr)
425 // CloseWithError() will return once pending I/O is done.
426 bufw.CloseWithError(ctx.Err())
427 theConfig.debugLogf("%s: abandoning CreateBlockBlobFromReader goroutine", v)
429 case err := <-errChan:
434 // Touch updates the last-modified property of a block blob.
435 func (v *AzureBlobVolume) Touch(loc string) error {
437 return MethodDisabledError
439 trashed, metadata, err := v.checkTrashed(loc)
444 return os.ErrNotExist
447 metadata["touch"] = fmt.Sprintf("%d", time.Now())
448 return v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
451 // Mtime returns the last-modified property of a block blob.
452 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
453 trashed, _, err := v.checkTrashed(loc)
455 return time.Time{}, err
458 return time.Time{}, os.ErrNotExist
461 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
463 return time.Time{}, err
465 return time.Parse(time.RFC1123, props.LastModified)
468 // IndexTo writes a list of Keep blocks that are stored in the
470 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
471 params := storage.ListBlobsParameters{
476 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
480 for _, b := range resp.Blobs {
481 t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
485 if !v.isKeepBlock(b.Name) {
488 if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
489 // A new zero-length blob is probably
490 // just a new non-empty blob that
491 // hasn't committed its data yet (see
492 // Get()), and in any case has no
496 if b.Metadata["expires_at"] != "" {
497 // Trashed blob; exclude it from response
500 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.UnixNano())
502 if resp.NextMarker == "" {
505 params.Marker = resp.NextMarker
509 // Trash a Keep block.
510 func (v *AzureBlobVolume) Trash(loc string) error {
512 return MethodDisabledError
515 // Ideally we would use If-Unmodified-Since, but that
516 // particular condition seems to be ignored by Azure. Instead,
517 // we get the Etag before checking Mtime, and use If-Match to
518 // ensure we don't delete data if Put() or Touch() happens
519 // between our calls to Mtime() and DeleteBlob().
520 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
524 if t, err := v.Mtime(loc); err != nil {
526 } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
530 // If TrashLifetime == 0, just delete it
531 if theConfig.TrashLifetime == 0 {
532 return v.bsClient.DeleteBlob(v.ContainerName, loc, map[string]string{
533 "If-Match": props.Etag,
537 // Otherwise, mark as trash
538 return v.bsClient.SetBlobMetadata(v.ContainerName, loc, map[string]string{
539 "expires_at": fmt.Sprintf("%d", time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()),
540 }, map[string]string{
541 "If-Match": props.Etag,
545 // Untrash a Keep block.
546 // Delete the expires_at metadata attribute
547 func (v *AzureBlobVolume) Untrash(loc string) error {
548 // if expires_at does not exist, return NotFoundError
549 metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
551 return v.translateError(err)
553 if metadata["expires_at"] == "" {
554 return os.ErrNotExist
557 // reset expires_at metadata attribute
558 metadata["expires_at"] = ""
559 err = v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
560 return v.translateError(err)
563 // Status returns a VolumeStatus struct with placeholder data.
564 func (v *AzureBlobVolume) Status() *VolumeStatus {
565 return &VolumeStatus{
567 BytesFree: BlockSize * 1000,
572 // String returns a volume label, including the container name.
573 func (v *AzureBlobVolume) String() string {
574 return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
577 // Writable returns true, unless the -readonly flag was on when the
579 func (v *AzureBlobVolume) Writable() bool {
583 // Replication returns the replication level of the container, as
584 // specified by the -azure-storage-replication argument.
585 func (v *AzureBlobVolume) Replication() int {
586 return v.AzureReplication
589 // If possible, translate an Azure SDK error to a recognizable error
590 // like os.ErrNotExist.
591 func (v *AzureBlobVolume) translateError(err error) error {
595 case strings.Contains(err.Error(), "Not Found"):
596 // "storage: service returned without a response body (404 Not Found)"
597 return os.ErrNotExist
603 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
605 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
606 return keepBlockRegexp.MatchString(s)
609 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
610 // and deletes them from the volume.
611 func (v *AzureBlobVolume) EmptyTrash() {
612 var bytesDeleted, bytesInTrash int64
613 var blocksDeleted, blocksInTrash int
614 params := storage.ListBlobsParameters{Include: "metadata"}
617 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
619 log.Printf("EmptyTrash: ListBlobs: %v", err)
622 for _, b := range resp.Blobs {
623 // Check if the block is expired
624 if b.Metadata["expires_at"] == "" {
629 bytesInTrash += b.Properties.ContentLength
631 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
633 log.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
637 if expiresAt > time.Now().Unix() {
641 err = v.bsClient.DeleteBlob(v.ContainerName, b.Name, map[string]string{
642 "If-Match": b.Properties.Etag,
645 log.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
649 bytesDeleted += b.Properties.ContentLength
651 if resp.NextMarker == "" {
654 params.Marker = resp.NextMarker
657 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)
660 // InternalStats returns bucket I/O and API call counters.
661 func (v *AzureBlobVolume) InternalStats() interface{} {
662 return &v.bsClient.stats
665 type azureBlobStats struct {
670 GetMetadataOps uint64
671 GetPropertiesOps uint64
673 SetMetadataOps uint64
678 func (s *azureBlobStats) TickErr(err error) {
682 errType := fmt.Sprintf("%T", err)
683 if err, ok := err.(storage.AzureStorageServiceError); ok {
684 errType = errType + fmt.Sprintf(" %d (%s)", err.StatusCode, err.Code)
686 log.Printf("errType %T, err %s", err, err)
687 s.statsTicker.TickErr(err, errType)
690 // azureBlobClient wraps storage.BlobStorageClient in order to count
691 // I/O and API usage stats.
692 type azureBlobClient struct {
693 client *storage.BlobStorageClient
697 func (c *azureBlobClient) ContainerExists(cname string) (bool, error) {
698 c.stats.Tick(&c.stats.Ops)
699 ok, err := c.client.ContainerExists(cname)
704 func (c *azureBlobClient) GetBlobMetadata(cname, bname string) (map[string]string, error) {
705 c.stats.Tick(&c.stats.Ops, &c.stats.GetMetadataOps)
706 m, err := c.client.GetBlobMetadata(cname, bname)
711 func (c *azureBlobClient) GetBlobProperties(cname, bname string) (*storage.BlobProperties, error) {
712 c.stats.Tick(&c.stats.Ops, &c.stats.GetPropertiesOps)
713 p, err := c.client.GetBlobProperties(cname, bname)
718 func (c *azureBlobClient) GetBlob(cname, bname string) (io.ReadCloser, error) {
719 c.stats.Tick(&c.stats.Ops, &c.stats.GetOps)
720 rdr, err := c.client.GetBlob(cname, bname)
722 return NewCountingReader(rdr, c.stats.TickInBytes), err
725 func (c *azureBlobClient) GetBlobRange(cname, bname, byterange string, hdrs map[string]string) (io.ReadCloser, error) {
726 c.stats.Tick(&c.stats.Ops, &c.stats.GetRangeOps)
727 rdr, err := c.client.GetBlobRange(cname, bname, byterange, hdrs)
729 return NewCountingReader(rdr, c.stats.TickInBytes), err
732 func (c *azureBlobClient) CreateBlockBlobFromReader(cname, bname string, size uint64, rdr io.Reader, hdrs map[string]string) error {
733 c.stats.Tick(&c.stats.Ops, &c.stats.CreateOps)
735 rdr = NewCountingReader(rdr, c.stats.TickOutBytes)
737 err := c.client.CreateBlockBlobFromReader(cname, bname, size, rdr, hdrs)
742 func (c *azureBlobClient) SetBlobMetadata(cname, bname string, m, hdrs map[string]string) error {
743 c.stats.Tick(&c.stats.Ops, &c.stats.SetMetadataOps)
744 err := c.client.SetBlobMetadata(cname, bname, m, hdrs)
749 func (c *azureBlobClient) ListBlobs(cname string, params storage.ListBlobsParameters) (storage.BlobListResponse, error) {
750 c.stats.Tick(&c.stats.Ops, &c.stats.ListOps)
751 resp, err := c.client.ListBlobs(cname, params)
756 func (c *azureBlobClient) DeleteBlob(cname, bname string, hdrs map[string]string) error {
757 c.stats.Tick(&c.stats.Ops, &c.stats.DelOps)
758 err := c.client.DeleteBlob(cname, bname, hdrs)