19 "git.curoverse.com/arvados.git/sdk/go/arvados"
20 log "github.com/Sirupsen/logrus"
21 "github.com/curoverse/azure-sdk-for-go/storage"
24 const azureDefaultRequestTimeout = arvados.Duration(10 * time.Minute)
28 azureStorageAccountName string
29 azureStorageAccountKeyFile string
30 azureStorageReplication int
31 azureWriteRaceInterval = 15 * time.Second
32 azureWriteRacePollTime = time.Second
35 func readKeyFromFile(file string) (string, error) {
36 buf, err := ioutil.ReadFile(file)
38 return "", errors.New("reading key from " + file + ": " + err.Error())
40 accountKey := strings.TrimSpace(string(buf))
42 return "", errors.New("empty account key in " + file)
44 return accountKey, nil
47 type azureVolumeAdder struct {
51 // String implements flag.Value
52 func (s *azureVolumeAdder) String() string {
56 func (s *azureVolumeAdder) Set(containerName string) error {
57 s.Config.Volumes = append(s.Config.Volumes, &AzureBlobVolume{
58 ContainerName: containerName,
59 StorageAccountName: azureStorageAccountName,
60 StorageAccountKeyFile: azureStorageAccountKeyFile,
61 AzureReplication: azureStorageReplication,
62 ReadOnly: deprecated.flagReadonly,
68 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &AzureBlobVolume{} })
70 flag.Var(&azureVolumeAdder{theConfig},
71 "azure-storage-container-volume",
72 "Use the given container as a storage volume. Can be given multiple times.")
74 &azureStorageAccountName,
75 "azure-storage-account-name",
77 "Azure storage account name used for subsequent --azure-storage-container-volume arguments.")
79 &azureStorageAccountKeyFile,
80 "azure-storage-account-key-file",
82 "`File` containing the account key used for subsequent --azure-storage-container-volume arguments.")
84 &azureStorageReplication,
85 "azure-storage-replication",
87 "Replication level to report to clients when data is stored in an Azure container.")
90 "azure-max-get-bytes",
92 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))
95 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
97 type AzureBlobVolume struct {
98 StorageAccountName string
99 StorageAccountKeyFile string
103 RequestTimeout arvados.Duration
105 azClient storage.Client
106 bsClient storage.BlobStorageClient
109 // Examples implements VolumeWithExamples.
110 func (*AzureBlobVolume) Examples() []Volume {
113 StorageAccountName: "example-account-name",
114 StorageAccountKeyFile: "/etc/azure_storage_account_key.txt",
115 ContainerName: "example-container-name",
117 RequestTimeout: azureDefaultRequestTimeout,
122 // Type implements Volume.
123 func (v *AzureBlobVolume) Type() string {
127 // Start implements Volume.
128 func (v *AzureBlobVolume) Start() error {
129 if v.ContainerName == "" {
130 return errors.New("no container name given")
132 if v.StorageAccountName == "" || v.StorageAccountKeyFile == "" {
133 return errors.New("StorageAccountName and StorageAccountKeyFile must be given")
135 accountKey, err := readKeyFromFile(v.StorageAccountKeyFile)
139 v.azClient, err = storage.NewBasicClient(v.StorageAccountName, accountKey)
141 return fmt.Errorf("creating Azure storage client: %s", err)
144 if v.RequestTimeout == 0 {
145 v.RequestTimeout = azureDefaultRequestTimeout
147 v.azClient.HTTPClient = &http.Client{
148 Timeout: time.Duration(v.RequestTimeout),
150 v.bsClient = v.azClient.GetBlobService()
152 ok, err := v.bsClient.ContainerExists(v.ContainerName)
157 return fmt.Errorf("Azure container %q does not exist", v.ContainerName)
162 // Return true if expires_at metadata attribute is found on the block
163 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
164 metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
166 return false, metadata, v.translateError(err)
168 if metadata["expires_at"] != "" {
169 return true, metadata, nil
171 return false, metadata, nil
174 // Get reads a Keep block that has been stored as a block blob in the
177 // If the block is younger than azureWriteRaceInterval and is
178 // unexpectedly empty, assume a PutBlob operation is in progress, and
179 // wait for it to finish writing.
180 func (v *AzureBlobVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
181 trashed, _, err := v.checkTrashed(loc)
186 return 0, os.ErrNotExist
188 var deadline time.Time
189 haveDeadline := false
190 size, err := v.get(ctx, loc, buf)
191 for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
192 // Seeing a brand new empty block probably means we're
193 // in a race with CreateBlob, which under the hood
194 // (apparently) does "CreateEmpty" and "CommitData"
195 // with no additional transaction locking.
197 t, err := v.Mtime(loc)
199 log.Print("Got empty block (possible race) but Mtime failed: ", err)
202 deadline = t.Add(azureWriteRaceInterval)
203 if time.Now().After(deadline) {
206 log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
208 } else if time.Now().After(deadline) {
214 case <-time.After(azureWriteRacePollTime):
216 size, err = v.get(ctx, loc, buf)
219 log.Printf("Race ended with size==%d", size)
224 func (v *AzureBlobVolume) get(ctx context.Context, loc string, buf []byte) (int, error) {
225 ctx, cancel := context.WithCancel(ctx)
227 expectSize := len(buf)
228 if azureMaxGetBytes < BlockSize {
229 // Unfortunately the handler doesn't tell us how long the blob
230 // is expected to be, so we have to ask Azure.
231 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
233 return 0, v.translateError(err)
235 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
236 return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
238 expectSize = int(props.ContentLength)
245 // We'll update this actualSize if/when we get the last piece.
247 pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
248 errors := make(chan error, pieces)
249 var wg sync.WaitGroup
251 for p := 0; p < pieces; p++ {
252 // Each goroutine retrieves one piece. If we hit an
253 // error, it is sent to the errors chan so get() can
254 // return it -- but only if the error happens before
255 // ctx is done. This way, if ctx is done before we hit
256 // any other error (e.g., requesting client has hung
257 // up), we return the original ctx.Err() instead of
258 // the secondary errors from the transfers that got
259 // interrupted as a result.
262 startPos := p * azureMaxGetBytes
263 endPos := startPos + azureMaxGetBytes
264 if endPos > expectSize {
267 var rdr io.ReadCloser
269 gotRdr := make(chan struct{})
272 if startPos == 0 && endPos == expectSize {
273 rdr, err = v.bsClient.GetBlob(v.ContainerName, loc)
275 rdr, err = v.bsClient.GetBlobRange(v.ContainerName, loc, fmt.Sprintf("%d-%d", startPos, endPos-1), nil)
295 // Close the reader when the client
296 // hangs up or another piece fails
297 // (possibly interrupting ReadFull())
298 // or when all pieces succeed and
303 n, err := io.ReadFull(rdr, buf[startPos:endPos])
304 if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
305 // If we don't know the actual size,
306 // and just tried reading 64 MiB, it's
307 // normal to encounter EOF.
308 } else if err != nil {
309 if ctx.Err() == nil {
316 actualSize = startPos + n
323 return 0, v.translateError(<-errors)
325 if ctx.Err() != nil {
328 return actualSize, nil
331 // Compare the given data with existing stored data.
332 func (v *AzureBlobVolume) Compare(ctx context.Context, loc string, expect []byte) error {
333 trashed, _, err := v.checkTrashed(loc)
338 return os.ErrNotExist
340 var rdr io.ReadCloser
341 gotRdr := make(chan struct{})
344 rdr, err = v.bsClient.GetBlob(v.ContainerName, loc)
358 return v.translateError(err)
361 return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
364 // Put stores a Keep block as a block blob in the container.
365 func (v *AzureBlobVolume) Put(ctx context.Context, loc string, block []byte) error {
367 return MethodDisabledError
369 // Send the block data through a pipe, so that (if we need to)
370 // we can close the pipe early and abandon our
371 // CreateBlockBlobFromReader() goroutine, without worrying
372 // about CreateBlockBlobFromReader() accessing our block
373 // buffer after we release it.
374 bufr, bufw := io.Pipe()
376 io.Copy(bufw, bytes.NewReader(block))
379 errChan := make(chan error)
381 errChan <- v.bsClient.CreateBlockBlobFromReader(v.ContainerName, loc, uint64(len(block)), bufr, nil)
385 theConfig.debugLogf("%s: taking CreateBlockBlobFromReader's input away: %s", v, ctx.Err())
386 // Our pipe might be stuck in Write(), waiting for
387 // io.Copy() to read. If so, un-stick it. This means
388 // CreateBlockBlobFromReader will get corrupt data,
389 // but that's OK: the size won't match, so the write
391 go io.Copy(ioutil.Discard, bufr)
392 // CloseWithError() will return once pending I/O is done.
393 bufw.CloseWithError(ctx.Err())
394 theConfig.debugLogf("%s: abandoning CreateBlockBlobFromReader goroutine", v)
396 case err := <-errChan:
401 // Touch updates the last-modified property of a block blob.
402 func (v *AzureBlobVolume) Touch(loc string) error {
404 return MethodDisabledError
406 trashed, metadata, err := v.checkTrashed(loc)
411 return os.ErrNotExist
414 metadata["touch"] = fmt.Sprintf("%d", time.Now())
415 return v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
418 // Mtime returns the last-modified property of a block blob.
419 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
420 trashed, _, err := v.checkTrashed(loc)
422 return time.Time{}, err
425 return time.Time{}, os.ErrNotExist
428 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
430 return time.Time{}, err
432 return time.Parse(time.RFC1123, props.LastModified)
435 // IndexTo writes a list of Keep blocks that are stored in the
437 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
438 params := storage.ListBlobsParameters{
443 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
447 for _, b := range resp.Blobs {
448 t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
452 if !v.isKeepBlock(b.Name) {
455 if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
456 // A new zero-length blob is probably
457 // just a new non-empty blob that
458 // hasn't committed its data yet (see
459 // Get()), and in any case has no
463 if b.Metadata["expires_at"] != "" {
464 // Trashed blob; exclude it from response
467 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.UnixNano())
469 if resp.NextMarker == "" {
472 params.Marker = resp.NextMarker
476 // Trash a Keep block.
477 func (v *AzureBlobVolume) Trash(loc string) error {
479 return MethodDisabledError
482 // Ideally we would use If-Unmodified-Since, but that
483 // particular condition seems to be ignored by Azure. Instead,
484 // we get the Etag before checking Mtime, and use If-Match to
485 // ensure we don't delete data if Put() or Touch() happens
486 // between our calls to Mtime() and DeleteBlob().
487 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
491 if t, err := v.Mtime(loc); err != nil {
493 } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
497 // If TrashLifetime == 0, just delete it
498 if theConfig.TrashLifetime == 0 {
499 return v.bsClient.DeleteBlob(v.ContainerName, loc, map[string]string{
500 "If-Match": props.Etag,
504 // Otherwise, mark as trash
505 return v.bsClient.SetBlobMetadata(v.ContainerName, loc, map[string]string{
506 "expires_at": fmt.Sprintf("%d", time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()),
507 }, map[string]string{
508 "If-Match": props.Etag,
512 // Untrash a Keep block.
513 // Delete the expires_at metadata attribute
514 func (v *AzureBlobVolume) Untrash(loc string) error {
515 // if expires_at does not exist, return NotFoundError
516 metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
518 return v.translateError(err)
520 if metadata["expires_at"] == "" {
521 return os.ErrNotExist
524 // reset expires_at metadata attribute
525 metadata["expires_at"] = ""
526 err = v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
527 return v.translateError(err)
530 // Status returns a VolumeStatus struct with placeholder data.
531 func (v *AzureBlobVolume) Status() *VolumeStatus {
532 return &VolumeStatus{
534 BytesFree: BlockSize * 1000,
539 // String returns a volume label, including the container name.
540 func (v *AzureBlobVolume) String() string {
541 return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
544 // Writable returns true, unless the -readonly flag was on when the
546 func (v *AzureBlobVolume) Writable() bool {
550 // Replication returns the replication level of the container, as
551 // specified by the -azure-storage-replication argument.
552 func (v *AzureBlobVolume) Replication() int {
553 return v.AzureReplication
556 // If possible, translate an Azure SDK error to a recognizable error
557 // like os.ErrNotExist.
558 func (v *AzureBlobVolume) translateError(err error) error {
562 case strings.Contains(err.Error(), "Not Found"):
563 // "storage: service returned without a response body (404 Not Found)"
564 return os.ErrNotExist
570 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
572 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
573 return keepBlockRegexp.MatchString(s)
576 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
577 // and deletes them from the volume.
578 func (v *AzureBlobVolume) EmptyTrash() {
579 var bytesDeleted, bytesInTrash int64
580 var blocksDeleted, blocksInTrash int
581 params := storage.ListBlobsParameters{Include: "metadata"}
584 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
586 log.Printf("EmptyTrash: ListBlobs: %v", err)
589 for _, b := range resp.Blobs {
590 // Check if the block is expired
591 if b.Metadata["expires_at"] == "" {
596 bytesInTrash += b.Properties.ContentLength
598 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
600 log.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
604 if expiresAt > time.Now().Unix() {
608 err = v.bsClient.DeleteBlob(v.ContainerName, b.Name, map[string]string{
609 "If-Match": b.Properties.Etag,
612 log.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
616 bytesDeleted += b.Properties.ContentLength
618 if resp.NextMarker == "" {
621 params.Marker = resp.NextMarker
624 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)