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 if strings.Contains(err.Error(), "404 Not Found") {
159 // "storage: service returned without a response body (404 Not Found)"
160 return nil, os.ErrNotExist
164 switch err := err.(type) {
167 log.Printf("ERROR IN Get(): %T %#v", err, err)
171 buf := bufs.Get(BlockSize)
172 n, err := io.ReadFull(rdr, buf)
174 case io.EOF, io.ErrUnexpectedEOF:
182 func (v *AzureBlobVolume) Compare(loc string, expect []byte) error {
183 rdr, err := v.bsClient.GetBlob(v.containerName, loc)
188 return compareReaderWithBuf(rdr, expect, loc[:32])
191 func (v *AzureBlobVolume) Put(loc string, block []byte) error {
193 return MethodDisabledError
195 return v.bsClient.CreateBlockBlobFromReader(v.containerName, loc, uint64(len(block)), bytes.NewReader(block))
198 func (v *AzureBlobVolume) Touch(loc string) error {
200 return MethodDisabledError
202 return v.bsClient.SetBlobMetadata(v.containerName, loc, map[string]string{
203 "touch": fmt.Sprintf("%d", time.Now()),
207 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
208 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
210 return time.Time{}, err
212 return time.Parse(time.RFC1123, props.LastModified)
215 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
216 params := storage.ListBlobsParameters{
220 resp, err := v.bsClient.ListBlobs(v.containerName, params)
224 for _, b := range resp.Blobs {
225 t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
229 if b.Properties.ContentLength == 0 && t.Add(azureWriteRaceInterval).After(time.Now()) {
230 // A new zero-length blob is probably
231 // just a new non-empty blob that
232 // hasn't committed its data yet (see
233 // Get()), and in any case has no
237 fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.Unix())
239 if resp.NextMarker == "" {
242 params.Marker = resp.NextMarker
246 func (v *AzureBlobVolume) Delete(loc string) error {
248 return MethodDisabledError
250 // Ideally we would use If-Unmodified-Since, but that
251 // particular condition seems to be ignored by Azure. Instead,
252 // we get the Etag before checking Mtime, and use If-Match to
253 // ensure we don't delete data if Put() or Touch() happens
254 // between our calls to Mtime() and DeleteBlob().
255 props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
259 if t, err := v.Mtime(loc); err != nil {
261 } else if time.Since(t) < blobSignatureTTL {
264 return v.bsClient.DeleteBlob(v.containerName, loc, map[string]string{
265 "If-Match": props.Etag,
269 func (v *AzureBlobVolume) Status() *VolumeStatus {
270 return &VolumeStatus{
272 BytesFree: BlockSize * 1000,
277 func (v *AzureBlobVolume) String() string {
278 return fmt.Sprintf("azure-storage-container:%+q", v.containerName)
281 func (v *AzureBlobVolume) Writable() bool {
285 func (v *AzureBlobVolume) Replication() int {