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 func (s *azureVolumeAdder) Set(containerName string) error {
47 if trashLifetime != 0 {
48 return ErrNotImplemented
51 if containerName == "" {
52 return errors.New("no container name given")
54 if azureStorageAccountName == "" || azureStorageAccountKeyFile == "" {
55 return errors.New("-azure-storage-account-name and -azure-storage-account-key-file arguments must given before -azure-storage-container-volume")
57 accountKey, err := readKeyFromFile(azureStorageAccountKeyFile)
61 azClient, err := storage.NewBasicClient(azureStorageAccountName, accountKey)
63 return errors.New("creating Azure storage client: " + err.Error())
66 log.Print("Notice: -serialize is not supported by azure-blob-container volumes.")
68 v := NewAzureBlobVolume(azClient, containerName, flagReadonly, azureStorageReplication)
69 if err := v.Check(); err != nil {
72 *s.volumeSet = append(*s.volumeSet, v)
77 flag.Var(&azureVolumeAdder{&volumes},
78 "azure-storage-container-volume",
79 "Use the given container as a storage volume. Can be given multiple times.")
81 &azureStorageAccountName,
82 "azure-storage-account-name",
84 "Azure storage account name used for subsequent --azure-storage-container-volume arguments.")
86 &azureStorageAccountKeyFile,
87 "azure-storage-account-key-file",
89 "File containing the account key used for subsequent --azure-storage-container-volume arguments.")
91 &azureStorageReplication,
92 "azure-storage-replication",
94 "Replication level to report to clients when data is stored in an Azure container.")
97 "azure-max-get-bytes",
99 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))
102 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
104 type AzureBlobVolume struct {
105 azClient storage.Client
106 bsClient storage.BlobStorageClient
112 // NewAzureBlobVolume returns a new AzureBlobVolume using the given
113 // client and container name. The replication argument specifies the
114 // replication level to report when writing data.
115 func NewAzureBlobVolume(client storage.Client, containerName string, readonly bool, replication int) *AzureBlobVolume {
116 return &AzureBlobVolume{
118 bsClient: client.GetBlobService(),
119 containerName: containerName,
121 replication: replication,
125 // Check returns nil if the volume is usable.
126 func (v *AzureBlobVolume) Check() error {
127 ok, err := v.bsClient.ContainerExists(v.containerName)
132 return errors.New("container does not exist")
137 // Return true if expires_at metadata attribute is found on the block
138 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
139 metadata, err := v.bsClient.GetBlobMetadata(v.containerName, loc)
141 return false, metadata, v.translateError(err)
143 if metadata["expires_at"] != "" {
144 return true, metadata, nil
146 return false, metadata, nil
149 // Get reads a Keep block that has been stored as a block blob in the
152 // If the block is younger than azureWriteRaceInterval and is
153 // unexpectedly empty, assume a PutBlob operation is in progress, and
154 // wait for it to finish writing.
155 func (v *AzureBlobVolume) Get(loc string, buf []byte) (int, error) {
156 trashed, _, err := v.checkTrashed(loc)
161 return 0, os.ErrNotExist
163 var deadline time.Time
164 haveDeadline := false
165 size, err := v.get(loc, buf)
166 for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
167 // Seeing a brand new empty block probably means we're
168 // in a race with CreateBlob, which under the hood
169 // (apparently) does "CreateEmpty" and "CommitData"
170 // with no additional transaction locking.
172 t, err := v.Mtime(loc)
174 log.Print("Got empty block (possible race) but Mtime failed: ", err)
177 deadline = t.Add(azureWriteRaceInterval)
178 if time.Now().After(deadline) {
181 log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
183 } else if time.Now().After(deadline) {
186 time.Sleep(azureWriteRacePollTime)
187 size, err = v.get(loc, buf)
190 log.Printf("Race ended with size==%d", size)
195 func (v *AzureBlobVolume) get(loc string, buf []byte) (int, error) {
196 expectSize := len(buf)
197 if azureMaxGetBytes < BlockSize {
198 // Unfortunately the handler doesn't tell us how long the blob
199 // is expected to be, so we have to ask Azure.
200 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
202 return 0, v.translateError(err)
204 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
205 return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
207 expectSize = int(props.ContentLength)
214 // We'll update this actualSize if/when we get the last piece.
216 pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
217 errors := make([]error, pieces)
218 var wg sync.WaitGroup
220 for p := 0; p < pieces; p++ {
223 startPos := p * azureMaxGetBytes
224 endPos := startPos + azureMaxGetBytes
225 if endPos > expectSize {
228 var rdr io.ReadCloser
230 if startPos == 0 && endPos == expectSize {
231 rdr, err = v.bsClient.GetBlob(v.containerName, loc)
233 rdr, err = v.bsClient.GetBlobRange(v.containerName, loc, fmt.Sprintf("%d-%d", startPos, endPos-1), nil)
240 n, err := io.ReadFull(rdr, buf[startPos:endPos])
241 if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
242 // If we don't know the actual size,
243 // and just tried reading 64 MiB, it's
244 // normal to encounter EOF.
245 } else if err != nil {
249 actualSize = startPos + n
254 for _, err := range errors {
256 return 0, v.translateError(err)
259 return actualSize, nil
262 // Compare the given data with existing stored data.
263 func (v *AzureBlobVolume) Compare(loc string, expect []byte) error {
264 trashed, _, err := v.checkTrashed(loc)
269 return os.ErrNotExist
271 rdr, err := v.bsClient.GetBlob(v.containerName, loc)
273 return v.translateError(err)
276 return compareReaderWithBuf(rdr, expect, loc[:32])
279 // Put stores a Keep block as a block blob in the container.
280 func (v *AzureBlobVolume) Put(loc string, block []byte) error {
282 return MethodDisabledError
284 return v.bsClient.CreateBlockBlobFromReader(v.containerName, loc, uint64(len(block)), bytes.NewReader(block), nil)
287 // Touch updates the last-modified property of a block blob.
288 func (v *AzureBlobVolume) Touch(loc string) error {
290 return MethodDisabledError
292 trashed, metadata, err := v.checkTrashed(loc)
297 return os.ErrNotExist
300 metadata["touch"] = fmt.Sprintf("%d", time.Now())
301 return v.bsClient.SetBlobMetadata(v.containerName, loc, metadata, nil)
304 // Mtime returns the last-modified property of a block blob.
305 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
306 trashed, _, err := v.checkTrashed(loc)
308 return time.Time{}, err
311 return time.Time{}, os.ErrNotExist
314 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
316 return time.Time{}, err
318 return time.Parse(time.RFC1123, props.LastModified)
321 // IndexTo writes a list of Keep blocks that are stored in the
323 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
324 params := storage.ListBlobsParameters{
329 resp, err := v.bsClient.ListBlobs(v.containerName, params)
333 for _, b := range resp.Blobs {
334 t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
338 if !v.isKeepBlock(b.Name) {
341 if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
342 // A new zero-length blob is probably
343 // just a new non-empty blob that
344 // hasn't committed its data yet (see
345 // Get()), and in any case has no
349 if b.Metadata["expires_at"] != "" {
350 // Trashed blob; exclude it from response
353 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.UnixNano())
355 if resp.NextMarker == "" {
358 params.Marker = resp.NextMarker
362 // Trash a Keep block.
363 func (v *AzureBlobVolume) Trash(loc string) error {
365 return MethodDisabledError
368 // Ideally we would use If-Unmodified-Since, but that
369 // particular condition seems to be ignored by Azure. Instead,
370 // we get the Etag before checking Mtime, and use If-Match to
371 // ensure we don't delete data if Put() or Touch() happens
372 // between our calls to Mtime() and DeleteBlob().
373 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
377 if t, err := v.Mtime(loc); err != nil {
379 } else if time.Since(t) < blobSignatureTTL {
383 // If trashLifetime == 0, just delete it
384 if trashLifetime == 0 {
385 return v.bsClient.DeleteBlob(v.containerName, loc, map[string]string{
386 "If-Match": props.Etag,
390 // Otherwise, mark as trash
391 return v.bsClient.SetBlobMetadata(v.containerName, loc, map[string]string{
392 "expires_at": fmt.Sprintf("%d", time.Now().Add(trashLifetime).Unix()),
393 }, map[string]string{
394 "If-Match": props.Etag,
398 // Untrash a Keep block.
399 // Delete the expires_at metadata attribute
400 func (v *AzureBlobVolume) Untrash(loc string) error {
401 // if expires_at does not exist, return NotFoundError
402 metadata, err := v.bsClient.GetBlobMetadata(v.containerName, loc)
404 return v.translateError(err)
406 if metadata["expires_at"] == "" {
407 return os.ErrNotExist
410 // reset expires_at metadata attribute
411 metadata["expires_at"] = ""
412 err = v.bsClient.SetBlobMetadata(v.containerName, loc, metadata, nil)
413 return v.translateError(err)
416 // Status returns a VolumeStatus struct with placeholder data.
417 func (v *AzureBlobVolume) Status() *VolumeStatus {
418 return &VolumeStatus{
420 BytesFree: BlockSize * 1000,
425 // String returns a volume label, including the container name.
426 func (v *AzureBlobVolume) String() string {
427 return fmt.Sprintf("azure-storage-container:%+q", v.containerName)
430 // Writable returns true, unless the -readonly flag was on when the
432 func (v *AzureBlobVolume) Writable() bool {
436 // Replication returns the replication level of the container, as
437 // specified by the -azure-storage-replication argument.
438 func (v *AzureBlobVolume) Replication() int {
442 // If possible, translate an Azure SDK error to a recognizable error
443 // like os.ErrNotExist.
444 func (v *AzureBlobVolume) translateError(err error) error {
448 case strings.Contains(err.Error(), "Not Found"):
449 // "storage: service returned without a response body (404 Not Found)"
450 return os.ErrNotExist
456 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
458 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
459 return keepBlockRegexp.MatchString(s)
462 // EmptyTrash looks for trashed blocks that exceeded trashLifetime
463 // and deletes them from the volume.
464 func (v *AzureBlobVolume) EmptyTrash() {
465 var bytesDeleted, bytesInTrash int64
466 var blocksDeleted, blocksInTrash int
467 params := storage.ListBlobsParameters{Include: "metadata"}
470 resp, err := v.bsClient.ListBlobs(v.containerName, params)
472 log.Printf("EmptyTrash: ListBlobs: %v", err)
475 for _, b := range resp.Blobs {
476 // Check if the block is expired
477 if b.Metadata["expires_at"] == "" {
482 bytesInTrash += b.Properties.ContentLength
484 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
486 log.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
490 if expiresAt > time.Now().Unix() {
494 err = v.bsClient.DeleteBlob(v.containerName, b.Name, map[string]string{
495 "If-Match": b.Properties.Etag,
498 log.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
502 bytesDeleted += b.Properties.ContentLength
504 if resp.NextMarker == "" {
507 params.Marker = resp.NextMarker
510 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)