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 log "github.com/Sirupsen/logrus"
25 "github.com/curoverse/azure-sdk-for-go/storage"
28 const azureDefaultRequestTimeout = arvados.Duration(10 * time.Minute)
32 azureStorageAccountName string
33 azureStorageAccountKeyFile string
34 azureStorageReplication int
35 azureWriteRaceInterval = 15 * time.Second
36 azureWriteRacePollTime = time.Second
39 func readKeyFromFile(file string) (string, error) {
40 buf, err := ioutil.ReadFile(file)
42 return "", errors.New("reading key from " + file + ": " + err.Error())
44 accountKey := strings.TrimSpace(string(buf))
46 return "", errors.New("empty account key in " + file)
48 return accountKey, nil
51 type azureVolumeAdder struct {
55 // String implements flag.Value
56 func (s *azureVolumeAdder) String() string {
60 func (s *azureVolumeAdder) Set(containerName string) error {
61 s.Config.Volumes = append(s.Config.Volumes, &AzureBlobVolume{
62 ContainerName: containerName,
63 StorageAccountName: azureStorageAccountName,
64 StorageAccountKeyFile: azureStorageAccountKeyFile,
65 AzureReplication: azureStorageReplication,
66 ReadOnly: deprecated.flagReadonly,
72 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &AzureBlobVolume{} })
74 flag.Var(&azureVolumeAdder{theConfig},
75 "azure-storage-container-volume",
76 "Use the given container as a storage volume. Can be given multiple times.")
78 &azureStorageAccountName,
79 "azure-storage-account-name",
81 "Azure storage account name used for subsequent --azure-storage-container-volume arguments.")
83 &azureStorageAccountKeyFile,
84 "azure-storage-account-key-file",
86 "`File` containing the account key used for subsequent --azure-storage-container-volume arguments.")
88 &azureStorageReplication,
89 "azure-storage-replication",
91 "Replication level to report to clients when data is stored in an Azure container.")
94 "azure-max-get-bytes",
96 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))
99 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
101 type AzureBlobVolume struct {
102 StorageAccountName string
103 StorageAccountKeyFile string
104 StorageBaseURL string // "" means default, "core.windows.net"
108 RequestTimeout arvados.Duration
110 azClient storage.Client
111 bsClient *azureBlobClient
114 // Examples implements VolumeWithExamples.
115 func (*AzureBlobVolume) Examples() []Volume {
118 StorageAccountName: "example-account-name",
119 StorageAccountKeyFile: "/etc/azure_storage_account_key.txt",
120 ContainerName: "example-container-name",
122 RequestTimeout: azureDefaultRequestTimeout,
125 StorageAccountName: "cn-account-name",
126 StorageAccountKeyFile: "/etc/azure_cn_storage_account_key.txt",
127 StorageBaseURL: "core.chinacloudapi.cn",
128 ContainerName: "cn-container-name",
130 RequestTimeout: azureDefaultRequestTimeout,
135 // Type implements Volume.
136 func (v *AzureBlobVolume) Type() string {
140 // Start implements Volume.
141 func (v *AzureBlobVolume) Start() error {
142 if v.ContainerName == "" {
143 return errors.New("no container name given")
145 if v.StorageAccountName == "" || v.StorageAccountKeyFile == "" {
146 return errors.New("StorageAccountName and StorageAccountKeyFile must be given")
148 accountKey, err := readKeyFromFile(v.StorageAccountKeyFile)
152 if v.StorageBaseURL == "" {
153 v.StorageBaseURL = storage.DefaultBaseURL
155 v.azClient, err = storage.NewClient(v.StorageAccountName, accountKey, v.StorageBaseURL, storage.DefaultAPIVersion, true)
157 return fmt.Errorf("creating Azure storage client: %s", err)
160 if v.RequestTimeout == 0 {
161 v.RequestTimeout = azureDefaultRequestTimeout
163 v.azClient.HTTPClient = &http.Client{
164 Timeout: time.Duration(v.RequestTimeout),
166 bs := v.azClient.GetBlobService()
167 v.bsClient = &azureBlobClient{
171 ok, err := v.bsClient.ContainerExists(v.ContainerName)
176 return fmt.Errorf("Azure container %q does not exist", v.ContainerName)
181 // DeviceID returns a globally unique ID for the storage container.
182 func (v *AzureBlobVolume) DeviceID() string {
183 return "azure://" + v.StorageBaseURL + "/" + v.StorageAccountName + "/" + v.ContainerName
186 // Return true if expires_at metadata attribute is found on the block
187 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
188 metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
190 return false, metadata, v.translateError(err)
192 if metadata["expires_at"] != "" {
193 return true, metadata, nil
195 return false, metadata, nil
198 // Get reads a Keep block that has been stored as a block blob in the
201 // If the block is younger than azureWriteRaceInterval and is
202 // unexpectedly empty, assume a PutBlob operation is in progress, and
203 // wait for it to finish writing.
204 func (v *AzureBlobVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
205 trashed, _, err := v.checkTrashed(loc)
210 return 0, os.ErrNotExist
212 var deadline time.Time
213 haveDeadline := false
214 size, err := v.get(ctx, loc, buf)
215 for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
216 // Seeing a brand new empty block probably means we're
217 // in a race with CreateBlob, which under the hood
218 // (apparently) does "CreateEmpty" and "CommitData"
219 // with no additional transaction locking.
221 t, err := v.Mtime(loc)
223 log.Print("Got empty block (possible race) but Mtime failed: ", err)
226 deadline = t.Add(azureWriteRaceInterval)
227 if time.Now().After(deadline) {
230 log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
232 } else if time.Now().After(deadline) {
238 case <-time.After(azureWriteRacePollTime):
240 size, err = v.get(ctx, loc, buf)
243 log.Printf("Race ended with size==%d", size)
248 func (v *AzureBlobVolume) get(ctx context.Context, loc string, buf []byte) (int, error) {
249 ctx, cancel := context.WithCancel(ctx)
251 expectSize := len(buf)
252 if azureMaxGetBytes < BlockSize {
253 // Unfortunately the handler doesn't tell us how long the blob
254 // is expected to be, so we have to ask Azure.
255 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
257 return 0, v.translateError(err)
259 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
260 return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
262 expectSize = int(props.ContentLength)
269 // We'll update this actualSize if/when we get the last piece.
271 pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
272 errors := make(chan error, pieces)
273 var wg sync.WaitGroup
275 for p := 0; p < pieces; p++ {
276 // Each goroutine retrieves one piece. If we hit an
277 // error, it is sent to the errors chan so get() can
278 // return it -- but only if the error happens before
279 // ctx is done. This way, if ctx is done before we hit
280 // any other error (e.g., requesting client has hung
281 // up), we return the original ctx.Err() instead of
282 // the secondary errors from the transfers that got
283 // interrupted as a result.
286 startPos := p * azureMaxGetBytes
287 endPos := startPos + azureMaxGetBytes
288 if endPos > expectSize {
291 var rdr io.ReadCloser
293 gotRdr := make(chan struct{})
296 if startPos == 0 && endPos == expectSize {
297 rdr, err = v.bsClient.GetBlob(v.ContainerName, loc)
299 rdr, err = v.bsClient.GetBlobRange(v.ContainerName, loc, fmt.Sprintf("%d-%d", startPos, endPos-1), nil)
319 // Close the reader when the client
320 // hangs up or another piece fails
321 // (possibly interrupting ReadFull())
322 // or when all pieces succeed and
327 n, err := io.ReadFull(rdr, buf[startPos:endPos])
328 if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
329 // If we don't know the actual size,
330 // and just tried reading 64 MiB, it's
331 // normal to encounter EOF.
332 } else if err != nil {
333 if ctx.Err() == nil {
340 actualSize = startPos + n
347 return 0, v.translateError(<-errors)
349 if ctx.Err() != nil {
352 return actualSize, nil
355 // Compare the given data with existing stored data.
356 func (v *AzureBlobVolume) Compare(ctx context.Context, loc string, expect []byte) error {
357 trashed, _, err := v.checkTrashed(loc)
362 return os.ErrNotExist
364 var rdr io.ReadCloser
365 gotRdr := make(chan struct{})
368 rdr, err = v.bsClient.GetBlob(v.ContainerName, loc)
382 return v.translateError(err)
385 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
388 // Put stores a Keep block as a block blob in the container.
389 func (v *AzureBlobVolume) Put(ctx context.Context, loc string, block []byte) error {
391 return MethodDisabledError
393 // Send the block data through a pipe, so that (if we need to)
394 // we can close the pipe early and abandon our
395 // CreateBlockBlobFromReader() goroutine, without worrying
396 // about CreateBlockBlobFromReader() accessing our block
397 // buffer after we release it.
398 bufr, bufw := io.Pipe()
400 io.Copy(bufw, bytes.NewReader(block))
403 errChan := make(chan error)
405 errChan <- v.bsClient.CreateBlockBlobFromReader(v.ContainerName, loc, uint64(len(block)), bufr, nil)
409 theConfig.debugLogf("%s: taking CreateBlockBlobFromReader's input away: %s", v, ctx.Err())
410 // Our pipe might be stuck in Write(), waiting for
411 // io.Copy() to read. If so, un-stick it. This means
412 // CreateBlockBlobFromReader will get corrupt data,
413 // but that's OK: the size won't match, so the write
415 go io.Copy(ioutil.Discard, bufr)
416 // CloseWithError() will return once pending I/O is done.
417 bufw.CloseWithError(ctx.Err())
418 theConfig.debugLogf("%s: abandoning CreateBlockBlobFromReader goroutine", v)
420 case err := <-errChan:
425 // Touch updates the last-modified property of a block blob.
426 func (v *AzureBlobVolume) Touch(loc string) error {
428 return MethodDisabledError
430 trashed, metadata, err := v.checkTrashed(loc)
435 return os.ErrNotExist
438 metadata["touch"] = fmt.Sprintf("%d", time.Now())
439 return v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
442 // Mtime returns the last-modified property of a block blob.
443 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
444 trashed, _, err := v.checkTrashed(loc)
446 return time.Time{}, err
449 return time.Time{}, os.ErrNotExist
452 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
454 return time.Time{}, err
456 return time.Parse(time.RFC1123, props.LastModified)
459 // IndexTo writes a list of Keep blocks that are stored in the
461 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
462 params := storage.ListBlobsParameters{
467 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
471 for _, b := range resp.Blobs {
472 t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
476 if !v.isKeepBlock(b.Name) {
479 if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
480 // A new zero-length blob is probably
481 // just a new non-empty blob that
482 // hasn't committed its data yet (see
483 // Get()), and in any case has no
487 if b.Metadata["expires_at"] != "" {
488 // Trashed blob; exclude it from response
491 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.UnixNano())
493 if resp.NextMarker == "" {
496 params.Marker = resp.NextMarker
500 // Trash a Keep block.
501 func (v *AzureBlobVolume) Trash(loc string) error {
503 return MethodDisabledError
506 // Ideally we would use If-Unmodified-Since, but that
507 // particular condition seems to be ignored by Azure. Instead,
508 // we get the Etag before checking Mtime, and use If-Match to
509 // ensure we don't delete data if Put() or Touch() happens
510 // between our calls to Mtime() and DeleteBlob().
511 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
515 if t, err := v.Mtime(loc); err != nil {
517 } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
521 // If TrashLifetime == 0, just delete it
522 if theConfig.TrashLifetime == 0 {
523 return v.bsClient.DeleteBlob(v.ContainerName, loc, map[string]string{
524 "If-Match": props.Etag,
528 // Otherwise, mark as trash
529 return v.bsClient.SetBlobMetadata(v.ContainerName, loc, map[string]string{
530 "expires_at": fmt.Sprintf("%d", time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()),
531 }, map[string]string{
532 "If-Match": props.Etag,
536 // Untrash a Keep block.
537 // Delete the expires_at metadata attribute
538 func (v *AzureBlobVolume) Untrash(loc string) error {
539 // if expires_at does not exist, return NotFoundError
540 metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
542 return v.translateError(err)
544 if metadata["expires_at"] == "" {
545 return os.ErrNotExist
548 // reset expires_at metadata attribute
549 metadata["expires_at"] = ""
550 err = v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
551 return v.translateError(err)
554 // Status returns a VolumeStatus struct with placeholder data.
555 func (v *AzureBlobVolume) Status() *VolumeStatus {
556 return &VolumeStatus{
558 BytesFree: BlockSize * 1000,
563 // String returns a volume label, including the container name.
564 func (v *AzureBlobVolume) String() string {
565 return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
568 // Writable returns true, unless the -readonly flag was on when the
570 func (v *AzureBlobVolume) Writable() bool {
574 // Replication returns the replication level of the container, as
575 // specified by the -azure-storage-replication argument.
576 func (v *AzureBlobVolume) Replication() int {
577 return v.AzureReplication
580 // If possible, translate an Azure SDK error to a recognizable error
581 // like os.ErrNotExist.
582 func (v *AzureBlobVolume) translateError(err error) error {
586 case strings.Contains(err.Error(), "Not Found"):
587 // "storage: service returned without a response body (404 Not Found)"
588 return os.ErrNotExist
594 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
596 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
597 return keepBlockRegexp.MatchString(s)
600 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
601 // and deletes them from the volume.
602 func (v *AzureBlobVolume) EmptyTrash() {
603 var bytesDeleted, bytesInTrash int64
604 var blocksDeleted, blocksInTrash int
605 params := storage.ListBlobsParameters{Include: "metadata"}
608 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
610 log.Printf("EmptyTrash: ListBlobs: %v", err)
613 for _, b := range resp.Blobs {
614 // Check if the block is expired
615 if b.Metadata["expires_at"] == "" {
620 bytesInTrash += b.Properties.ContentLength
622 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
624 log.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
628 if expiresAt > time.Now().Unix() {
632 err = v.bsClient.DeleteBlob(v.ContainerName, b.Name, map[string]string{
633 "If-Match": b.Properties.Etag,
636 log.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
640 bytesDeleted += b.Properties.ContentLength
642 if resp.NextMarker == "" {
645 params.Marker = resp.NextMarker
648 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)
651 // InternalStats returns bucket I/O and API call counters.
652 func (v *AzureBlobVolume) InternalStats() interface{} {
653 return &v.bsClient.stats
656 type azureBlobStats struct {
661 GetMetadataOps uint64
662 GetPropertiesOps uint64
664 SetMetadataOps uint64
669 func (s *azureBlobStats) TickErr(err error) {
673 errType := fmt.Sprintf("%T", err)
674 if err, ok := err.(storage.AzureStorageServiceError); ok {
675 errType = errType + fmt.Sprintf(" %d (%s)", err.StatusCode, err.Code)
677 log.Printf("errType %T, err %s", err, err)
678 s.statsTicker.TickErr(err, errType)
681 // azureBlobClient wraps storage.BlobStorageClient in order to count
682 // I/O and API usage stats.
683 type azureBlobClient struct {
684 client *storage.BlobStorageClient
688 func (c *azureBlobClient) ContainerExists(cname string) (bool, error) {
689 c.stats.Tick(&c.stats.Ops)
690 ok, err := c.client.ContainerExists(cname)
695 func (c *azureBlobClient) GetBlobMetadata(cname, bname string) (map[string]string, error) {
696 c.stats.Tick(&c.stats.Ops, &c.stats.GetMetadataOps)
697 m, err := c.client.GetBlobMetadata(cname, bname)
702 func (c *azureBlobClient) GetBlobProperties(cname, bname string) (*storage.BlobProperties, error) {
703 c.stats.Tick(&c.stats.Ops, &c.stats.GetPropertiesOps)
704 p, err := c.client.GetBlobProperties(cname, bname)
709 func (c *azureBlobClient) GetBlob(cname, bname string) (io.ReadCloser, error) {
710 c.stats.Tick(&c.stats.Ops, &c.stats.GetOps)
711 rdr, err := c.client.GetBlob(cname, bname)
713 return NewCountingReader(rdr, c.stats.TickInBytes), err
716 func (c *azureBlobClient) GetBlobRange(cname, bname, byterange string, hdrs map[string]string) (io.ReadCloser, error) {
717 c.stats.Tick(&c.stats.Ops, &c.stats.GetRangeOps)
718 rdr, err := c.client.GetBlobRange(cname, bname, byterange, hdrs)
720 return NewCountingReader(rdr, c.stats.TickInBytes), err
723 func (c *azureBlobClient) CreateBlockBlobFromReader(cname, bname string, size uint64, rdr io.Reader, hdrs map[string]string) error {
724 c.stats.Tick(&c.stats.Ops, &c.stats.CreateOps)
725 rdr = NewCountingReader(rdr, c.stats.TickOutBytes)
726 err := c.client.CreateBlockBlobFromReader(cname, bname, size, rdr, hdrs)
731 func (c *azureBlobClient) SetBlobMetadata(cname, bname string, m, hdrs map[string]string) error {
732 c.stats.Tick(&c.stats.Ops, &c.stats.SetMetadataOps)
733 err := c.client.SetBlobMetadata(cname, bname, m, hdrs)
738 func (c *azureBlobClient) ListBlobs(cname string, params storage.ListBlobsParameters) (storage.BlobListResponse, error) {
739 c.stats.Tick(&c.stats.Ops, &c.stats.ListOps)
740 resp, err := c.client.ListBlobs(cname, params)
745 func (c *azureBlobClient) DeleteBlob(cname, bname string, hdrs map[string]string) error {
746 c.stats.Tick(&c.stats.Ops, &c.stats.DelOps)
747 err := c.client.DeleteBlob(cname, bname, hdrs)