9068: Move buffer allocation from volumes to GetBlockHandler.
[arvados.git] / services / keepstore / azure_blob_volume.go
index e9fda2ab76dd41c6cdde36cb139e3f3f030c273b..a6b98bd43aa9ce9ee691820695905ca27901d90f 100644 (file)
@@ -11,12 +11,14 @@ import (
        "os"
        "regexp"
        "strings"
+       "sync"
        "time"
 
        "github.com/curoverse/azure-sdk-for-go/storage"
 )
 
 var (
+       azureMaxGetBytes           int
        azureStorageAccountName    string
        azureStorageAccountKeyFile string
        azureStorageReplication    int
@@ -41,6 +43,10 @@ type azureVolumeAdder struct {
 }
 
 func (s *azureVolumeAdder) Set(containerName string) error {
+       if trashLifetime != 0 {
+               return ErrNotImplemented
+       }
+
        if containerName == "" {
                return errors.New("no container name given")
        }
@@ -85,6 +91,11 @@ func init() {
                "azure-storage-replication",
                3,
                "Replication level to report to clients when data is stored in an Azure container.")
+       flag.IntVar(
+               &azureMaxGetBytes,
+               "azure-max-get-bytes",
+               BlockSize,
+               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))
 }
 
 // An AzureBlobVolume stores and retrieves blocks in an Azure Blob
@@ -128,11 +139,11 @@ func (v *AzureBlobVolume) Check() error {
 // If the block is younger than azureWriteRaceInterval and is
 // unexpectedly empty, assume a PutBlob operation is in progress, and
 // wait for it to finish writing.
-func (v *AzureBlobVolume) Get(loc string) ([]byte, error) {
+func (v *AzureBlobVolume) Get(loc string, buf []byte) (int, error) {
        var deadline time.Time
        haveDeadline := false
-       buf, err := v.get(loc)
-       for err == nil && len(buf) == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
+       size, err := v.get(loc, buf)
+       for err == nil && size == 0 && loc != "d41d8cd98f00b204e9800998ecf8427e" {
                // Seeing a brand new empty block probably means we're
                // in a race with CreateBlob, which under the hood
                // (apparently) does "CreateEmpty" and "CommitData"
@@ -152,31 +163,80 @@ func (v *AzureBlobVolume) Get(loc string) ([]byte, error) {
                } else if time.Now().After(deadline) {
                        break
                }
-               bufs.Put(buf)
                time.Sleep(azureWriteRacePollTime)
-               buf, err = v.get(loc)
+               size, err = v.get(loc, buf)
        }
        if haveDeadline {
-               log.Printf("Race ended with len(buf)==%d", len(buf))
+               log.Printf("Race ended with size==%d", size)
        }
-       return buf, err
+       return size, err
 }
 
-func (v *AzureBlobVolume) get(loc string) ([]byte, error) {
-       rdr, err := v.bsClient.GetBlob(v.containerName, loc)
-       if err != nil {
-               return nil, v.translateError(err)
+func (v *AzureBlobVolume) get(loc string, buf []byte) (int, error) {
+       expectSize := len(buf)
+       if azureMaxGetBytes < BlockSize {
+               // Unfortunately the handler doesn't tell us how long the blob
+               // is expected to be, so we have to ask Azure.
+               props, err := v.bsClient.GetBlobProperties(v.containerName, loc)
+               if err != nil {
+                       return 0, v.translateError(err)
+               }
+               if props.ContentLength > int64(BlockSize) || props.ContentLength < 0 {
+                       return 0, fmt.Errorf("block %s invalid size %d (max %d)", loc, props.ContentLength, BlockSize)
+               }
+               expectSize = int(props.ContentLength)
        }
-       defer rdr.Close()
-       buf := bufs.Get(BlockSize)
-       n, err := io.ReadFull(rdr, buf)
-       switch err {
-       case nil, io.EOF, io.ErrUnexpectedEOF:
-               return buf[:n], nil
-       default:
-               bufs.Put(buf)
-               return nil, err
+
+       if expectSize == 0 {
+               return 0, nil
+       }
+
+       // We'll update this actualSize if/when we get the last piece.
+       actualSize := -1
+       pieces := (expectSize + azureMaxGetBytes - 1) / azureMaxGetBytes
+       errors := make([]error, pieces)
+       var wg sync.WaitGroup
+       wg.Add(pieces)
+       for p := 0; p < pieces; p++ {
+               go func(p int) {
+                       defer wg.Done()
+                       startPos := p * azureMaxGetBytes
+                       endPos := startPos + azureMaxGetBytes
+                       if endPos > expectSize {
+                               endPos = expectSize
+                       }
+                       var rdr io.ReadCloser
+                       var err error
+                       if startPos == 0 && endPos == expectSize {
+                               rdr, err = v.bsClient.GetBlob(v.containerName, loc)
+                       } else {
+                               rdr, err = v.bsClient.GetBlobRange(v.containerName, loc, fmt.Sprintf("%d-%d", startPos, endPos-1))
+                       }
+                       if err != nil {
+                               errors[p] = err
+                               return
+                       }
+                       defer rdr.Close()
+                       n, err := io.ReadFull(rdr, buf[startPos:endPos])
+                       if pieces == 1 && (err == io.ErrUnexpectedEOF || err == io.EOF) {
+                               // If we don't know the actual size,
+                               // and just tried reading 64 MiB, it's
+                               // normal to encounter EOF.
+                       } else if err != nil {
+                               errors[p] = err
+                       }
+                       if p == pieces-1 {
+                               actualSize = startPos + n
+                       }
+               }(p)
        }
+       wg.Wait()
+       for _, err := range errors {
+               if err != nil {
+                       return 0, v.translateError(err)
+               }
+       }
+       return actualSize, nil
 }
 
 // Compare the given data with existing stored data.
@@ -189,12 +249,12 @@ func (v *AzureBlobVolume) Compare(loc string, expect []byte) error {
        return compareReaderWithBuf(rdr, expect, loc[:32])
 }
 
-// Put sotres a Keep block as a block blob in the container.
+// Put stores a Keep block as a block blob in the container.
 func (v *AzureBlobVolume) Put(loc string, block []byte) error {
        if v.readonly {
                return MethodDisabledError
        }
-       return v.bsClient.CreateBlockBlobFromReader(v.containerName, loc, uint64(len(block)), bytes.NewReader(block))
+       return v.bsClient.CreateBlockBlobFromReader(v.containerName, loc, uint64(len(block)), bytes.NewReader(block), nil)
 }
 
 // Touch updates the last-modified property of a block blob.
@@ -252,11 +312,16 @@ func (v *AzureBlobVolume) IndexTo(prefix string, writer io.Writer) error {
        }
 }
 
-// Delete a Keep block.
-func (v *AzureBlobVolume) Delete(loc string) error {
+// Trash a Keep block.
+func (v *AzureBlobVolume) Trash(loc string) error {
        if v.readonly {
                return MethodDisabledError
        }
+
+       if trashLifetime != 0 {
+               return ErrNotImplemented
+       }
+
        // Ideally we would use If-Unmodified-Since, but that
        // particular condition seems to be ignored by Azure. Instead,
        // we get the Etag before checking Mtime, and use If-Match to
@@ -276,6 +341,12 @@ func (v *AzureBlobVolume) Delete(loc string) error {
        })
 }
 
+// Untrash a Keep block.
+// TBD
+func (v *AzureBlobVolume) Untrash(loc string) error {
+       return ErrNotImplemented
+}
+
 // Status returns a VolumeStatus struct with placeholder data.
 func (v *AzureBlobVolume) Status() *VolumeStatus {
        return &VolumeStatus{
@@ -317,6 +388,13 @@ func (v *AzureBlobVolume) translateError(err error) error {
 }
 
 var keepBlockRegexp = regexp.MustCompile(`^[0-9a-f]{32}$`)
+
 func (v *AzureBlobVolume) isKeepBlock(s string) bool {
        return keepBlockRegexp.MatchString(s)
 }
+
+// EmptyTrash looks for trashed blocks that exceeded trashLifetime
+// and deletes them from the volume.
+// TBD
+func (v *AzureBlobVolume) EmptyTrash() {
+}