18 "github.com/curoverse/azure-sdk-for-go/storage"
23 azureStorageAccountName string
24 azureStorageAccountKeyFile string
25 azureStorageReplication int
26 azureWriteRaceInterval = 15 * time.Second
27 azureWriteRacePollTime = time.Second
30 func readKeyFromFile(file string) (string, error) {
31 buf, err := ioutil.ReadFile(file)
33 return "", errors.New("reading key from " + file + ": " + err.Error())
35 accountKey := strings.TrimSpace(string(buf))
37 return "", errors.New("empty account key in " + file)
39 return accountKey, nil
42 type azureVolumeAdder struct {
46 // String implements flag.Value
47 func (s *azureVolumeAdder) String() string {
51 func (s *azureVolumeAdder) Set(containerName string) error {
52 s.Config.Volumes = append(s.Config.Volumes, &AzureBlobVolume{
53 ContainerName: containerName,
54 StorageAccountName: azureStorageAccountName,
55 StorageAccountKeyFile: azureStorageAccountKeyFile,
56 AzureReplication: azureStorageReplication,
57 ReadOnly: flagReadonly,
63 VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &AzureBlobVolume{} })
65 flag.Var(&azureVolumeAdder{theConfig},
66 "azure-storage-container-volume",
67 "Use the given container as a storage volume. Can be given multiple times.")
69 &azureStorageAccountName,
70 "azure-storage-account-name",
72 "Azure storage account name used for subsequent --azure-storage-container-volume arguments.")
74 &azureStorageAccountKeyFile,
75 "azure-storage-account-key-file",
77 "`File` containing the account key used for subsequent --azure-storage-container-volume arguments.")
79 &azureStorageReplication,
80 "azure-storage-replication",
82 "Replication level to report to clients when data is stored in an Azure container.")
85 "azure-max-get-bytes",
87 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))
90 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
92 type AzureBlobVolume struct {
93 StorageAccountName string
94 StorageAccountKeyFile string
99 azClient storage.Client
100 bsClient storage.BlobStorageClient
103 // Examples implements VolumeWithExamples.
104 func (*AzureBlobVolume) Examples() []Volume {
107 StorageAccountName: "example-account-name",
108 StorageAccountKeyFile: "/etc/azure_storage_account_key.txt",
109 ContainerName: "example-container-name",
115 // Type implements Volume.
116 func (v *AzureBlobVolume) Type() string {
120 // Start implements Volume.
121 func (v *AzureBlobVolume) Start() error {
122 if v.ContainerName == "" {
123 return errors.New("no container name given")
125 if v.StorageAccountName == "" || v.StorageAccountKeyFile == "" {
126 return errors.New("StorageAccountName and StorageAccountKeyFile must be given")
128 accountKey, err := readKeyFromFile(v.StorageAccountKeyFile)
132 v.azClient, err = storage.NewBasicClient(v.StorageAccountName, accountKey)
134 return fmt.Errorf("creating Azure storage client: %s", err)
136 v.bsClient = v.azClient.GetBlobService()
138 ok, err := v.bsClient.ContainerExists(v.ContainerName)
143 return fmt.Errorf("Azure container %q does not exist", v.ContainerName)
148 // Return true if expires_at metadata attribute is found on the block
149 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
150 metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
152 return false, metadata, v.translateError(err)
154 if metadata["expires_at"] != "" {
155 return true, metadata, nil
157 return false, metadata, nil
160 // Get reads a Keep block that has been stored as a block blob in the
163 // If the block is younger than azureWriteRaceInterval and is
164 // unexpectedly empty, assume a PutBlob operation is in progress, and
165 // wait for it to finish writing.
166 func (v *AzureBlobVolume) Get(loc string, buf []byte) (int, error) {
167 trashed, _, err := v.checkTrashed(loc)
172 return 0, os.ErrNotExist
174 var deadline time.Time
175 haveDeadline := false
176 size, err := v.get(loc, buf)
177 for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
178 // Seeing a brand new empty block probably means we're
179 // in a race with CreateBlob, which under the hood
180 // (apparently) does "CreateEmpty" and "CommitData"
181 // with no additional transaction locking.
183 t, err := v.Mtime(loc)
185 log.Print("Got empty block (possible race) but Mtime failed: ", err)
188 deadline = t.Add(azureWriteRaceInterval)
189 if time.Now().After(deadline) {
192 log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
194 } else if time.Now().After(deadline) {
197 time.Sleep(azureWriteRacePollTime)
198 size, err = v.get(loc, buf)
201 log.Printf("Race ended with size==%d", size)
206 func (v *AzureBlobVolume) get(loc string, buf []byte) (int, error) {
207 expectSize := len(buf)
208 if azureMaxGetBytes < BlockSize {
209 // Unfortunately the handler doesn't tell us how long the blob
210 // is expected to be, so we have to ask Azure.
211 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
213 return 0, v.translateError(err)
215 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
216 return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
218 expectSize = int(props.ContentLength)
225 // We'll update this actualSize if/when we get the last piece.
227 pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
228 errors := make([]error, pieces)
229 var wg sync.WaitGroup
231 for p := 0; p < pieces; p++ {
234 startPos := p * azureMaxGetBytes
235 endPos := startPos + azureMaxGetBytes
236 if endPos > expectSize {
239 var rdr io.ReadCloser
241 if startPos == 0 && endPos == expectSize {
242 rdr, err = v.bsClient.GetBlob(v.ContainerName, loc)
244 rdr, err = v.bsClient.GetBlobRange(v.ContainerName, loc, fmt.Sprintf("%d-%d", startPos, endPos-1), nil)
251 n, err := io.ReadFull(rdr, buf[startPos:endPos])
252 if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
253 // If we don't know the actual size,
254 // and just tried reading 64 MiB, it's
255 // normal to encounter EOF.
256 } else if err != nil {
260 actualSize = startPos + n
265 for _, err := range errors {
267 return 0, v.translateError(err)
270 return actualSize, nil
273 // Compare the given data with existing stored data.
274 func (v *AzureBlobVolume) Compare(loc string, expect []byte) error {
275 trashed, _, err := v.checkTrashed(loc)
280 return os.ErrNotExist
282 rdr, err := v.bsClient.GetBlob(v.ContainerName, loc)
284 return v.translateError(err)
287 return compareReaderWithBuf(rdr, expect, loc[:32])
290 // Put stores a Keep block as a block blob in the container.
291 func (v *AzureBlobVolume) Put(loc string, block []byte) error {
293 return MethodDisabledError
295 return v.bsClient.CreateBlockBlobFromReader(v.ContainerName, loc, uint64(len(block)), bytes.NewReader(block), nil)
298 // Touch updates the last-modified property of a block blob.
299 func (v *AzureBlobVolume) Touch(loc string) error {
301 return MethodDisabledError
303 trashed, metadata, err := v.checkTrashed(loc)
308 return os.ErrNotExist
311 metadata["touch"] = fmt.Sprintf("%d", time.Now())
312 return v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
315 // Mtime returns the last-modified property of a block blob.
316 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
317 trashed, _, err := v.checkTrashed(loc)
319 return time.Time{}, err
322 return time.Time{}, os.ErrNotExist
325 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
327 return time.Time{}, err
329 return time.Parse(time.RFC1123, props.LastModified)
332 // IndexTo writes a list of Keep blocks that are stored in the
334 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
335 params := storage.ListBlobsParameters{
340 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
344 for _, b := range resp.Blobs {
345 t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
349 if !v.isKeepBlock(b.Name) {
352 if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
353 // A new zero-length blob is probably
354 // just a new non-empty blob that
355 // hasn't committed its data yet (see
356 // Get()), and in any case has no
360 if b.Metadata["expires_at"] != "" {
361 // Trashed blob; exclude it from response
364 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.UnixNano())
366 if resp.NextMarker == "" {
369 params.Marker = resp.NextMarker
373 // Trash a Keep block.
374 func (v *AzureBlobVolume) Trash(loc string) error {
376 return MethodDisabledError
379 // Ideally we would use If-Unmodified-Since, but that
380 // particular condition seems to be ignored by Azure. Instead,
381 // we get the Etag before checking Mtime, and use If-Match to
382 // ensure we don't delete data if Put() or Touch() happens
383 // between our calls to Mtime() and DeleteBlob().
384 props, err := v.bsClient.GetBlobProperties(v.ContainerName, loc)
388 if t, err := v.Mtime(loc); err != nil {
390 } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
394 // If TrashLifetime == 0, just delete it
395 if theConfig.TrashLifetime == 0 {
396 return v.bsClient.DeleteBlob(v.ContainerName, loc, map[string]string{
397 "If-Match": props.Etag,
401 // Otherwise, mark as trash
402 return v.bsClient.SetBlobMetadata(v.ContainerName, loc, map[string]string{
403 "expires_at": fmt.Sprintf("%d", time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()),
404 }, map[string]string{
405 "If-Match": props.Etag,
409 // Untrash a Keep block.
410 // Delete the expires_at metadata attribute
411 func (v *AzureBlobVolume) Untrash(loc string) error {
412 // if expires_at does not exist, return NotFoundError
413 metadata, err := v.bsClient.GetBlobMetadata(v.ContainerName, loc)
415 return v.translateError(err)
417 if metadata["expires_at"] == "" {
418 return os.ErrNotExist
421 // reset expires_at metadata attribute
422 metadata["expires_at"] = ""
423 err = v.bsClient.SetBlobMetadata(v.ContainerName, loc, metadata, nil)
424 return v.translateError(err)
427 // Status returns a VolumeStatus struct with placeholder data.
428 func (v *AzureBlobVolume) Status() *VolumeStatus {
429 return &VolumeStatus{
431 BytesFree: BlockSize * 1000,
436 // String returns a volume label, including the container name.
437 func (v *AzureBlobVolume) String() string {
438 return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
441 // Writable returns true, unless the -readonly flag was on when the
443 func (v *AzureBlobVolume) Writable() bool {
447 // Replication returns the replication level of the container, as
448 // specified by the -azure-storage-replication argument.
449 func (v *AzureBlobVolume) Replication() int {
450 return v.AzureReplication
453 // If possible, translate an Azure SDK error to a recognizable error
454 // like os.ErrNotExist.
455 func (v *AzureBlobVolume) translateError(err error) error {
459 case strings.Contains(err.Error(), "Not Found"):
460 // "storage: service returned without a response body (404 Not Found)"
461 return os.ErrNotExist
467 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
469 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
470 return keepBlockRegexp.MatchString(s)
473 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
474 // and deletes them from the volume.
475 func (v *AzureBlobVolume) EmptyTrash() {
476 var bytesDeleted, bytesInTrash int64
477 var blocksDeleted, blocksInTrash int
478 params := storage.ListBlobsParameters{Include: "metadata"}
481 resp, err := v.bsClient.ListBlobs(v.ContainerName, params)
483 log.Printf("EmptyTrash: ListBlobs: %v", err)
486 for _, b := range resp.Blobs {
487 // Check if the block is expired
488 if b.Metadata["expires_at"] == "" {
493 bytesInTrash += b.Properties.ContentLength
495 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
497 log.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
501 if expiresAt > time.Now().Unix() {
505 err = v.bsClient.DeleteBlob(v.ContainerName, b.Name, map[string]string{
506 "If-Match": b.Properties.Etag,
509 log.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
513 bytesDeleted += b.Properties.ContentLength
515 if resp.NextMarker == "" {
518 params.Marker = resp.NextMarker
521 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)