16 "github.com/curoverse/azure-sdk-for-go/storage"
20 azureStorageAccountName string
21 azureStorageAccountKeyFile string
22 azureStorageReplication int
23 azureWriteRaceInterval = 15 * time.Second
24 azureWriteRacePollTime = time.Second
27 func readKeyFromFile(file string) (string, error) {
28 buf, err := ioutil.ReadFile(file)
30 return "", errors.New("reading key from " + file + ": " + err.Error())
32 accountKey := strings.TrimSpace(string(buf))
34 return "", errors.New("empty account key in " + file)
36 return accountKey, nil
39 type azureVolumeAdder struct {
43 func (s *azureVolumeAdder) Set(containerName string) error {
44 if containerName == "" {
45 return errors.New("no container name given")
47 if azureStorageAccountName == "" || azureStorageAccountKeyFile == "" {
48 return errors.New("-azure-storage-account-name and -azure-storage-account-key-file arguments must given before -azure-storage-container-volume")
50 accountKey, err := readKeyFromFile(azureStorageAccountKeyFile)
54 azClient, err := storage.NewBasicClient(azureStorageAccountName, accountKey)
56 return errors.New("creating Azure storage client: " + err.Error())
59 log.Print("Notice: -serialize is not supported by azure-blob-container volumes.")
61 v := NewAzureBlobVolume(azClient, containerName, flagReadonly, azureStorageReplication)
62 if err := v.Check(); err != nil {
65 *s.volumeSet = append(*s.volumeSet, v)
70 flag.Var(&azureVolumeAdder{&volumes},
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 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
92 type AzureBlobVolume struct {
93 azClient storage.Client
94 bsClient storage.BlobStorageClient
100 // NewAzureBlobVolume returns a new AzureBlobVolume using the given
101 // client and container name. The replication argument specifies the
102 // replication level to report when writing data.
103 func NewAzureBlobVolume(client storage.Client, containerName string, readonly bool, replication int) *AzureBlobVolume {
104 return &AzureBlobVolume{
106 bsClient: client.GetBlobService(),
107 containerName: containerName,
109 replication: replication,
113 // Check returns nil if the volume is usable.
114 func (v *AzureBlobVolume) Check() error {
115 ok, err := v.bsClient.ContainerExists(v.containerName)
120 return errors.New("container does not exist")
125 // Get reads a Keep block that has been stored as a block blob in the
128 // If the block is younger than azureWriteRaceInterval and is
129 // unexpectedly empty, assume a PutBlob operation is in progress, and
130 // wait for it to finish writing.
131 func (v *AzureBlobVolume) Get(loc string) ([]byte, error) {
132 var deadline time.Time
133 haveDeadline := false
134 buf, err := v.get(loc)
135 for err == nil && len(buf) == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
136 // Seeing a brand new empty block probably means we're
137 // in a race with CreateBlob, which under the hood
138 // (apparently) does "CreateEmpty" and "CommitData"
139 // with no additional transaction locking.
141 t, err := v.Mtime(loc)
143 log.Print("Got empty block (possible race) but Mtime failed: ", err)
146 deadline = t.Add(azureWriteRaceInterval)
147 if time.Now().After(deadline) {
150 log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
152 } else if time.Now().After(deadline) {
156 time.Sleep(azureWriteRacePollTime)
157 buf, err = v.get(loc)
160 log.Printf("Race ended with len(buf)==%d", len(buf))
165 func (v *AzureBlobVolume) get(loc string) ([]byte, error) {
166 rdr, err := v.bsClient.GetBlob(v.containerName, loc)
168 return nil, v.translateError(err)
171 buf := bufs.Get(BlockSize)
172 n, err := io.ReadFull(rdr, buf)
174 case nil, io.EOF, io.ErrUnexpectedEOF:
182 // Compare the given data with existing stored data.
183 func (v *AzureBlobVolume) Compare(loc string, expect []byte) error {
184 rdr, err := v.bsClient.GetBlob(v.containerName, loc)
186 return v.translateError(err)
189 return compareReaderWithBuf(rdr, expect, loc[:32])
192 // Put sotres a Keep block as a block blob in the container.
193 func (v *AzureBlobVolume) Put(loc string, block []byte) error {
195 return MethodDisabledError
197 return v.bsClient.CreateBlockBlobFromReader(v.containerName, loc, uint64(len(block)), bytes.NewReader(block))
200 // Touch updates the last-modified property of a block blob.
201 func (v *AzureBlobVolume) Touch(loc string) error {
203 return MethodDisabledError
205 return v.bsClient.SetBlobMetadata(v.containerName, loc, map[string]string{
206 "touch": fmt.Sprintf("%d", time.Now()),
210 // Mtime returns the last-modified property of a block blob.
211 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
212 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
214 return time.Time{}, err
216 return time.Parse(time.RFC1123, props.LastModified)
219 // IndexTo writes a list of Keep blocks that are stored in the
221 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
222 params := storage.ListBlobsParameters{
226 resp, err := v.bsClient.ListBlobs(v.containerName, params)
230 for _, b := range resp.Blobs {
231 t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
235 if !v.isKeepBlock(b.Name) {
238 if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
239 // A new zero-length blob is probably
240 // just a new non-empty blob that
241 // hasn't committed its data yet (see
242 // Get()), and in any case has no
246 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.Unix())
248 if resp.NextMarker == "" {
251 params.Marker = resp.NextMarker
255 // Delete a Keep block.
256 func (v *AzureBlobVolume) Delete(loc string) error {
258 return MethodDisabledError
260 // Ideally we would use If-Unmodified-Since, but that
261 // particular condition seems to be ignored by Azure. Instead,
262 // we get the Etag before checking Mtime, and use If-Match to
263 // ensure we don't delete data if Put() or Touch() happens
264 // between our calls to Mtime() and DeleteBlob().
265 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
269 if t, err := v.Mtime(loc); err != nil {
271 } else if time.Since(t) < blobSignatureTTL {
274 return v.bsClient.DeleteBlob(v.containerName, loc, map[string]string{
275 "If-Match": props.Etag,
279 // Status returns a VolumeStatus struct with placeholder data.
280 func (v *AzureBlobVolume) Status() *VolumeStatus {
281 return &VolumeStatus{
283 BytesFree: BlockSize * 1000,
288 // String returns a volume label, including the container name.
289 func (v *AzureBlobVolume) String() string {
290 return fmt.Sprintf("azure-storage-container:%+q", v.containerName)
293 // Writable returns true, unless the -readonly flag was on when the
295 func (v *AzureBlobVolume) Writable() bool {
299 // Replication returns the replication level of the container, as
300 // specified by the -azure-storage-replication argument.
301 func (v *AzureBlobVolume) Replication() int {
305 // If possible, translate an Azure SDK error to a recognizable error
306 // like os.ErrNotExist.
307 func (v *AzureBlobVolume) translateError(err error) error {
311 case strings.Contains(err.Error(), "404 Not Found"):
312 // "storage: service returned without a response body (404 Not Found)"
313 return os.ErrNotExist
319 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
320 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
321 return keepBlockRegexp.MatchString(s)