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/Azure/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
108 StorageClasses []string
110 azClient storage.Client
111 container *azureContainer
114 // singleSender is a single-attempt storage.Sender.
115 type singleSender struct{}
117 // Send performs req exactly once.
118 func (*singleSender) Send(c *storage.Client, req *http.Request) (resp *http.Response, err error) {
119 return c.HTTPClient.Do(req)
122 // Examples implements VolumeWithExamples.
123 func (*AzureBlobVolume) Examples() []Volume {
126 StorageAccountName: "example-account-name",
127 StorageAccountKeyFile: "/etc/azure_storage_account_key.txt",
128 ContainerName: "example-container-name",
130 RequestTimeout: azureDefaultRequestTimeout,
133 StorageAccountName: "cn-account-name",
134 StorageAccountKeyFile: "/etc/azure_cn_storage_account_key.txt",
135 StorageBaseURL: "core.chinacloudapi.cn",
136 ContainerName: "cn-container-name",
138 RequestTimeout: azureDefaultRequestTimeout,
143 // Type implements Volume.
144 func (v *AzureBlobVolume) Type() string {
148 // Start implements Volume.
149 func (v *AzureBlobVolume) Start() error {
150 if v.ContainerName == "" {
151 return errors.New("no container name given")
153 if v.StorageAccountName == "" || v.StorageAccountKeyFile == "" {
154 return errors.New("StorageAccountName and StorageAccountKeyFile must be given")
156 accountKey, err := readKeyFromFile(v.StorageAccountKeyFile)
160 if v.StorageBaseURL == "" {
161 v.StorageBaseURL = storage.DefaultBaseURL
163 v.azClient, err = storage.NewClient(v.StorageAccountName, accountKey, v.StorageBaseURL, storage.DefaultAPIVersion, true)
165 return fmt.Errorf("creating Azure storage client: %s", err)
167 v.azClient.Sender = &singleSender{}
169 if v.RequestTimeout == 0 {
170 v.RequestTimeout = azureDefaultRequestTimeout
172 v.azClient.HTTPClient = &http.Client{
173 Timeout: time.Duration(v.RequestTimeout),
175 bs := v.azClient.GetBlobService()
176 v.container = &azureContainer{
177 ctr: bs.GetContainerReference(v.ContainerName),
180 if ok, err := v.container.Exists(); err != nil {
183 return fmt.Errorf("Azure container %q does not exist", v.ContainerName)
188 // DeviceID returns a globally unique ID for the storage container.
189 func (v *AzureBlobVolume) DeviceID() string {
190 return "azure://" + v.StorageBaseURL + "/" + v.StorageAccountName + "/" + v.ContainerName
193 // Return true if expires_at metadata attribute is found on the block
194 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
195 metadata, err := v.container.GetBlobMetadata(loc)
197 return false, metadata, v.translateError(err)
199 if metadata["expires_at"] != "" {
200 return true, metadata, nil
202 return false, metadata, nil
205 // Get reads a Keep block that has been stored as a block blob in the
208 // If the block is younger than azureWriteRaceInterval and is
209 // unexpectedly empty, assume a PutBlob operation is in progress, and
210 // wait for it to finish writing.
211 func (v *AzureBlobVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
212 trashed, _, err := v.checkTrashed(loc)
217 return 0, os.ErrNotExist
219 var deadline time.Time
220 haveDeadline := false
221 size, err := v.get(ctx, loc, buf)
222 for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
223 // Seeing a brand new empty block probably means we're
224 // in a race with CreateBlob, which under the hood
225 // (apparently) does "CreateEmpty" and "CommitData"
226 // with no additional transaction locking.
228 t, err := v.Mtime(loc)
230 log.Print("Got empty block (possible race) but Mtime failed: ", err)
233 deadline = t.Add(azureWriteRaceInterval)
234 if time.Now().After(deadline) {
237 log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
239 } else if time.Now().After(deadline) {
245 case <-time.After(azureWriteRacePollTime):
247 size, err = v.get(ctx, loc, buf)
250 log.Printf("Race ended with size==%d", size)
255 func (v *AzureBlobVolume) get(ctx context.Context, loc string, buf []byte) (int, error) {
256 ctx, cancel := context.WithCancel(ctx)
258 expectSize := len(buf)
259 if azureMaxGetBytes < BlockSize {
260 // Unfortunately the handler doesn't tell us how long the blob
261 // is expected to be, so we have to ask Azure.
262 props, err := v.container.GetBlobProperties(loc)
264 return 0, v.translateError(err)
266 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
267 return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
269 expectSize = int(props.ContentLength)
276 // We'll update this actualSize if/when we get the last piece.
278 pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
279 errors := make(chan error, pieces)
280 var wg sync.WaitGroup
282 for p := 0; p < pieces; p++ {
283 // Each goroutine retrieves one piece. If we hit an
284 // error, it is sent to the errors chan so get() can
285 // return it -- but only if the error happens before
286 // ctx is done. This way, if ctx is done before we hit
287 // any other error (e.g., requesting client has hung
288 // up), we return the original ctx.Err() instead of
289 // the secondary errors from the transfers that got
290 // interrupted as a result.
293 startPos := p * azureMaxGetBytes
294 endPos := startPos + azureMaxGetBytes
295 if endPos > expectSize {
298 var rdr io.ReadCloser
300 gotRdr := make(chan struct{})
303 if startPos == 0 && endPos == expectSize {
304 rdr, err = v.container.GetBlob(loc)
306 rdr, err = v.container.GetBlobRange(loc, startPos, endPos-1, nil)
326 // Close the reader when the client
327 // hangs up or another piece fails
328 // (possibly interrupting ReadFull())
329 // or when all pieces succeed and
334 n, err := io.ReadFull(rdr, buf[startPos:endPos])
335 if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
336 // If we don't know the actual size,
337 // and just tried reading 64 MiB, it's
338 // normal to encounter EOF.
339 } else if err != nil {
340 if ctx.Err() == nil {
347 actualSize = startPos + n
354 return 0, v.translateError(<-errors)
356 if ctx.Err() != nil {
359 return actualSize, nil
362 // Compare the given data with existing stored data.
363 func (v *AzureBlobVolume) Compare(ctx context.Context, loc string, expect []byte) error {
364 trashed, _, err := v.checkTrashed(loc)
369 return os.ErrNotExist
371 var rdr io.ReadCloser
372 gotRdr := make(chan struct{})
375 rdr, err = v.container.GetBlob(loc)
389 return v.translateError(err)
392 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
395 // Put stores a Keep block as a block blob in the container.
396 func (v *AzureBlobVolume) Put(ctx context.Context, loc string, block []byte) error {
398 return MethodDisabledError
400 // Send the block data through a pipe, so that (if we need to)
401 // we can close the pipe early and abandon our
402 // CreateBlockBlobFromReader() goroutine, without worrying
403 // about CreateBlockBlobFromReader() accessing our block
404 // buffer after we release it.
405 bufr, bufw := io.Pipe()
407 io.Copy(bufw, bytes.NewReader(block))
410 errChan := make(chan error)
412 var body io.Reader = bufr
414 // We must send a "Content-Length: 0" header,
415 // but the http client interprets
416 // ContentLength==0 as "unknown" unless it can
417 // confirm by introspection that Body will
422 errChan <- v.container.CreateBlockBlobFromReader(loc, len(block), body, nil)
426 theConfig.debugLogf("%s: taking CreateBlockBlobFromReader's input away: %s", v, ctx.Err())
427 // Our pipe might be stuck in Write(), waiting for
428 // io.Copy() to read. If so, un-stick it. This means
429 // CreateBlockBlobFromReader will get corrupt data,
430 // but that's OK: the size won't match, so the write
432 go io.Copy(ioutil.Discard, bufr)
433 // CloseWithError() will return once pending I/O is done.
434 bufw.CloseWithError(ctx.Err())
435 theConfig.debugLogf("%s: abandoning CreateBlockBlobFromReader goroutine", v)
437 case err := <-errChan:
442 // Touch updates the last-modified property of a block blob.
443 func (v *AzureBlobVolume) Touch(loc string) error {
445 return MethodDisabledError
447 trashed, metadata, err := v.checkTrashed(loc)
452 return os.ErrNotExist
455 metadata["touch"] = fmt.Sprintf("%d", time.Now())
456 return v.container.SetBlobMetadata(loc, metadata, nil)
459 // Mtime returns the last-modified property of a block blob.
460 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
461 trashed, _, err := v.checkTrashed(loc)
463 return time.Time{}, err
466 return time.Time{}, os.ErrNotExist
469 props, err := v.container.GetBlobProperties(loc)
471 return time.Time{}, err
473 return time.Time(props.LastModified), nil
476 // IndexTo writes a list of Keep blocks that are stored in the
478 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
479 params := storage.ListBlobsParameters{
481 Include: &storage.IncludeBlobDataset{Metadata: true},
484 resp, err := v.container.ListBlobs(params)
488 for _, b := range resp.Blobs {
489 if !v.isKeepBlock(b.Name) {
492 modtime := time.Time(b.Properties.LastModified)
493 if b.Properties.ContentLength == 0 && modtime.Add(azureWriteRaceInterval).After(time.Now()) {
494 // A new zero-length blob is probably
495 // just a new non-empty blob that
496 // hasn't committed its data yet (see
497 // Get()), and in any case has no
501 if b.Metadata["expires_at"] != "" {
502 // Trashed blob; exclude it from response
505 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, modtime.UnixNano())
507 if resp.NextMarker == "" {
510 params.Marker = resp.NextMarker
514 // Trash a Keep block.
515 func (v *AzureBlobVolume) Trash(loc string) error {
517 return MethodDisabledError
520 // Ideally we would use If-Unmodified-Since, but that
521 // particular condition seems to be ignored by Azure. Instead,
522 // we get the Etag before checking Mtime, and use If-Match to
523 // ensure we don't delete data if Put() or Touch() happens
524 // between our calls to Mtime() and DeleteBlob().
525 props, err := v.container.GetBlobProperties(loc)
529 if t, err := v.Mtime(loc); err != nil {
531 } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
535 // If TrashLifetime == 0, just delete it
536 if theConfig.TrashLifetime == 0 {
537 return v.container.DeleteBlob(loc, &storage.DeleteBlobOptions{
542 // Otherwise, mark as trash
543 return v.container.SetBlobMetadata(loc, storage.BlobMetadata{
544 "expires_at": fmt.Sprintf("%d", time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()),
545 }, &storage.SetBlobMetadataOptions{
550 // Untrash a Keep block.
551 // Delete the expires_at metadata attribute
552 func (v *AzureBlobVolume) Untrash(loc string) error {
553 // if expires_at does not exist, return NotFoundError
554 metadata, err := v.container.GetBlobMetadata(loc)
556 return v.translateError(err)
558 if metadata["expires_at"] == "" {
559 return os.ErrNotExist
562 // reset expires_at metadata attribute
563 metadata["expires_at"] = ""
564 err = v.container.SetBlobMetadata(loc, metadata, nil)
565 return v.translateError(err)
568 // Status returns a VolumeStatus struct with placeholder data.
569 func (v *AzureBlobVolume) Status() *VolumeStatus {
570 return &VolumeStatus{
572 BytesFree: BlockSize * 1000,
577 // String returns a volume label, including the container name.
578 func (v *AzureBlobVolume) String() string {
579 return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
582 // Writable returns true, unless the -readonly flag was on when the
584 func (v *AzureBlobVolume) Writable() bool {
588 // Replication returns the replication level of the container, as
589 // specified by the -azure-storage-replication argument.
590 func (v *AzureBlobVolume) Replication() int {
591 return v.AzureReplication
594 // GetStorageClasses implements Volume
595 func (v *AzureBlobVolume) GetStorageClasses() []string {
596 return v.StorageClasses
599 // If possible, translate an Azure SDK error to a recognizable error
600 // like os.ErrNotExist.
601 func (v *AzureBlobVolume) translateError(err error) error {
605 case strings.Contains(err.Error(), "Not Found"):
606 // "storage: service returned without a response body (404 Not Found)"
607 return os.ErrNotExist
613 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
615 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
616 return keepBlockRegexp.MatchString(s)
619 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
620 // and deletes them from the volume.
621 func (v *AzureBlobVolume) EmptyTrash() {
622 var bytesDeleted, bytesInTrash int64
623 var blocksDeleted, blocksInTrash int
624 params := storage.ListBlobsParameters{Include: &storage.IncludeBlobDataset{Metadata: true}}
627 resp, err := v.container.ListBlobs(params)
629 log.Printf("EmptyTrash: ListBlobs: %v", err)
632 for _, b := range resp.Blobs {
633 // Check if the block is expired
634 if b.Metadata["expires_at"] == "" {
639 bytesInTrash += b.Properties.ContentLength
641 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
643 log.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
647 if expiresAt > time.Now().Unix() {
651 err = v.container.DeleteBlob(b.Name, &storage.DeleteBlobOptions{
652 IfMatch: b.Properties.Etag,
655 log.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
659 bytesDeleted += b.Properties.ContentLength
661 if resp.NextMarker == "" {
664 params.Marker = resp.NextMarker
667 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)
670 // InternalStats returns bucket I/O and API call counters.
671 func (v *AzureBlobVolume) InternalStats() interface{} {
672 return &v.container.stats
675 type azureBlobStats struct {
680 GetMetadataOps uint64
681 GetPropertiesOps uint64
683 SetMetadataOps uint64
688 func (s *azureBlobStats) TickErr(err error) {
692 errType := fmt.Sprintf("%T", err)
693 if err, ok := err.(storage.AzureStorageServiceError); ok {
694 errType = errType + fmt.Sprintf(" %d (%s)", err.StatusCode, err.Code)
696 log.Printf("errType %T, err %s", err, err)
697 s.statsTicker.TickErr(err, errType)
700 // azureContainer wraps storage.Container in order to count I/O and
702 type azureContainer struct {
703 ctr *storage.Container
707 func (c *azureContainer) Exists() (bool, error) {
708 c.stats.Tick(&c.stats.Ops)
709 ok, err := c.ctr.Exists()
714 func (c *azureContainer) GetBlobMetadata(bname string) (storage.BlobMetadata, error) {
715 c.stats.Tick(&c.stats.Ops, &c.stats.GetMetadataOps)
716 b := c.ctr.GetBlobReference(bname)
717 err := b.GetMetadata(nil)
719 return b.Metadata, err
722 func (c *azureContainer) GetBlobProperties(bname string) (*storage.BlobProperties, error) {
723 c.stats.Tick(&c.stats.Ops, &c.stats.GetPropertiesOps)
724 b := c.ctr.GetBlobReference(bname)
725 err := b.GetProperties(nil)
727 return &b.Properties, err
730 func (c *azureContainer) GetBlob(bname string) (io.ReadCloser, error) {
731 c.stats.Tick(&c.stats.Ops, &c.stats.GetOps)
732 b := c.ctr.GetBlobReference(bname)
733 rdr, err := b.Get(nil)
735 return NewCountingReader(rdr, c.stats.TickInBytes), err
738 func (c *azureContainer) GetBlobRange(bname string, start, end int, opts *storage.GetBlobOptions) (io.ReadCloser, error) {
739 c.stats.Tick(&c.stats.Ops, &c.stats.GetRangeOps)
740 b := c.ctr.GetBlobReference(bname)
741 rdr, err := b.GetRange(&storage.GetBlobRangeOptions{
742 Range: &storage.BlobRange{
743 Start: uint64(start),
746 GetBlobOptions: opts,
749 return NewCountingReader(rdr, c.stats.TickInBytes), err
752 // If we give it an io.Reader that doesn't also have a Len() int
753 // method, the Azure SDK determines data size by copying the data into
754 // a new buffer, which is not a good use of memory.
755 type readerWithAzureLen struct {
760 // Len satisfies the private lener interface in azure-sdk-for-go.
761 func (r *readerWithAzureLen) Len() int {
765 func (c *azureContainer) CreateBlockBlobFromReader(bname string, size int, rdr io.Reader, opts *storage.PutBlobOptions) error {
766 c.stats.Tick(&c.stats.Ops, &c.stats.CreateOps)
768 rdr = &readerWithAzureLen{
769 Reader: NewCountingReader(rdr, c.stats.TickOutBytes),
773 b := c.ctr.GetBlobReference(bname)
774 err := b.CreateBlockBlobFromReader(rdr, opts)
779 func (c *azureContainer) SetBlobMetadata(bname string, m storage.BlobMetadata, opts *storage.SetBlobMetadataOptions) error {
780 c.stats.Tick(&c.stats.Ops, &c.stats.SetMetadataOps)
781 b := c.ctr.GetBlobReference(bname)
783 err := b.SetMetadata(opts)
788 func (c *azureContainer) ListBlobs(params storage.ListBlobsParameters) (storage.BlobListResponse, error) {
789 c.stats.Tick(&c.stats.Ops, &c.stats.ListOps)
790 resp, err := c.ctr.ListBlobs(params)
795 func (c *azureContainer) DeleteBlob(bname string, opts *storage.DeleteBlobOptions) error {
796 c.stats.Tick(&c.stats.Ops, &c.stats.DelOps)
797 b := c.ctr.GetBlobReference(bname)
798 err := b.Delete(opts)