13937: Simplified volume specific metric handling (WIP)
[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(opsCounters, errCounters, ioBytes *prometheus.CounterVec) 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         return nil
188 }
189
190 // DeviceID returns a globally unique ID for the storage container.
191 func (v *AzureBlobVolume) DeviceID() string {
192         return "azure://" + v.StorageBaseURL + "/" + v.StorageAccountName + "/" + v.ContainerName
193 }
194
195 // Return true if expires_at metadata attribute is found on the block
196 func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, error) {
197         metadata, err := v.container.GetBlobMetadata(loc)
198         if err != nil {
199                 return false, metadata, v.translateError(err)
200         }
201         if metadata["expires_at"] != "" {
202                 return true, metadata, nil
203         }
204         return false, metadata, nil
205 }
206
207 // Get reads a Keep block that has been stored as a block blob in the
208 // container.
209 //
210 // If the block is younger than azureWriteRaceInterval and is
211 // unexpectedly empty, assume a PutBlob operation is in progress, and
212 // wait for it to finish writing.
213 func (v *AzureBlobVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
214         trashed, _, err := v.checkTrashed(loc)
215         if err != nil {
216                 return 0, err
217         }
218         if trashed {
219                 return 0, os.ErrNotExist
220         }
221         var deadline time.Time
222         haveDeadline := false
223         size, err := v.get(ctx, loc, buf)
224         for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
225                 // Seeing a brand new empty block probably means we're
226                 // in a race with CreateBlob, which under the hood
227                 // (apparently) does "CreateEmpty" and "CommitData"
228                 // with no additional transaction locking.
229                 if !haveDeadline {
230                         t, err := v.Mtime(loc)
231                         if err != nil {
232                                 log.Print("Got empty block (possible race) but Mtime failed: ", err)
233                                 break
234                         }
235                         deadline = t.Add(azureWriteRaceInterval)
236                         if time.Now().After(deadline) {
237                                 break
238                         }
239                         log.Printf("Race? Block %s is 0 bytes, %s old. Polling until %s", loc, time.Since(t), deadline)
240                         haveDeadline = true
241                 } else if time.Now().After(deadline) {
242                         break
243                 }
244                 select {
245                 case <-ctx.Done():
246                         return 0, ctx.Err()
247                 case <-time.After(azureWriteRacePollTime):
248                 }
249                 size, err = v.get(ctx, loc, buf)
250         }
251         if haveDeadline {
252                 log.Printf("Race ended with size==%d", size)
253         }
254         return size, err
255 }
256
257 func (v *AzureBlobVolume) get(ctx context.Context, loc string, buf []byte) (int, error) {
258         ctx, cancel := context.WithCancel(ctx)
259         defer cancel()
260         expectSize := len(buf)
261         if azureMaxGetBytes < BlockSize {
262                 // Unfortunately the handler doesn't tell us how long the blob
263                 // is expected to be, so we have to ask Azure.
264                 props, err := v.container.GetBlobProperties(loc)
265                 if err != nil {
266                         return 0, v.translateError(err)
267                 }
268                 if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
269                         return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
270                 }
271                 expectSize = int(props.ContentLength)
272         }
273
274         if expectSize == 0 {
275                 return 0, nil
276         }
277
278         // We'll update this actualSize if/when we get the last piece.
279         actualSize := -1
280         pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
281         errors := make(chan error, pieces)
282         var wg sync.WaitGroup
283         wg.Add(pieces)
284         for p := 0; p < pieces; p++ {
285                 // Each goroutine retrieves one piece. If we hit an
286                 // error, it is sent to the errors chan so get() can
287                 // return it -- but only if the error happens before
288                 // ctx is done. This way, if ctx is done before we hit
289                 // any other error (e.g., requesting client has hung
290                 // up), we return the original ctx.Err() instead of
291                 // the secondary errors from the transfers that got
292                 // interrupted as a result.
293                 go func(p int) {
294                         defer wg.Done()
295                         startPos := p * azureMaxGetBytes
296                         endPos := startPos + azureMaxGetBytes
297                         if endPos > expectSize {
298                                 endPos = expectSize
299                         }
300                         var rdr io.ReadCloser
301                         var err error
302                         gotRdr := make(chan struct{})
303                         go func() {
304                                 defer close(gotRdr)
305                                 if startPos == 0 && endPos == expectSize {
306                                         rdr, err = v.container.GetBlob(loc)
307                                 } else {
308                                         rdr, err = v.container.GetBlobRange(loc, startPos, endPos-1, nil)
309                                 }
310                         }()
311                         select {
312                         case <-ctx.Done():
313                                 go func() {
314                                         <-gotRdr
315                                         if err == nil {
316                                                 rdr.Close()
317                                         }
318                                 }()
319                                 return
320                         case <-gotRdr:
321                         }
322                         if err != nil {
323                                 errors <- err
324                                 cancel()
325                                 return
326                         }
327                         go func() {
328                                 // Close the reader when the client
329                                 // hangs up or another piece fails
330                                 // (possibly interrupting ReadFull())
331                                 // or when all pieces succeed and
332                                 // get() returns.
333                                 <-ctx.Done()
334                                 rdr.Close()
335                         }()
336                         n, err := io.ReadFull(rdr, buf[startPos:endPos])
337                         if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
338                                 // If we don't know the actual size,
339                                 // and just tried reading 64 MiB, it's
340                                 // normal to encounter EOF.
341                         } else if err != nil {
342                                 if ctx.Err() == nil {
343                                         errors <- err
344                                 }
345                                 cancel()
346                                 return
347                         }
348                         if p == pieces-1 {
349                                 actualSize = startPos + n
350                         }
351                 }(p)
352         }
353         wg.Wait()
354         close(errors)
355         if len(errors) > 0 {
356                 return 0, v.translateError(<-errors)
357         }
358         if ctx.Err() != nil {
359                 return 0, ctx.Err()
360         }
361         return actualSize, nil
362 }
363
364 // Compare the given data with existing stored data.
365 func (v *AzureBlobVolume) Compare(ctx context.Context, loc string, expect []byte) error {
366         trashed, _, err := v.checkTrashed(loc)
367         if err != nil {
368                 return err
369         }
370         if trashed {
371                 return os.ErrNotExist
372         }
373         var rdr io.ReadCloser
374         gotRdr := make(chan struct{})
375         go func() {
376                 defer close(gotRdr)
377                 rdr, err = v.container.GetBlob(loc)
378         }()
379         select {
380         case <-ctx.Done():
381                 go func() {
382                         <-gotRdr
383                         if err == nil {
384                                 rdr.Close()
385                         }
386                 }()
387                 return ctx.Err()
388         case <-gotRdr:
389         }
390         if err != nil {
391                 return v.translateError(err)
392         }
393         defer rdr.Close()
394         return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
395 }
396
397 // Put stores a Keep block as a block blob in the container.
398 func (v *AzureBlobVolume) Put(ctx context.Context, loc string, block []byte) error {
399         if v.ReadOnly {
400                 return MethodDisabledError
401         }
402         // Send the block data through a pipe, so that (if we need to)
403         // we can close the pipe early and abandon our
404         // CreateBlockBlobFromReader() goroutine, without worrying
405         // about CreateBlockBlobFromReader() accessing our block
406         // buffer after we release it.
407         bufr, bufw := io.Pipe()
408         go func() {
409                 io.Copy(bufw, bytes.NewReader(block))
410                 bufw.Close()
411         }()
412         errChan := make(chan error)
413         go func() {
414                 var body io.Reader = bufr
415                 if len(block) == 0 {
416                         // We must send a "Content-Length: 0" header,
417                         // but the http client interprets
418                         // ContentLength==0 as "unknown" unless it can
419                         // confirm by introspection that Body will
420                         // read 0 bytes.
421                         body = http.NoBody
422                         bufr.Close()
423                 }
424                 errChan <- v.container.CreateBlockBlobFromReader(loc, len(block), body, nil)
425         }()
426         select {
427         case <-ctx.Done():
428                 theConfig.debugLogf("%s: taking CreateBlockBlobFromReader's input away: %s", v, ctx.Err())
429                 // Our pipe might be stuck in Write(), waiting for
430                 // io.Copy() to read. If so, un-stick it. This means
431                 // CreateBlockBlobFromReader will get corrupt data,
432                 // but that's OK: the size won't match, so the write
433                 // will fail.
434                 go io.Copy(ioutil.Discard, bufr)
435                 // CloseWithError() will return once pending I/O is done.
436                 bufw.CloseWithError(ctx.Err())
437                 theConfig.debugLogf("%s: abandoning CreateBlockBlobFromReader goroutine", v)
438                 return ctx.Err()
439         case err := <-errChan:
440                 return err
441         }
442 }
443
444 // Touch updates the last-modified property of a block blob.
445 func (v *AzureBlobVolume) Touch(loc string) error {
446         if v.ReadOnly {
447                 return MethodDisabledError
448         }
449         trashed, metadata, err := v.checkTrashed(loc)
450         if err != nil {
451                 return err
452         }
453         if trashed {
454                 return os.ErrNotExist
455         }
456
457         metadata["touch"] = fmt.Sprintf("%d", time.Now().Unix())
458         return v.container.SetBlobMetadata(loc, metadata, nil)
459 }
460
461 // Mtime returns the last-modified property of a block blob.
462 func (v *AzureBlobVolume) Mtime(loc string) (time.Time, error) {
463         trashed, _, err := v.checkTrashed(loc)
464         if err != nil {
465                 return time.Time{}, err
466         }
467         if trashed {
468                 return time.Time{}, os.ErrNotExist
469         }
470
471         props, err := v.container.GetBlobProperties(loc)
472         if err != nil {
473                 return time.Time{}, err
474         }
475         return time.Time(props.LastModified), nil
476 }
477
478 // IndexTo writes a list of Keep blocks that are stored in the
479 // container.
480 func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
481         params := storage.ListBlobsParameters{
482                 Prefix:  prefix,
483                 Include: &storage.IncludeBlobDataset{Metadata: true},
484         }
485         for {
486                 resp, err := v.container.ListBlobs(params)
487                 if err != nil {
488                         return err
489                 }
490                 for _, b := range resp.Blobs {
491                         if !v.isKeepBlock(b.Name) {
492                                 continue
493                         }
494                         modtime := time.Time(b.Properties.LastModified)
495                         if b.Properties.ContentLength == 0 && modtime.Add(azureWriteRaceInterval).After(time.Now()) {
496                                 // A new zero-length blob is probably
497                                 // just a new non-empty blob that
498                                 // hasn't committed its data yet (see
499                                 // Get()), and in any case has no
500                                 // value.
501                                 continue
502                         }
503                         if b.Metadata["expires_at"] != "" {
504                                 // Trashed blob; exclude it from response
505                                 continue
506                         }
507                         fmt.Fprintf(writer, "%s+%d %d\n", b.Name, b.Properties.ContentLength, modtime.UnixNano())
508                 }
509                 if resp.NextMarker == "" {
510                         return nil
511                 }
512                 params.Marker = resp.NextMarker
513         }
514 }
515
516 // Trash a Keep block.
517 func (v *AzureBlobVolume) Trash(loc string) error {
518         if v.ReadOnly {
519                 return MethodDisabledError
520         }
521
522         // Ideally we would use If-Unmodified-Since, but that
523         // particular condition seems to be ignored by Azure. Instead,
524         // we get the Etag before checking Mtime, and use If-Match to
525         // ensure we don't delete data if Put() or Touch() happens
526         // between our calls to Mtime() and DeleteBlob().
527         props, err := v.container.GetBlobProperties(loc)
528         if err != nil {
529                 return err
530         }
531         if t, err := v.Mtime(loc); err != nil {
532                 return err
533         } else if time.Since(t) < theConfig.BlobSignatureTTL.Duration() {
534                 return nil
535         }
536
537         // If TrashLifetime == 0, just delete it
538         if theConfig.TrashLifetime == 0 {
539                 return v.container.DeleteBlob(loc, &storage.DeleteBlobOptions{
540                         IfMatch: props.Etag,
541                 })
542         }
543
544         // Otherwise, mark as trash
545         return v.container.SetBlobMetadata(loc, storage.BlobMetadata{
546                 "expires_at": fmt.Sprintf("%d", time.Now().Add(theConfig.TrashLifetime.Duration()).Unix()),
547         }, &storage.SetBlobMetadataOptions{
548                 IfMatch: props.Etag,
549         })
550 }
551
552 // Untrash a Keep block.
553 // Delete the expires_at metadata attribute
554 func (v *AzureBlobVolume) Untrash(loc string) error {
555         // if expires_at does not exist, return NotFoundError
556         metadata, err := v.container.GetBlobMetadata(loc)
557         if err != nil {
558                 return v.translateError(err)
559         }
560         if metadata["expires_at"] == "" {
561                 return os.ErrNotExist
562         }
563
564         // reset expires_at metadata attribute
565         metadata["expires_at"] = ""
566         err = v.container.SetBlobMetadata(loc, metadata, nil)
567         return v.translateError(err)
568 }
569
570 // Status returns a VolumeStatus struct with placeholder data.
571 func (v *AzureBlobVolume) Status() *VolumeStatus {
572         return &VolumeStatus{
573                 DeviceNum: 1,
574                 BytesFree: BlockSize * 1000,
575                 BytesUsed: 1,
576         }
577 }
578
579 // String returns a volume label, including the container name.
580 func (v *AzureBlobVolume) String() string {
581         return fmt.Sprintf("azure-storage-container:%+q", v.ContainerName)
582 }
583
584 // Writable returns true, unless the -readonly flag was on when the
585 // volume was added.
586 func (v *AzureBlobVolume) Writable() bool {
587         return !v.ReadOnly
588 }
589
590 // Replication returns the replication level of the container, as
591 // specified by the -azure-storage-replication argument.
592 func (v *AzureBlobVolume) Replication() int {
593         return v.AzureReplication
594 }
595
596 // GetStorageClasses implements Volume
597 func (v *AzureBlobVolume) GetStorageClasses() []string {
598         return v.StorageClasses
599 }
600
601 // If possible, translate an Azure SDK error to a recognizable error
602 // like os.ErrNotExist.
603 func (v *AzureBlobVolume) translateError(err error) error {
604         switch {
605         case err == nil:
606                 return err
607         case strings.Contains(err.Error(), "Not Found"):
608                 // "storage: service returned without a response body (404 Not Found)"
609                 return os.ErrNotExist
610         default:
611                 return err
612         }
613 }
614
615 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
616
617 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
618         return keepBlockRegexp.MatchString(s)
619 }
620
621 // EmptyTrash looks for trashed blocks that exceeded TrashLifetime
622 // and deletes them from the volume.
623 func (v *AzureBlobVolume) EmptyTrash() {
624         var bytesDeleted, bytesInTrash int64
625         var blocksDeleted, blocksInTrash int64
626
627         doBlob := func(b storage.Blob) {
628                 // Check whether the block is flagged as trash
629                 if b.Metadata["expires_at"] == "" {
630                         return
631                 }
632
633                 atomic.AddInt64(&blocksInTrash, 1)
634                 atomic.AddInt64(&bytesInTrash, b.Properties.ContentLength)
635
636                 expiresAt, err := strconv.ParseInt(b.Metadata["expires_at"], 10, 64)
637                 if err != nil {
638                         log.Printf("EmptyTrash: ParseInt(%v): %v", b.Metadata["expires_at"], err)
639                         return
640                 }
641
642                 if expiresAt > time.Now().Unix() {
643                         return
644                 }
645
646                 err = v.container.DeleteBlob(b.Name, &storage.DeleteBlobOptions{
647                         IfMatch: b.Properties.Etag,
648                 })
649                 if err != nil {
650                         log.Printf("EmptyTrash: DeleteBlob(%v): %v", b.Name, err)
651                         return
652                 }
653                 atomic.AddInt64(&blocksDeleted, 1)
654                 atomic.AddInt64(&bytesDeleted, b.Properties.ContentLength)
655         }
656
657         var wg sync.WaitGroup
658         todo := make(chan storage.Blob, theConfig.EmptyTrashWorkers)
659         for i := 0; i < 1 || i < theConfig.EmptyTrashWorkers; i++ {
660                 wg.Add(1)
661                 go func() {
662                         defer wg.Done()
663                         for b := range todo {
664                                 doBlob(b)
665                         }
666                 }()
667         }
668
669         params := storage.ListBlobsParameters{Include: &storage.IncludeBlobDataset{Metadata: true}}
670         for {
671                 resp, err := v.container.ListBlobs(params)
672                 if err != nil {
673                         log.Printf("EmptyTrash: ListBlobs: %v", err)
674                         break
675                 }
676                 for _, b := range resp.Blobs {
677                         todo <- b
678                 }
679                 if resp.NextMarker == "" {
680                         break
681                 }
682                 params.Marker = resp.NextMarker
683         }
684         close(todo)
685         wg.Wait()
686
687         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)
688 }
689
690 // InternalStats returns bucket I/O and API call counters.
691 func (v *AzureBlobVolume) InternalStats() interface{} {
692         return &v.container.stats
693 }
694
695 type azureBlobStats struct {
696         statsTicker
697         Ops              uint64
698         GetOps           uint64
699         GetRangeOps      uint64
700         GetMetadataOps   uint64
701         GetPropertiesOps uint64
702         CreateOps        uint64
703         SetMetadataOps   uint64
704         DelOps           uint64
705         ListOps          uint64
706 }
707
708 func (s *azureBlobStats) TickErr(err error) {
709         if err == nil {
710                 return
711         }
712         errType := fmt.Sprintf("%T", err)
713         if err, ok := err.(storage.AzureStorageServiceError); ok {
714                 errType = errType + fmt.Sprintf(" %d (%s)", err.StatusCode, err.Code)
715         }
716         log.Printf("errType %T, err %s", err, err)
717         s.statsTicker.TickErr(err, errType)
718 }
719
720 // azureContainer wraps storage.Container in order to count I/O and
721 // API usage stats.
722 type azureContainer struct {
723         ctr   *storage.Container
724         stats azureBlobStats
725 }
726
727 func (c *azureContainer) Exists() (bool, error) {
728         c.stats.Tick(&c.stats.Ops)
729         ok, err := c.ctr.Exists()
730         c.stats.TickErr(err)
731         return ok, err
732 }
733
734 func (c *azureContainer) GetBlobMetadata(bname string) (storage.BlobMetadata, error) {
735         c.stats.Tick(&c.stats.Ops, &c.stats.GetMetadataOps)
736         b := c.ctr.GetBlobReference(bname)
737         err := b.GetMetadata(nil)
738         c.stats.TickErr(err)
739         return b.Metadata, err
740 }
741
742 func (c *azureContainer) GetBlobProperties(bname string) (*storage.BlobProperties, error) {
743         c.stats.Tick(&c.stats.Ops, &c.stats.GetPropertiesOps)
744         b := c.ctr.GetBlobReference(bname)
745         err := b.GetProperties(nil)
746         c.stats.TickErr(err)
747         return &b.Properties, err
748 }
749
750 func (c *azureContainer) GetBlob(bname string) (io.ReadCloser, error) {
751         c.stats.Tick(&c.stats.Ops, &c.stats.GetOps)
752         b := c.ctr.GetBlobReference(bname)
753         rdr, err := b.Get(nil)
754         c.stats.TickErr(err)
755         return NewCountingReader(rdr, c.stats.TickInBytes), err
756 }
757
758 func (c *azureContainer) GetBlobRange(bname string, start, end int, opts *storage.GetBlobOptions) (io.ReadCloser, error) {
759         c.stats.Tick(&c.stats.Ops, &c.stats.GetRangeOps)
760         b := c.ctr.GetBlobReference(bname)
761         rdr, err := b.GetRange(&storage.GetBlobRangeOptions{
762                 Range: &storage.BlobRange{
763                         Start: uint64(start),
764                         End:   uint64(end),
765                 },
766                 GetBlobOptions: opts,
767         })
768         c.stats.TickErr(err)
769         return NewCountingReader(rdr, c.stats.TickInBytes), err
770 }
771
772 // If we give it an io.Reader that doesn't also have a Len() int
773 // method, the Azure SDK determines data size by copying the data into
774 // a new buffer, which is not a good use of memory.
775 type readerWithAzureLen struct {
776         io.Reader
777         len int
778 }
779
780 // Len satisfies the private lener interface in azure-sdk-for-go.
781 func (r *readerWithAzureLen) Len() int {
782         return r.len
783 }
784
785 func (c *azureContainer) CreateBlockBlobFromReader(bname string, size int, rdr io.Reader, opts *storage.PutBlobOptions) error {
786         c.stats.Tick(&c.stats.Ops, &c.stats.CreateOps)
787         if size != 0 {
788                 rdr = &readerWithAzureLen{
789                         Reader: NewCountingReader(rdr, c.stats.TickOutBytes),
790                         len:    size,
791                 }
792         }
793         b := c.ctr.GetBlobReference(bname)
794         err := b.CreateBlockBlobFromReader(rdr, opts)
795         c.stats.TickErr(err)
796         return err
797 }
798
799 func (c *azureContainer) SetBlobMetadata(bname string, m storage.BlobMetadata, opts *storage.SetBlobMetadataOptions) error {
800         c.stats.Tick(&c.stats.Ops, &c.stats.SetMetadataOps)
801         b := c.ctr.GetBlobReference(bname)
802         b.Metadata = m
803         err := b.SetMetadata(opts)
804         c.stats.TickErr(err)
805         return err
806 }
807
808 func (c *azureContainer) ListBlobs(params storage.ListBlobsParameters) (storage.BlobListResponse, error) {
809         c.stats.Tick(&c.stats.Ops, &c.stats.ListOps)
810         resp, err := c.ctr.ListBlobs(params)
811         c.stats.TickErr(err)
812         return resp, err
813 }
814
815 func (c *azureContainer) DeleteBlob(bname string, opts *storage.DeleteBlobOptions) error {
816         c.stats.Tick(&c.stats.Ops, &c.stats.DelOps)
817         b := c.ctr.GetBlobReference(bname)
818         err := b.Delete(opts)
819         c.stats.TickErr(err)
820         return err
821 }