15 "github.com/curoverse/azure-sdk-for-go/storage"
19 azureStorageAccountName string
20 azureStorageAccountKeyFile string
21 azureStorageReplication int
22 azureWriteRaceInterval time.Duration = 15 * time.Second
23 azureWriteRacePollTime time.Duration = time.Second
26 func readKeyFromFile(file string) (string, error) {
27 buf, err := ioutil.ReadFile(file)
29 return "", errors.New("reading key from " + file + ": " + err.Error())
31 accountKey := strings.TrimSpace(string(buf))
33 return "", errors.New("empty account key in " + file)
35 return accountKey, nil
38 type azureVolumeAdder struct {
42 func (s *azureVolumeAdder) Set(containerName string) error {
43 if containerName == "" {
44 return errors.New("no container name given")
46 if azureStorageAccountName == "" || azureStorageAccountKeyFile == "" {
47 return errors.New("-azure-storage-account-name and -azure-storage-account-key-file arguments must given before -azure-storage-container-volume")
49 accountKey, err := readKeyFromFile(azureStorageAccountKeyFile)
53 azClient, err := storage.NewBasicClient(azureStorageAccountName, accountKey)
55 return errors.New("creating Azure storage client: " + err.Error())
58 log.Print("Notice: -serialize is not supported by azure-blob-container volumes.")
60 v := NewAzureBlobVolume(azClient, containerName, flagReadonly, azureStorageReplication)
61 if err := v.Check(); err != nil {
64 *s.volumeSet = append(*s.volumeSet, v)
69 flag.Var(&azureVolumeAdder{&volumes},
70 "azure-storage-container-volume",
71 "Use the given container as a storage volume. Can be given multiple times.")
73 &azureStorageAccountName,
74 "azure-storage-account-name",
76 "Azure storage account name used for subsequent --azure-storage-container-volume arguments.")
78 &azureStorageAccountKeyFile,
79 "azure-storage-account-key-file",
81 "File containing the account key used for subsequent --azure-storage-container-volume arguments.")
83 &azureStorageReplication,
84 "azure-storage-replication",
86 "Replication level to report to clients when data is stored in an Azure container.")
89 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
91 type AzureBlobVolume struct {
92 azClient storage.Client
93 bsClient storage.BlobStorageClient
99 func NewAzureBlobVolume(client storage.Client, containerName string, readonly bool, replication int) *AzureBlobVolume {
100 return &AzureBlobVolume{
102 bsClient: client.GetBlobService(),
103 containerName: containerName,
105 replication: replication,
109 // Check returns nil if the volume is usable.
110 func (v *AzureBlobVolume) Check() error {
111 ok, err := v.bsClient.ContainerExists(v.containerName)
116 return errors.New("container does not exist")
121 func (v *AzureBlobVolume) Get(loc string) ([]byte, error) {
122 var deadline time.Time
123 haveDeadline := false
124 buf, err := v.get(loc)
125 for err == nil && len(buf) == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
126 // Seeing a brand new empty block probably means we're
127 // in a race with CreateBlob, which under the hood
128 // (apparently) does "CreateEmpty" and "CommitData"
129 // with no additional transaction locking.
131 t, err := v.Mtime(loc)
133 log.Print("Got empty block (possible race) but Mtime failed: ", err)
136 deadline = t.Add(azureWriteRaceInterval)
137 if time.Now().After(deadline) {
140 log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
142 } else if time.Now().After(deadline) {
146 time.Sleep(azureWriteRacePollTime)
147 buf, err = v.get(loc)
150 log.Printf("Race ended with len(buf)==%d", len(buf))
155 func (v *AzureBlobVolume) get(loc string) ([]byte, error) {
156 rdr, err := v.bsClient.GetBlob(v.containerName, loc)
158 return nil, v.translateError(err)
161 buf := bufs.Get(BlockSize)
162 n, err := io.ReadFull(rdr, buf)
164 case nil, io.EOF, io.ErrUnexpectedEOF:
172 func (v *AzureBlobVolume) Compare(loc string, expect []byte) error {
173 rdr, err := v.bsClient.GetBlob(v.containerName, loc)
175 return v.translateError(err)
178 return compareReaderWithBuf(rdr, expect, loc[:32])
181 func (v *AzureBlobVolume) Put(loc string, block []byte) error {
183 return MethodDisabledError
185 return v.bsClient.CreateBlockBlobFromReader(v.containerName, loc, uint64(len(block)), bytes.NewReader(block))
188 func (v *AzureBlobVolume) Touch(loc string) error {
190 return MethodDisabledError
192 return v.bsClient.SetBlobMetadata(v.containerName, loc, map[string]string{
193 "touch": fmt.Sprintf("%d", time.Now()),
197 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
198 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
200 return time.Time{}, err
202 return time.Parse(time.RFC1123, props.LastModified)
205 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
206 params := storage.ListBlobsParameters{
210 resp, err := v.bsClient.ListBlobs(v.containerName, params)
214 for _, b := range resp.Blobs {
215 t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
219 if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
220 // A new zero-length blob is probably
221 // just a new non-empty blob that
222 // hasn't committed its data yet (see
223 // Get()), and in any case has no
227 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.Unix())
229 if resp.NextMarker == "" {
232 params.Marker = resp.NextMarker
236 func (v *AzureBlobVolume) Delete(loc string) error {
238 return MethodDisabledError
240 // Ideally we would use If-Unmodified-Since, but that
241 // particular condition seems to be ignored by Azure. Instead,
242 // we get the Etag before checking Mtime, and use If-Match to
243 // ensure we don't delete data if Put() or Touch() happens
244 // between our calls to Mtime() and DeleteBlob().
245 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
249 if t, err := v.Mtime(loc); err != nil {
251 } else if time.Since(t) < blobSignatureTTL {
254 return v.bsClient.DeleteBlob(v.containerName, loc, map[string]string{
255 "If-Match": props.Etag,
259 func (v *AzureBlobVolume) Status() *VolumeStatus {
260 return &VolumeStatus{
262 BytesFree: BlockSize * 1000,
267 func (v *AzureBlobVolume) String() string {
268 return fmt.Sprintf("azure-storage-container:%+q", v.containerName)
271 func (v *AzureBlobVolume) Writable() bool {
275 func (v *AzureBlobVolume) Replication() int {
279 // If possible, translate an Azure SDK error to a recognizable error
280 // like os.ErrNotExist.
281 func (v *AzureBlobVolume) translateError(err error) error {
285 case strings.Contains(err.Error(), "404 Not Found"):
286 // "storage: service returned without a response body (404 Not Found)"
287 return os.ErrNotExist