16 "github.com/curoverse/azure-sdk-for-go/storage"
20 azureStorageAccountName string
21 azureStorageAccountKeyFile string
22 azureStorageReplication int
23 azureWriteRaceInterval time.Duration = 15 * time.Second
24 azureWriteRacePollTime time.Duration = 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 func NewAzureBlobVolume(client storage.Client, containerName string, readonly bool, replication int) *AzureBlobVolume {
101 return &AzureBlobVolume{
103 bsClient: client.GetBlobService(),
104 containerName: containerName,
106 replication: replication,
110 // Check returns nil if the volume is usable.
111 func (v *AzureBlobVolume) Check() error {
112 ok, err := v.bsClient.ContainerExists(v.containerName)
117 return errors.New("container does not exist")
122 func (v *AzureBlobVolume) Get(loc string) ([]byte, error) {
123 var deadline time.Time
124 haveDeadline := false
125 buf, err := v.get(loc)
126 for err == nil && len(buf) == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
127 // Seeing a brand new empty block probably means we're
128 // in a race with CreateBlob, which under the hood
129 // (apparently) does "CreateEmpty" and "CommitData"
130 // with no additional transaction locking.
132 t, err := v.Mtime(loc)
134 log.Print("Got empty block (possible race) but Mtime failed: ", err)
137 deadline = t.Add(azureWriteRaceInterval)
138 if time.Now().After(deadline) {
141 log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
143 } else if time.Now().After(deadline) {
147 time.Sleep(azureWriteRacePollTime)
148 buf, err = v.get(loc)
151 log.Printf("Race ended with len(buf)==%d", len(buf))
156 func (v *AzureBlobVolume) get(loc string) ([]byte, error) {
157 rdr, err := v.bsClient.GetBlob(v.containerName, loc)
159 return nil, v.translateError(err)
162 buf := bufs.Get(BlockSize)
163 n, err := io.ReadFull(rdr, buf)
165 case nil, io.EOF, io.ErrUnexpectedEOF:
173 func (v *AzureBlobVolume) Compare(loc string, expect []byte) error {
174 rdr, err := v.bsClient.GetBlob(v.containerName, loc)
176 return v.translateError(err)
179 return compareReaderWithBuf(rdr, expect, loc[:32])
182 func (v *AzureBlobVolume) Put(loc string, block []byte) error {
184 return MethodDisabledError
186 return v.bsClient.CreateBlockBlobFromReader(v.containerName, loc, uint64(len(block)), bytes.NewReader(block))
189 func (v *AzureBlobVolume) Touch(loc string) error {
191 return MethodDisabledError
193 return v.bsClient.SetBlobMetadata(v.containerName, loc, map[string]string{
194 "touch": fmt.Sprintf("%d", time.Now()),
198 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
199 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
201 return time.Time{}, err
203 return time.Parse(time.RFC1123, props.LastModified)
206 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
207 params := storage.ListBlobsParameters{
211 resp, err := v.bsClient.ListBlobs(v.containerName, params)
215 for _, b := range resp.Blobs {
216 t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
220 if !v.isKeepBlock(b.Name) {
223 if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
224 // A new zero-length blob is probably
225 // just a new non-empty blob that
226 // hasn't committed its data yet (see
227 // Get()), and in any case has no
231 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.Unix())
233 if resp.NextMarker == "" {
236 params.Marker = resp.NextMarker
240 func (v *AzureBlobVolume) Delete(loc string) error {
242 return MethodDisabledError
244 // Ideally we would use If-Unmodified-Since, but that
245 // particular condition seems to be ignored by Azure. Instead,
246 // we get the Etag before checking Mtime, and use If-Match to
247 // ensure we don't delete data if Put() or Touch() happens
248 // between our calls to Mtime() and DeleteBlob().
249 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
253 if t, err := v.Mtime(loc); err != nil {
255 } else if time.Since(t) < blobSignatureTTL {
258 return v.bsClient.DeleteBlob(v.containerName, loc, map[string]string{
259 "If-Match": props.Etag,
263 func (v *AzureBlobVolume) Status() *VolumeStatus {
264 return &VolumeStatus{
266 BytesFree: BlockSize * 1000,
271 func (v *AzureBlobVolume) String() string {
272 return fmt.Sprintf("azure-storage-container:%+q", v.containerName)
275 func (v *AzureBlobVolume) Writable() bool {
279 func (v *AzureBlobVolume) Replication() int {
283 // If possible, translate an Azure SDK error to a recognizable error
284 // like os.ErrNotExist.
285 func (v *AzureBlobVolume) translateError(err error) error {
289 case strings.Contains(err.Error(), "404 Not Found"):
290 // "storage: service returned without a response body (404 Not Found)"
291 return os.ErrNotExist
297 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
298 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
299 return keepBlockRegexp.MatchString(s)