Merge branch '6321-slurm-oserror' closes #6321
[arvados.git] / services / keepstore / azure_blob_volume.go
1 package main
2
3 import (
4         "bytes"
5         "errors"
6         "flag"
7         "fmt"
8         "io"
9         "io/ioutil"
10         "log"
11         "os"
12         "regexp"
13         "strings"
14         "time"
15
16         "github.com/curoverse/azure-sdk-for-go/storage"
17 )
18
19 var (
20         azureStorageAccountName    string
21         azureStorageAccountKeyFile string
22         azureStorageReplication    int
23         azureWriteRaceInterval     = 15 * time.Second
24         azureWriteRacePollTime     = time.Second
25 )
26
27 func readKeyFromFile(file string) (string, error) {
28         buf, err := ioutil.ReadFile(file)
29         if err != nil {
30                 return "", errors.New("reading key from " + file + ": " + err.Error())
31         }
32         accountKey := strings.TrimSpace(string(buf))
33         if accountKey == "" {
34                 return "", errors.New("empty account key in " + file)
35         }
36         return accountKey, nil
37 }
38
39 type azureVolumeAdder struct {
40         *volumeSet
41 }
42
43 func (s *azureVolumeAdder) Set(containerName string) error {
44         if containerName == "" {
45                 return errors.New("no container name given")
46         }
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")
49         }
50         accountKey, err := readKeyFromFile(azureStorageAccountKeyFile)
51         if err != nil {
52                 return err
53         }
54         azClient, err := storage.NewBasicClient(azureStorageAccountName, accountKey)
55         if err != nil {
56                 return errors.New("creating Azure storage client: " + err.Error())
57         }
58         if flagSerializeIO {
59                 log.Print("Notice: -serialize is not supported by azure-blob-container volumes.")
60         }
61         v := NewAzureBlobVolume(azClient, containerName, flagReadonly, azureStorageReplication)
62         if err := v.Check(); err != nil {
63                 return err
64         }
65         *s.volumeSet = append(*s.volumeSet, v)
66         return nil
67 }
68
69 func init() {
70         flag.Var(&azureVolumeAdder{&volumes},
71                 "azure-storage-container-volume",
72                 "Use the given container as a storage volume. Can be given multiple times.")
73         flag.StringVar(
74                 &azureStorageAccountName,
75                 "azure-storage-account-name",
76                 "",
77                 "Azure storage account name used for subsequent --azure-storage-container-volume arguments.")
78         flag.StringVar(
79                 &azureStorageAccountKeyFile,
80                 "azure-storage-account-key-file",
81                 "",
82                 "File containing the account key used for subsequent --azure-storage-container-volume arguments.")
83         flag.IntVar(
84                 &azureStorageReplication,
85                 "azure-storage-replication",
86                 3,
87                 "Replication level to report to clients when data is stored in an Azure container.")
88 }
89
90 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
91 // container.
92 type AzureBlobVolume struct {
93         azClient      storage.Client
94         bsClient      storage.BlobStorageClient
95         containerName string
96         readonly      bool
97         replication   int
98 }
99
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{
105                 azClient:      client,
106                 bsClient:      client.GetBlobService(),
107                 containerName: containerName,
108                 readonly:      readonly,
109                 replication:   replication,
110         }
111 }
112
113 // Check returns nil if the volume is usable.
114 func (v *AzureBlobVolume) Check() error {
115         ok, err := v.bsClient.ContainerExists(v.containerName)
116         if err != nil {
117                 return err
118         }
119         if !ok {
120                 return errors.New("container does not exist")
121         }
122         return nil
123 }
124
125 // Get reads a Keep block that has been stored as a block blob in the
126 // container.
127 //
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.
140                 if !haveDeadline {
141                         t, err := v.Mtime(loc)
142                         if err != nil {
143                                 log.Print("Got empty block (possible race) but Mtime failed: ", err)
144                                 break
145                         }
146                         deadline = t.Add(azureWriteRaceInterval)
147                         if time.Now().After(deadline) {
148                                 break
149                         }
150                         log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
151                         haveDeadline = true
152                 } else if time.Now().After(deadline) {
153                         break
154                 }
155                 bufs.Put(buf)
156                 time.Sleep(azureWriteRacePollTime)
157                 buf, err = v.get(loc)
158         }
159         if haveDeadline {
160                 log.Printf("Race ended with len(buf)==%d", len(buf))
161         }
162         return buf, err
163 }
164
165 func (v *AzureBlobVolume) get(loc string) ([]byte, error) {
166         rdr, err := v.bsClient.GetBlob(v.containerName, loc)
167         if err != nil {
168                 return nil, v.translateError(err)
169         }
170         defer rdr.Close()
171         buf := bufs.Get(BlockSize)
172         n, err := io.ReadFull(rdr, buf)
173         switch err {
174         case nil, io.EOF, io.ErrUnexpectedEOF:
175                 return buf[:n], nil
176         default:
177                 bufs.Put(buf)
178                 return nil, err
179         }
180 }
181
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)
185         if err != nil {
186                 return v.translateError(err)
187         }
188         defer rdr.Close()
189         return compareReaderWithBuf(rdr, expect, loc[:32])
190 }
191
192 // Put sotres a Keep block as a block blob in the container.
193 func (v *AzureBlobVolume) Put(loc string, block []byte) error {
194         if v.readonly {
195                 return MethodDisabledError
196         }
197         return v.bsClient.CreateBlockBlobFromReader(v.containerName, loc, uint64(len(block)), bytes.NewReader(block))
198 }
199
200 // Touch updates the last-modified property of a block blob.
201 func (v *AzureBlobVolume) Touch(loc string) error {
202         if v.readonly {
203                 return MethodDisabledError
204         }
205         return v.bsClient.SetBlobMetadata(v.containerName, loc, map[string]string{
206                 "touch": fmt.Sprintf("%d", time.Now()),
207         })
208 }
209
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)
213         if err != nil {
214                 return time.Time{}, err
215         }
216         return time.Parse(time.RFC1123, props.LastModified)
217 }
218
219 // IndexTo writes a list of Keep blocks that are stored in the
220 // container.
221 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
222         params := storage.ListBlobsParameters{
223                 Prefix: prefix,
224         }
225         for {
226                 resp, err := v.bsClient.ListBlobs(v.containerName, params)
227                 if err != nil {
228                         return err
229                 }
230                 for _, b := range resp.Blobs {
231                         t, err := time.Parse(time.RFC1123, b.Properties.LastModified)
232                         if err != nil {
233                                 return err
234                         }
235                         if !v.isKeepBlock(b.Name) {
236                                 continue
237                         }
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
243                                 // value.
244                                 continue
245                         }
246                         fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, t.Unix())
247                 }
248                 if resp.NextMarker == "" {
249                         return nil
250                 }
251                 params.Marker = resp.NextMarker
252         }
253 }
254
255 // Delete a Keep block.
256 func (v *AzureBlobVolume) Delete(loc string) error {
257         if v.readonly {
258                 return MethodDisabledError
259         }
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)
266         if err != nil {
267                 return err
268         }
269         if t, err := v.Mtime(loc); err != nil {
270                 return err
271         } else if time.Since(t) < blobSignatureTTL {
272                 return nil
273         }
274         return v.bsClient.DeleteBlob(v.containerName, loc, map[string]string{
275                 "If-Match": props.Etag,
276         })
277 }
278
279 // Status returns a VolumeStatus struct with placeholder data.
280 func (v *AzureBlobVolume) Status() *VolumeStatus {
281         return &VolumeStatus{
282                 DeviceNum: 1,
283                 BytesFree: BlockSize * 1000,
284                 BytesUsed: 1,
285         }
286 }
287
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)
291 }
292
293 // Writable returns true, unless the -readonly flag was on when the
294 // volume was added.
295 func (v *AzureBlobVolume) Writable() bool {
296         return !v.readonly
297 }
298
299 // Replication returns the replication level of the container, as
300 // specified by the -azure-storage-replication argument.
301 func (v *AzureBlobVolume) Replication() int {
302         return v.replication
303 }
304
305 // If possible, translate an Azure SDK error to a recognizable error
306 // like os.ErrNotExist.
307 func (v *AzureBlobVolume) translateError(err error) error {
308         switch {
309         case err == nil:
310                 return err
311         case strings.Contains(err.Error(), "404 Not Found"):
312                 // "storage: service returned without a response body (404 Not Found)"
313                 return os.ErrNotExist
314         default:
315                 return err
316         }
317 }
318
319 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
320 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
321         return keepBlockRegexp.MatchString(s)
322 }