Merge branch '13937-keepstore-prometheus'
[arvados.git] / services / keepstore / azure_blob_volume.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "bytes"
9         "context"
10         "errors"
11         "flag"
12         "fmt"
13         "io"
14         "io/ioutil"
15         "net/http"
16         "os"
17         "regexp"
18         "strconv"
19         "strings"
20         "sync"
21         "sync/atomic"
22         "time"
23
24         "git.curoverse.com/arvados.git/sdk/go/arvados"
25         "github.com/Azure/azure-sdk-for-go/storage"
26         "github.com/prometheus/client_golang/prometheus"
27 )
28
29 const azureDefaultRequestTimeout = arvados.Duration(10 * time.Minute)
30
31 var (
32         azureMaxGetBytes           int
33         azureStorageAccountName    string
34         azureStorageAccountKeyFile string
35         azureStorageReplication    int
36         azureWriteRaceInterval     = 15 * time.Second
37         azureWriteRacePollTime     = time.Second
38 )
39
40 func readKeyFromFile(file string) (string, error) {
41         buf, err := ioutil.ReadFile(file)
42         if err != nil {
43                 return "", errors.New("reading key from " + file + ": " + err.Error())
44         }
45         accountKey := strings.TrimSpace(string(buf))
46         if accountKey == "" {
47                 return "", errors.New("empty account key in " + file)
48         }
49         return accountKey, nil
50 }
51
52 type azureVolumeAdder struct {
53         *Config
54 }
55
56 // String implements flag.Value
57 func (s *azureVolumeAdder) String() string {
58         return "-"
59 }
60
61 func (s *azureVolumeAdder) Set(containerName string) error {
62         s.Config.Volumes = append(s.Config.Volumes, &AzureBlobVolume{
63                 ContainerName:         containerName,
64                 StorageAccountName:    azureStorageAccountName,
65                 StorageAccountKeyFile: azureStorageAccountKeyFile,
66                 AzureReplication:      azureStorageReplication,
67                 ReadOnly:              deprecated.flagReadonly,
68         })
69         return nil
70 }
71
72 func init() {
73         VolumeTypes = append(VolumeTypes, func() VolumeWithExamples { return &AzureBlobVolume{} })
74
75         flag.Var(&azureVolumeAdder{theConfig},
76                 "azure-storage-container-volume",
77                 "Use the given container as a storage volume. Can be given multiple times.")
78         flag.StringVar(
79                 &azureStorageAccountName,
80                 "azure-storage-account-name",
81                 "",
82                 "Azure storage account name used for subsequent --azure-storage-container-volume arguments.")
83         flag.StringVar(
84                 &azureStorageAccountKeyFile,
85                 "azure-storage-account-key-file",
86                 "",
87                 "`File` containing the account key used for subsequent --azure-storage-container-volume arguments.")
88         flag.IntVar(
89                 &azureStorageReplication,
90                 "azure-storage-replication",
91                 3,
92                 "Replication level to report to clients when data is stored in an Azure container.")
93         flag.IntVar(
94                 &azureMaxGetBytes,
95                 "azure-max-get-bytes",
96                 BlockSize,
97                 fmt.Sprintf("Maximum bytes to request in a single GET request. If smaller than %d, use multiple concurrent range requests to retrieve a block.", BlockSize))
98 }
99
100 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
101 // container.
102 type AzureBlobVolume struct {
103         StorageAccountName    string
104         StorageAccountKeyFile string
105         StorageBaseURL        string // "" means default, "core.windows.net"
106         ContainerName         string
107         AzureReplication      int
108         ReadOnly              bool
109         RequestTimeout        arvados.Duration
110         StorageClasses        []string
111
112         azClient  storage.Client
113         container *azureContainer
114 }
115
116 // singleSender is a single-attempt storage.Sender.
117 type singleSender struct{}
118
119 // Send performs req exactly once.
120 func (*singleSender) Send(c *storage.Client, req *http.Request) (resp *http.Response, err error) {
121         return c.HTTPClient.Do(req)
122 }
123
124 // Examples implements VolumeWithExamples.
125 func (*AzureBlobVolume) Examples() []Volume {
126         return []Volume{
127                 &AzureBlobVolume{
128                         StorageAccountName:    "example-account-name",
129                         StorageAccountKeyFile: "/etc/azure_storage_account_key.txt",
130                         ContainerName:         "example-container-name",
131                         AzureReplication:      3,
132                         RequestTimeout:        azureDefaultRequestTimeout,
133                 },
134                 &AzureBlobVolume{
135                         StorageAccountName:    "cn-account-name",
136                         StorageAccountKeyFile: "/etc/azure_cn_storage_account_key.txt",
137                         StorageBaseURL:        "core.chinacloudapi.cn",
138                         ContainerName:         "cn-container-name",
139                         AzureReplication:      3,
140                         RequestTimeout:        azureDefaultRequestTimeout,
141                 },
142         }
143 }
144
145 // Type implements Volume.
146 func (v *AzureBlobVolume) Type() string {
147         return "Azure"
148 }
149
150 // Start implements Volume.
151 func (v *AzureBlobVolume) Start(vm *volumeMetricsVecs) error {
152         if v.ContainerName == "" {
153                 return errors.New("no container name given")
154         }
155         if v.StorageAccountName == "" || v.StorageAccountKeyFile == "" {
156                 return errors.New("StorageAccountName and StorageAccountKeyFile must be given")
157         }
158         accountKey, err := readKeyFromFile(v.StorageAccountKeyFile)
159         if err != nil {
160                 return err
161         }
162         if v.StorageBaseURL == "" {
163                 v.StorageBaseURL = storage.DefaultBaseURL
164         }
165         v.azClient, err = storage.NewClient(v.StorageAccountName, accountKey, v.StorageBaseURL, storage.DefaultAPIVersion, true)
166         if err != nil {
167                 return fmt.Errorf("creating Azure storage client: %s", err)
168         }
169         v.azClient.Sender = &singleSender{}
170
171         if v.RequestTimeout == 0 {
172                 v.RequestTimeout = azureDefaultRequestTimeout
173         }
174         v.azClient.HTTPClient = &http.Client{
175                 Timeout: time.Duration(v.RequestTimeout),
176         }
177         bs := v.azClient.GetBlobService()
178         v.container = &azureContainer{
179                 ctr: bs.GetContainerReference(v.ContainerName),
180         }
181
182         if ok, err := v.container.Exists(); err != nil {
183                 return err
184         } else if !ok {
185                 return fmt.Errorf("Azure container %q does not exist", v.ContainerName)
186         }
187         // Set up prometheus metrics
188         lbls := prometheus.Labels{"device_id": v.DeviceID()}
189         v.container.stats.opsCounters, v.container.stats.errCounters, v.container.stats.ioBytes = vm.getCounterVecsFor(lbls)
190
191         return nil
192 }
193
194 // DeviceID returns a globally unique ID for the storage container.
195 func (v *AzureBlobVolume) DeviceID() string {
196         return "azure://" + v.StorageBaseURL + "/" + v.StorageAccountName + "/" + v.ContainerName
197 }
198
199 // Return true if expires_at metadata attribute is found on the block
200 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
201         metadata, err := v.container.GetBlobMetadata(loc)
202         if err != nil {
203                 return false, metadata, v.translateError(err)
204         }
205         if metadata["expires_at"] != "" {
206                 return true, metadata, nil
207         }
208         return false, metadata, nil
209 }
210
211 // Get reads a Keep block that has been stored as a block blob in the
212 // container.
213 //
214 // If the block is younger than azureWriteRaceInterval and is
215 // unexpectedly empty, assume a PutBlob operation is in progress, and
216 // wait for it to finish writing.
217 func (v *AzureBlobVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
218         trashed, _, err := v.checkTrashed(loc)
219         if err != nil {
220                 return 0, err
221         }
222         if trashed {
223                 return 0, os.ErrNotExist
224         }
225         var deadline time.Time
226         haveDeadline := false
227         size, err := v.get(ctx, loc, buf)
228         for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
229                 // Seeing a brand new empty block probably means we're
230                 // in a race with CreateBlob, which under the hood
231                 // (apparently) does "CreateEmpty" and "CommitData"
232                 // with no additional transaction locking.
233                 if !haveDeadline {
234                         t, err := v.Mtime(loc)
235                         if err != nil {
236                                 log.Print("Got empty block (possible race) but Mtime failed: ", err)
237                                 break
238                         }
239                         deadline = t.Add(azureWriteRaceInterval)
240                         if time.Now().After(deadline) {
241                                 break
242                         }
243                         log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
244                         haveDeadline = true
245                 } else if time.Now().After(deadline) {
246                         break
247                 }
248                 select {
249                 case <-ctx.Done():
250                         return 0, ctx.Err()
251                 case <-time.After(azureWriteRacePollTime):
252                 }
253                 size, err = v.get(ctx, loc, buf)
254         }
255         if haveDeadline {
256                 log.Printf("Race ended with size==%d", size)
257         }
258         return size, err
259 }
260
261 func (v *AzureBlobVolume) get(ctx context.Context, loc string, buf []byte) (int, error) {
262         ctx, cancel := context.WithCancel(ctx)
263         defer cancel()
264         expectSize := len(buf)
265         if azureMaxGetBytes < BlockSize {
266                 // Unfortunately the handler doesn't tell us how long the blob
267                 // is expected to be, so we have to ask Azure.
268                 props, err := v.container.GetBlobProperties(loc)
269                 if err != nil {
270                         return 0, v.translateError(err)
271                 }
272                 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
273                         return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
274                 }
275                 expectSize = int(props.ContentLength)
276         }
277
278         if expectSize == 0 {
279                 return 0, nil
280         }
281
282         // We'll update this actualSize if/when we get the last piece.
283         actualSize := -1
284         pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
285         errors := make(chan error, pieces)
286         var wg sync.WaitGroup
287         wg.Add(pieces)
288         for p := 0; p < pieces; p++ {
289                 // Each goroutine retrieves one piece. If we hit an
290                 // error, it is sent to the errors chan so get() can
291                 // return it -- but only if the error happens before
292                 // ctx is done. This way, if ctx is done before we hit
293                 // any other error (e.g., requesting client has hung
294                 // up), we return the original ctx.Err() instead of
295                 // the secondary errors from the transfers that got
296                 // interrupted as a result.
297                 go func(p int) {
298                         defer wg.Done()
299                         startPos := p * azureMaxGetBytes
300                         endPos := startPos + azureMaxGetBytes
301                         if endPos > expectSize {
302                                 endPos = expectSize
303                         }
304                         var rdr io.ReadCloser
305                         var err error
306                         gotRdr := make(chan struct{})
307                         go func() {
308                                 defer close(gotRdr)
309                                 if startPos == 0 && endPos == expectSize {
310                                         rdr, err = v.container.GetBlob(loc)
311                                 } else {
312                                         rdr, err = v.container.GetBlobRange(loc, startPos, endPos-1, nil)
313                                 }
314                         }()
315                         select {
316                         case <-ctx.Done():
317                                 go func() {
318                                         <-gotRdr
319                                         if err == nil {
320                                                 rdr.Close()
321                                         }
322                                 }()
323                                 return
324                         case <-gotRdr:
325                         }
326                         if err != nil {
327                                 errors <- err
328                                 cancel()
329                                 return
330                         }
331                         go func() {
332                                 // Close the reader when the client
333                                 // hangs up or another piece fails
334                                 // (possibly interrupting ReadFull())
335                                 // or when all pieces succeed and
336                                 // get() returns.
337                                 <-ctx.Done()
338                                 rdr.Close()
339                         }()
340                         n, err := io.ReadFull(rdr, buf[startPos:endPos])
341                         if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
342                                 // If we don't know the actual size,
343                                 // and just tried reading 64 MiB, it's
344                                 // normal to encounter EOF.
345                         } else if err != nil {
346                                 if ctx.Err() == nil {
347                                         errors <- err
348                                 }
349                                 cancel()
350                                 return
351                         }
352                         if p == pieces-1 {
353                                 actualSize = startPos + n
354                         }
355                 }(p)
356         }
357         wg.Wait()
358         close(errors)
359         if len(errors) > 0 {
360                 return 0, v.translateError(<-errors)
361         }
362         if ctx.Err() != nil {
363                 return 0, ctx.Err()
364         }
365         return actualSize, nil
366 }
367
368 // Compare the given data with existing stored data.
369 func (v *AzureBlobVolume) Compare(ctx context.Context, loc string, expect []byte) error {
370         trashed, _, err := v.checkTrashed(loc)
371         if err != nil {
372                 return err
373         }
374         if trashed {
375                 return os.ErrNotExist
376         }
377         var rdr io.ReadCloser
378         gotRdr := make(chan struct{})
379         go func() {
380                 defer close(gotRdr)
381                 rdr, err = v.container.GetBlob(loc)
382         }()
383         select {
384         case <-ctx.Done():
385                 go func() {
386                         <-gotRdr
387                         if err == nil {
388                                 rdr.Close()
389                         }
390                 }()
391                 return ctx.Err()
392         case <-gotRdr:
393         }
394         if err != nil {
395                 return v.translateError(err)
396         }
397         defer rdr.Close()
398         return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
399 }
400
401 // Put stores a Keep block as a block blob in the container.
402 func (v *AzureBlobVolume) Put(ctx context.Context, loc string, block []byte) error {
403         if v.ReadOnly {
404                 return MethodDisabledError
405         }
406         // Send the block data through a pipe, so that (if we need to)
407         // we can close the pipe early and abandon our
408         // CreateBlockBlobFromReader() goroutine, without worrying
409         // about CreateBlockBlobFromReader() accessing our block
410         // buffer after we release it.
411         bufr, bufw := io.Pipe()
412         go func() {
413                 io.Copy(bufw, bytes.NewReader(block))
414                 bufw.Close()
415         }()
416         errChan := make(chan error)
417         go func() {
418                 var body io.Reader = bufr
419                 if len(block) == 0 {
420                         // We must send a "Content-Length: 0" header,
421                         // but the http client interprets
422                         // ContentLength==0 as "unknown" unless it can
423                         // confirm by introspection that Body will
424                         // read 0 bytes.
425                         body = http.NoBody
426                         bufr.Close()
427                 }
428                 errChan <- v.container.CreateBlockBlobFromReader(loc, len(block), body, nil)
429         }()
430         select {
431         case <-ctx.Done():
432                 theConfig.debugLogf("%s: taking CreateBlockBlobFromReader's input away: %s", v, ctx.Err())
433                 // Our pipe might be stuck in Write(), waiting for
434                 // io.Copy() to read. If so, un-stick it. This means
435                 // CreateBlockBlobFromReader will get corrupt data,
436                 // but that's OK: the size won't match, so the write
437                 // will fail.
438                 go io.Copy(ioutil.Discard, bufr)
439                 // CloseWithError() will return once pending I/O is done.
440                 bufw.CloseWithError(ctx.Err())
441                 theConfig.debugLogf("%s: abandoning CreateBlockBlobFromReader goroutine", v)
442                 return ctx.Err()
443         case err := <-errChan:
444                 return err
445         }
446 }
447
448 // Touch updates the last-modified property of a block blob.
449 func (v *AzureBlobVolume) Touch(loc string) error {
450         if v.ReadOnly {
451                 return MethodDisabledError
452         }
453         trashed, metadata, err := v.checkTrashed(loc)
454         if err != nil {
455                 return err
456         }
457         if trashed {
458                 return os.ErrNotExist
459         }
460
461         metadata["touch"] = fmt.Sprintf("%d", time.Now().Unix())
462         return v.container.SetBlobMetadata(loc, metadata, nil)
463 }
464
465 // Mtime returns the last-modified property of a block blob.
466 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
467         trashed, _, err := v.checkTrashed(loc)
468         if err != nil {
469                 return time.Time{}, err
470         }
471         if trashed {
472                 return time.Time{}, os.ErrNotExist
473         }
474
475         props, err := v.container.GetBlobProperties(loc)
476         if err != nil {
477                 return time.Time{}, err
478         }
479         return time.Time(props.LastModified), nil
480 }
481
482 // IndexTo writes a list of Keep blocks that are stored in the
483 // container.
484 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
485         params := storage.ListBlobsParameters{
486                 Prefix:  prefix,
487                 Include: &storage.IncludeBlobDataset{Metadata: true},
488         }
489         for {
490                 resp, err := v.container.ListBlobs(params)
491                 if err != nil {
492                         return err
493                 }
494                 for _, b := range resp.Blobs {
495                         if !v.isKeepBlock(b.Name) {
496                                 continue
497                         }
498                         modtime := time.Time(b.Properties.LastModified)
499                         if b.Properties.ContentLength == 0 && modtime.Add(azureWriteRaceInterval).After(time.Now()) {
500                                 // A new zero-length blob is probably
501                                 // just a new non-empty blob that
502                                 // hasn't committed its data yet (see
503                                 // Get()), and in any case has no
504                                 // value.
505                                 continue
506                         }
507                         if b.Metadata["expires_at"] != "" {
508                                 // Trashed blob; exclude it from response
509                                 continue
510                         }
511                         fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, modtime.UnixNano())
512                 }
513                 if resp.NextMarker == "" {
514                         return nil
515                 }
516                 params.Marker = resp.NextMarker
517         }
518 }
519
520 // Trash a Keep block.
521 func (v *AzureBlobVolume) Trash(loc string) error {
522         if v.ReadOnly {
523                 return MethodDisabledError
524         }
525
526         // Ideally we would use If-Unmodified-Since, but that
527         // particular condition seems to be ignored by Azure. Instead,
528         // we get the Etag before checking Mtime, and use If-Match to
529         // ensure we don't delete data if Put() or Touch() happens
530         // between our calls to Mtime() and DeleteBlob().
531         props, err := v.container.GetBlobProperties(loc)
532         if err != nil {
533                 return err
534         }
535         if t, err := v.Mtime(loc); err != nil {
536                 return err
537         } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
538                 return nil
539         }
540
541         // If TrashLifetime == 0, just delete it
542         if theConfig.TrashLifetime == 0 {
543                 return v.container.DeleteBlob(loc, &storage.DeleteBlobOptions{
544                         IfMatch: props.Etag,
545                 })
546         }
547
548         // Otherwise, mark as trash
549         return v.container.SetBlobMetadata(loc, storage.BlobMetadata{
550                 "expires_at": fmt.Sprintf("%d", time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()),
551         }, &storage.SetBlobMetadataOptions{
552                 IfMatch: props.Etag,
553         })
554 }
555
556 // Untrash a Keep block.
557 // Delete the expires_at metadata attribute
558 func (v *AzureBlobVolume) Untrash(loc string) error {
559         // if expires_at does not exist, return NotFoundError
560         metadata, err := v.container.GetBlobMetadata(loc)
561         if err != nil {
562                 return v.translateError(err)
563         }
564         if metadata["expires_at"] == "" {
565                 return os.ErrNotExist
566         }
567
568         // reset expires_at metadata attribute
569         metadata["expires_at"] = ""
570         err = v.container.SetBlobMetadata(loc, metadata, nil)
571         return v.translateError(err)
572 }
573
574 // Status returns a VolumeStatus struct with placeholder data.
575 func (v *AzureBlobVolume) Status() *VolumeStatus {
576         return &VolumeStatus{
577                 DeviceNum: 1,
578                 BytesFree: BlockSize * 1000,
579                 BytesUsed: 1,
580         }
581 }
582
583 // String returns a volume label, including the container name.
584 func (v *AzureBlobVolume) String() string {
585         return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
586 }
587
588 // Writable returns true, unless the -readonly flag was on when the
589 // volume was added.
590 func (v *AzureBlobVolume) Writable() bool {
591         return !v.ReadOnly
592 }
593
594 // Replication returns the replication level of the container, as
595 // specified by the -azure-storage-replication argument.
596 func (v *AzureBlobVolume) Replication() int {
597         return v.AzureReplication
598 }
599
600 // GetStorageClasses implements Volume
601 func (v *AzureBlobVolume) GetStorageClasses() []string {
602         return v.StorageClasses
603 }
604
605 // If possible, translate an Azure SDK error to a recognizable error
606 // like os.ErrNotExist.
607 func (v *AzureBlobVolume) translateError(err error) error {
608         switch {
609         case err == nil:
610                 return err
611         case strings.Contains(err.Error(), "StatusCode=503"):
612                 // "storage: service returned error: StatusCode=503, ErrorCode=ServerBusy, ErrorMessage=The server is busy" (See #14804)
613                 return VolumeBusyError
614         case strings.Contains(err.Error(), "Not Found"):
615                 // "storage: service returned without a response body (404 Not Found)"
616                 return os.ErrNotExist
617         default:
618                 return err
619         }
620 }
621
622 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
623
624 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
625         return keepBlockRegexp.MatchString(s)
626 }
627
628 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
629 // and deletes them from the volume.
630 func (v *AzureBlobVolume) EmptyTrash() {
631         var bytesDeleted, bytesInTrash int64
632         var blocksDeleted, blocksInTrash int64
633
634         doBlob := func(b storage.Blob) {
635                 // Check whether the block is flagged as trash
636                 if b.Metadata["expires_at"] == "" {
637                         return
638                 }
639
640                 atomic.AddInt64(&blocksInTrash, 1)
641                 atomic.AddInt64(&bytesInTrash, b.Properties.ContentLength)
642
643                 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
644                 if err != nil {
645                         log.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
646                         return
647                 }
648
649                 if expiresAt > time.Now().Unix() {
650                         return
651                 }
652
653                 err = v.container.DeleteBlob(b.Name, &storage.DeleteBlobOptions{
654                         IfMatch: b.Properties.Etag,
655                 })
656                 if err != nil {
657                         log.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
658                         return
659                 }
660                 atomic.AddInt64(&blocksDeleted, 1)
661                 atomic.AddInt64(&bytesDeleted, b.Properties.ContentLength)
662         }
663
664         var wg sync.WaitGroup
665         todo := make(chan storage.Blob, theConfig.EmptyTrashWorkers)
666         for i := 0; i < 1 || i < theConfig.EmptyTrashWorkers; i++ {
667                 wg.Add(1)
668                 go func() {
669                         defer wg.Done()
670                         for b := range todo {
671                                 doBlob(b)
672                         }
673                 }()
674         }
675
676         params := storage.ListBlobsParameters{Include: &storage.IncludeBlobDataset{Metadata: true}}
677         for {
678                 resp, err := v.container.ListBlobs(params)
679                 if err != nil {
680                         log.Printf("EmptyTrash: ListBlobs: %v", err)
681                         break
682                 }
683                 for _, b := range resp.Blobs {
684                         todo <- b
685                 }
686                 if resp.NextMarker == "" {
687                         break
688                 }
689                 params.Marker = resp.NextMarker
690         }
691         close(todo)
692         wg.Wait()
693
694         log.Printf("EmptyTrash stats for %v: Deleted %v bytes in %v blocks. Remaining in trash: %v bytes in %v blocks.", v.String(), bytesDeleted, blocksDeleted, bytesInTrash-bytesDeleted, blocksInTrash-blocksDeleted)
695 }
696
697 // InternalStats returns bucket I/O and API call counters.
698 func (v *AzureBlobVolume) InternalStats() interface{} {
699         return &v.container.stats
700 }
701
702 type azureBlobStats struct {
703         statsTicker
704         Ops              uint64
705         GetOps           uint64
706         GetRangeOps      uint64
707         GetMetadataOps   uint64
708         GetPropertiesOps uint64
709         CreateOps        uint64
710         SetMetadataOps   uint64
711         DelOps           uint64
712         ListOps          uint64
713 }
714
715 func (s *azureBlobStats) TickErr(err error) {
716         if err == nil {
717                 return
718         }
719         errType := fmt.Sprintf("%T", err)
720         if err, ok := err.(storage.AzureStorageServiceError); ok {
721                 errType = errType + fmt.Sprintf(" %d (%s)", err.StatusCode, err.Code)
722         }
723         log.Printf("errType %T, err %s", err, err)
724         s.statsTicker.TickErr(err, errType)
725 }
726
727 // azureContainer wraps storage.Container in order to count I/O and
728 // API usage stats.
729 type azureContainer struct {
730         ctr   *storage.Container
731         stats azureBlobStats
732 }
733
734 func (c *azureContainer) Exists() (bool, error) {
735         c.stats.TickOps("exists")
736         c.stats.Tick(&c.stats.Ops)
737         ok, err := c.ctr.Exists()
738         c.stats.TickErr(err)
739         return ok, err
740 }
741
742 func (c *azureContainer) GetBlobMetadata(bname string) (storage.BlobMetadata, error) {
743         c.stats.TickOps("get_metadata")
744         c.stats.Tick(&c.stats.Ops, &c.stats.GetMetadataOps)
745         b := c.ctr.GetBlobReference(bname)
746         err := b.GetMetadata(nil)
747         c.stats.TickErr(err)
748         return b.Metadata, err
749 }
750
751 func (c *azureContainer) GetBlobProperties(bname string) (*storage.BlobProperties, error) {
752         c.stats.TickOps("get_properties")
753         c.stats.Tick(&c.stats.Ops, &c.stats.GetPropertiesOps)
754         b := c.ctr.GetBlobReference(bname)
755         err := b.GetProperties(nil)
756         c.stats.TickErr(err)
757         return &b.Properties, err
758 }
759
760 func (c *azureContainer) GetBlob(bname string) (io.ReadCloser, error) {
761         c.stats.TickOps("get")
762         c.stats.Tick(&c.stats.Ops, &c.stats.GetOps)
763         b := c.ctr.GetBlobReference(bname)
764         rdr, err := b.Get(nil)
765         c.stats.TickErr(err)
766         return NewCountingReader(rdr, c.stats.TickInBytes), err
767 }
768
769 func (c *azureContainer) GetBlobRange(bname string, start, end int, opts *storage.GetBlobOptions) (io.ReadCloser, error) {
770         c.stats.TickOps("get_range")
771         c.stats.Tick(&c.stats.Ops, &c.stats.GetRangeOps)
772         b := c.ctr.GetBlobReference(bname)
773         rdr, err := b.GetRange(&storage.GetBlobRangeOptions{
774                 Range: &storage.BlobRange{
775                         Start: uint64(start),
776                         End:   uint64(end),
777                 },
778                 GetBlobOptions: opts,
779         })
780         c.stats.TickErr(err)
781         return NewCountingReader(rdr, c.stats.TickInBytes), err
782 }
783
784 // If we give it an io.Reader that doesn't also have a Len() int
785 // method, the Azure SDK determines data size by copying the data into
786 // a new buffer, which is not a good use of memory.
787 type readerWithAzureLen struct {
788         io.Reader
789         len int
790 }
791
792 // Len satisfies the private lener interface in azure-sdk-for-go.
793 func (r *readerWithAzureLen) Len() int {
794         return r.len
795 }
796
797 func (c *azureContainer) CreateBlockBlobFromReader(bname string, size int, rdr io.Reader, opts *storage.PutBlobOptions) error {
798         c.stats.TickOps("create")
799         c.stats.Tick(&c.stats.Ops, &c.stats.CreateOps)
800         if size != 0 {
801                 rdr = &readerWithAzureLen{
802                         Reader: NewCountingReader(rdr, c.stats.TickOutBytes),
803                         len:    size,
804                 }
805         }
806         b := c.ctr.GetBlobReference(bname)
807         err := b.CreateBlockBlobFromReader(rdr, opts)
808         c.stats.TickErr(err)
809         return err
810 }
811
812 func (c *azureContainer) SetBlobMetadata(bname string, m storage.BlobMetadata, opts *storage.SetBlobMetadataOptions) error {
813         c.stats.TickOps("set_metadata")
814         c.stats.Tick(&c.stats.Ops, &c.stats.SetMetadataOps)
815         b := c.ctr.GetBlobReference(bname)
816         b.Metadata = m
817         err := b.SetMetadata(opts)
818         c.stats.TickErr(err)
819         return err
820 }
821
822 func (c *azureContainer) ListBlobs(params storage.ListBlobsParameters) (storage.BlobListResponse, error) {
823         c.stats.TickOps("list")
824         c.stats.Tick(&c.stats.Ops, &c.stats.ListOps)
825         resp, err := c.ctr.ListBlobs(params)
826         c.stats.TickErr(err)
827         return resp, err
828 }
829
830 func (c *azureContainer) DeleteBlob(bname string, opts *storage.DeleteBlobOptions) error {
831         c.stats.TickOps("delete")
832         c.stats.Tick(&c.stats.Ops, &c.stats.DelOps)
833         b := c.ctr.GetBlobReference(bname)
834         err := b.Delete(opts)
835         c.stats.TickErr(err)
836         return err
837 }