10467: Merge branch 'master' into 10467-client-disconnect
authorTom Clegg <tom@curoverse.com>
Tue, 8 Nov 2016 20:37:26 +0000 (15:37 -0500)
committerTom Clegg <tom@curoverse.com>
Tue, 8 Nov 2016 20:37:26 +0000 (15:37 -0500)
19 files changed:
build/run-tests.sh
services/keepstore/azure_blob_volume.go
services/keepstore/azure_blob_volume_test.go
services/keepstore/collision.go
services/keepstore/config.go
services/keepstore/config_test.go [new file with mode: 0644]
services/keepstore/handler_test.go
services/keepstore/handlers.go
services/keepstore/handlers_with_generic_volume_test.go
services/keepstore/keepstore_test.go
services/keepstore/pull_worker.go
services/keepstore/s3_volume.go
services/keepstore/s3_volume_test.go
services/keepstore/trash_worker_test.go
services/keepstore/volume.go
services/keepstore/volume_generic_test.go
services/keepstore/volume_test.go
services/keepstore/volume_unix.go
services/keepstore/volume_unix_test.go

index fa608738c7e63cd3aa24ad8457fafc7bed829e84..8959cfbe09c3ea7ac6ded2142b626259787d2121 100755 (executable)
@@ -159,8 +159,8 @@ sanity_checks() {
     echo -n 'go: '
     go version \
         || fatal "No go binary. See http://golang.org/doc/install"
-    [[ $(go version) =~ go1.([0-9]+) ]] && [[ ${BASH_REMATCH[1]} -ge 6 ]] \
-        || fatal "Go >= 1.6 required. See http://golang.org/doc/install"
+    [[ $(go version) =~ go1.([0-9]+) ]] && [[ ${BASH_REMATCH[1]} -ge 7 ]] \
+        || fatal "Go >= 1.7 required. See http://golang.org/doc/install"
     echo -n 'gcc: '
     gcc --version | egrep ^gcc \
         || fatal "No gcc. Try: apt-get install build-essential"
index d2c4620066cf7f88d8374f5331e64e822df760be..6ca31c38329ec7347631a03c802b4216bd05f167 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bytes"
+       "context"
        "errors"
        "flag"
        "fmt"
@@ -176,7 +177,7 @@ func (v *AzureBlobVolume) checkTrashed(loc string) (bool, map[string]string, err
 // 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, buf []byte) (int, error) {
+func (v *AzureBlobVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
        trashed, _, err := v.checkTrashed(loc)
        if err != nil {
                return 0, err
@@ -284,7 +285,7 @@ func (v *AzureBlobVolume) get(loc string, buf []byte) (int, error) {
 }
 
 // Compare the given data with existing stored data.
-func (v *AzureBlobVolume) Compare(loc string, expect []byte) error {
+func (v *AzureBlobVolume) Compare(ctx context.Context, loc string, expect []byte) error {
        trashed, _, err := v.checkTrashed(loc)
        if err != nil {
                return err
@@ -297,11 +298,11 @@ func (v *AzureBlobVolume) Compare(loc string, expect []byte) error {
                return v.translateError(err)
        }
        defer rdr.Close()
-       return compareReaderWithBuf(rdr, expect, loc[:32])
+       return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
 }
 
 // Put stores a Keep block as a block blob in the container.
-func (v *AzureBlobVolume) Put(loc string, block []byte) error {
+func (v *AzureBlobVolume) Put(ctx context.Context, loc string, block []byte) error {
        if v.ReadOnly {
                return MethodDisabledError
        }
index c8c898fe2da3957e3efdf069c5370e146ac5d693..d636a5ee86887806372a14e2f291e5c4f2c11b33 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bytes"
+       "context"
        "crypto/md5"
        "encoding/base64"
        "encoding/xml"
@@ -454,12 +455,12 @@ func TestAzureBlobVolumeRangeFenceposts(t *testing.T) {
                        data[i] = byte((i + 7) & 0xff)
                }
                hash := fmt.Sprintf("%x", md5.Sum(data))
-               err := v.Put(hash, data)
+               err := v.Put(context.Background(), hash, data)
                if err != nil {
                        t.Error(err)
                }
                gotData := make([]byte, len(data))
-               gotLen, err := v.Get(hash, gotData)
+               gotLen, err := v.Get(context.Background(), hash, gotData)
                if err != nil {
                        t.Error(err)
                }
@@ -500,7 +501,7 @@ func TestAzureBlobVolumeCreateBlobRace(t *testing.T) {
        allDone := make(chan struct{})
        v.azHandler.race = make(chan chan struct{})
        go func() {
-               err := v.Put(TestHash, TestBlock)
+               err := v.Put(context.Background(), TestHash, TestBlock)
                if err != nil {
                        t.Error(err)
                }
@@ -510,7 +511,7 @@ func TestAzureBlobVolumeCreateBlobRace(t *testing.T) {
        v.azHandler.race <- continuePut
        go func() {
                buf := make([]byte, len(TestBlock))
-               _, err := v.Get(TestHash, buf)
+               _, err := v.Get(context.Background(), TestHash, buf)
                if err != nil {
                        t.Error(err)
                }
@@ -553,7 +554,7 @@ func TestAzureBlobVolumeCreateBlobRaceDeadline(t *testing.T) {
        go func() {
                defer close(allDone)
                buf := make([]byte, BlockSize)
-               n, err := v.Get(TestHash, buf)
+               n, err := v.Get(context.Background(), TestHash, buf)
                if err != nil {
                        t.Error(err)
                        return
index a4af563729b3cf0e72686a2913fd3664e497e24d..82cb789eb954c289172ac478dc04392a14c6a989 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bytes"
+       "context"
        "crypto/md5"
        "fmt"
        "io"
@@ -49,7 +50,7 @@ func collisionOrCorrupt(expectMD5 string, buf1, buf2 []byte, rdr io.Reader) erro
        return <-outcome
 }
 
-func compareReaderWithBuf(rdr io.Reader, expect []byte, hash string) error {
+func compareReaderWithBuf(ctx context.Context, rdr io.Reader, expect []byte, hash string) error {
        bufLen := 1 << 20
        if bufLen > len(expect) && len(expect) > 0 {
                // No need for bufLen to be longer than
@@ -67,7 +68,18 @@ func compareReaderWithBuf(rdr io.Reader, expect []byte, hash string) error {
        // expected to equal the next N bytes read from
        // rdr.
        for {
-               n, err := rdr.Read(buf)
+               ready := make(chan bool)
+               var n int
+               var err error
+               go func() {
+                       n, err = rdr.Read(buf)
+                       close(ready)
+               }()
+               select {
+               case <-ready:
+               case <-ctx.Done():
+                       return ctx.Err()
+               }
                if n > len(cmp) || bytes.Compare(cmp[:n], buf[:n]) != 0 {
                        return collisionOrCorrupt(hash, expect[:len(expect)-len(cmp)], buf[:n], rdr)
                }
index 9c318d1245abcb285634ed46eaf17ddcabe300b2..dc06ef549877ba0316294e4a0e7767393ef4436d 100644 (file)
@@ -13,6 +13,7 @@ import (
 )
 
 type Config struct {
+       Debug  bool
        Listen string
 
        PIDFile string
@@ -32,6 +33,7 @@ type Config struct {
 
        blobSigningKey  []byte
        systemAuthToken string
+       debugLogf       func(string, ...interface{})
 }
 
 var theConfig = DefaultConfig()
@@ -52,6 +54,13 @@ func DefaultConfig() *Config {
 // Start should be called exactly once: after setting all public
 // fields, and before using the config.
 func (cfg *Config) Start() error {
+       if cfg.Debug {
+               cfg.debugLogf = log.Printf
+               cfg.debugLogf("debugging enabled")
+       } else {
+               cfg.debugLogf = func(string, ...interface{}) {}
+       }
+
        if cfg.MaxBuffers < 0 {
                return fmt.Errorf("MaxBuffers must be greater than zero")
        }
diff --git a/services/keepstore/config_test.go b/services/keepstore/config_test.go
new file mode 100644 (file)
index 0000000..eaa0904
--- /dev/null
@@ -0,0 +1,9 @@
+package main
+
+import (
+       "log"
+)
+
+func init() {
+       theConfig.debugLogf = log.Printf
+}
index dc9bcb117f0508e748a97ff3cb2a736aa5c00178..9708b4e6be32f96645d500dfcd4319972f213d47 100644 (file)
@@ -11,6 +11,7 @@ package main
 
 import (
        "bytes"
+       "context"
        "encoding/json"
        "fmt"
        "net/http"
@@ -48,7 +49,7 @@ func TestGetHandler(t *testing.T) {
        defer KeepVM.Close()
 
        vols := KeepVM.AllWritable()
-       if err := vols[0].Put(TestHash, TestBlock); err != nil {
+       if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
                t.Error(err)
        }
 
@@ -288,10 +289,10 @@ func TestIndexHandler(t *testing.T) {
        defer KeepVM.Close()
 
        vols := KeepVM.AllWritable()
-       vols[0].Put(TestHash, TestBlock)
-       vols[1].Put(TestHash2, TestBlock2)
-       vols[0].Put(TestHash+".meta", []byte("metadata"))
-       vols[1].Put(TestHash2+".meta", []byte("metadata"))
+       vols[0].Put(context.Background(), TestHash, TestBlock)
+       vols[1].Put(context.Background(), TestHash2, TestBlock2)
+       vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
+       vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
 
        theConfig.systemAuthToken = "DATA MANAGER TOKEN"
 
@@ -477,7 +478,7 @@ func TestDeleteHandler(t *testing.T) {
        defer KeepVM.Close()
 
        vols := KeepVM.AllWritable()
-       vols[0].Put(TestHash, TestBlock)
+       vols[0].Put(context.Background(), TestHash, TestBlock)
 
        // Explicitly set the BlobSignatureTTL to 0 for these
        // tests, to ensure the MockVolume deletes the blocks
@@ -564,7 +565,7 @@ func TestDeleteHandler(t *testing.T) {
        }
        // Confirm the block has been deleted
        buf := make([]byte, BlockSize)
-       _, err := vols[0].Get(TestHash, buf)
+       _, err := vols[0].Get(context.Background(), TestHash, buf)
        var blockDeleted = os.IsNotExist(err)
        if !blockDeleted {
                t.Error("superuserExistingBlockReq: block not deleted")
@@ -572,7 +573,7 @@ func TestDeleteHandler(t *testing.T) {
 
        // A DELETE request on a block newer than BlobSignatureTTL
        // should return success but leave the block on the volume.
-       vols[0].Put(TestHash, TestBlock)
+       vols[0].Put(context.Background(), TestHash, TestBlock)
        theConfig.BlobSignatureTTL = arvados.Duration(time.Hour)
 
        response = IssueRequest(superuserExistingBlockReq)
@@ -588,7 +589,7 @@ func TestDeleteHandler(t *testing.T) {
                        expectedDc, responseDc)
        }
        // Confirm the block has NOT been deleted.
-       _, err = vols[0].Get(TestHash, buf)
+       _, err = vols[0].Get(context.Background(), TestHash, buf)
        if err != nil {
                t.Errorf("testing delete on new block: %s\n", err)
        }
@@ -940,7 +941,7 @@ func TestGetHandlerClientDisconnect(t *testing.T) {
        KeepVM = MakeTestVolumeManager(2)
        defer KeepVM.Close()
 
-       if err := KeepVM.AllWritable()[0].Put(TestHash, TestBlock); err != nil {
+       if err := KeepVM.AllWritable()[0].Put(context.Background(), TestHash, TestBlock); err != nil {
                t.Error(err)
        }
 
@@ -985,7 +986,7 @@ func TestGetHandlerNoBufferLeak(t *testing.T) {
        defer KeepVM.Close()
 
        vols := KeepVM.AllWritable()
-       if err := vols[0].Put(TestHash, TestBlock); err != nil {
+       if err := vols[0].Put(context.Background(), TestHash, TestBlock); err != nil {
                t.Error(err)
        }
 
@@ -1040,7 +1041,7 @@ func TestUntrashHandler(t *testing.T) {
        KeepVM = MakeTestVolumeManager(2)
        defer KeepVM.Close()
        vols := KeepVM.AllWritable()
-       vols[0].Put(TestHash, TestBlock)
+       vols[0].Put(context.Background(), TestHash, TestBlock)
 
        theConfig.systemAuthToken = "DATA MANAGER TOKEN"
 
index 54b8b485e1dc99d491bd94d4b5b888b60b990b13..289dce15a06168572f5269d7fed82bdb31a75075 100644 (file)
@@ -9,6 +9,7 @@ package main
 
 import (
        "container/list"
+       "context"
        "crypto/md5"
        "encoding/json"
        "fmt"
@@ -71,6 +72,9 @@ func BadRequestHandler(w http.ResponseWriter, r *http.Request) {
 
 // GetBlockHandler is a HandleFunc to address Get block requests.
 func GetBlockHandler(resp http.ResponseWriter, req *http.Request) {
+       ctx, cancel := contextForResponse(context.TODO(), resp)
+       defer cancel()
+
        if theConfig.RequireSignatures {
                locator := req.URL.Path[1:] // strip leading slash
                if err := VerifySignature(locator, GetAPIToken(req)); err != nil {
@@ -86,14 +90,14 @@ func GetBlockHandler(resp http.ResponseWriter, req *http.Request) {
        // isn't here, we can return 404 now instead of waiting for a
        // buffer.
 
-       buf, err := getBufferForResponseWriter(resp, bufs, BlockSize)
+       buf, err := getBufferWithContext(ctx, bufs, BlockSize)
        if err != nil {
                http.Error(resp, err.Error(), http.StatusServiceUnavailable)
                return
        }
        defer bufs.Put(buf)
 
-       size, err := GetBlock(mux.Vars(req)["hash"], buf, resp)
+       size, err := GetBlock(ctx, mux.Vars(req)["hash"], buf, resp)
        if err != nil {
                code := http.StatusInternalServerError
                if err, ok := err.(*KeepError); ok {
@@ -108,24 +112,33 @@ func GetBlockHandler(resp http.ResponseWriter, req *http.Request) {
        resp.Write(buf[:size])
 }
 
+// Return a new context that gets cancelled by resp's CloseNotifier.
+func contextForResponse(parent context.Context, resp http.ResponseWriter) (context.Context, context.CancelFunc) {
+       ctx, cancel := context.WithCancel(parent)
+       if cn, ok := resp.(http.CloseNotifier); ok {
+               go func(c <-chan bool) {
+                       select {
+                       case <-c:
+                               theConfig.debugLogf("cancel context")
+                               cancel()
+                       case <-ctx.Done():
+                       }
+               }(cn.CloseNotify())
+       }
+       return ctx, cancel
+}
+
 // Get a buffer from the pool -- but give up and return a non-nil
-// error if resp implements http.CloseNotifier and tells us that the
-// client has disconnected before we get a buffer.
-func getBufferForResponseWriter(resp http.ResponseWriter, bufs *bufferPool, bufSize int) ([]byte, error) {
-       var closeNotifier <-chan bool
-       if resp, ok := resp.(http.CloseNotifier); ok {
-               closeNotifier = resp.CloseNotify()
-       }
-       var buf []byte
+// error if ctx ends before we get a buffer.
+func getBufferWithContext(ctx context.Context, bufs *bufferPool, bufSize int) ([]byte, error) {
        bufReady := make(chan []byte)
        go func() {
                bufReady <- bufs.Get(bufSize)
-               close(bufReady)
        }()
        select {
-       case buf = <-bufReady:
+       case buf := <-bufReady:
                return buf, nil
-       case <-closeNotifier:
+       case <-ctx.Done():
                go func() {
                        // Even if closeNotifier happened first, we
                        // need to keep waiting for our buf so we can
@@ -138,6 +151,9 @@ func getBufferForResponseWriter(resp http.ResponseWriter, bufs *bufferPool, bufS
 
 // PutBlockHandler is a HandleFunc to address Put block requests.
 func PutBlockHandler(resp http.ResponseWriter, req *http.Request) {
+       ctx, cancel := contextForResponse(context.TODO(), resp)
+       defer cancel()
+
        hash := mux.Vars(req)["hash"]
 
        // Detect as many error conditions as possible before reading
@@ -159,7 +175,7 @@ func PutBlockHandler(resp http.ResponseWriter, req *http.Request) {
                return
        }
 
-       buf, err := getBufferForResponseWriter(resp, bufs, int(req.ContentLength))
+       buf, err := getBufferWithContext(ctx, bufs, int(req.ContentLength))
        if err != nil {
                http.Error(resp, err.Error(), http.StatusServiceUnavailable)
                return
@@ -172,12 +188,15 @@ func PutBlockHandler(resp http.ResponseWriter, req *http.Request) {
                return
        }
 
-       replication, err := PutBlock(buf, hash)
+       replication, err := PutBlock(ctx, buf, hash)
        bufs.Put(buf)
 
        if err != nil {
-               ke := err.(*KeepError)
-               http.Error(resp, ke.Error(), ke.HTTPCode)
+               code := http.StatusInternalServerError
+               if err, ok := err.(*KeepError); ok {
+                       code = err.HTTPCode
+               }
+               http.Error(resp, err.Error(), code)
                return
        }
 
@@ -548,12 +567,17 @@ func UntrashHandler(resp http.ResponseWriter, req *http.Request) {
 // If the block found does not have the correct MD5 hash, returns
 // DiskHashError.
 //
-func GetBlock(hash string, buf []byte, resp http.ResponseWriter) (int, error) {
+func GetBlock(ctx context.Context, hash string, buf []byte, resp http.ResponseWriter) (int, error) {
        // Attempt to read the requested hash from a keep volume.
        errorToCaller := NotFoundError
 
        for _, vol := range KeepVM.AllReadable() {
-               size, err := vol.Get(hash, buf)
+               size, err := vol.Get(ctx, hash, buf)
+               select {
+               case <-ctx.Done():
+                       return 0, ErrClientDisconnect
+               default:
+               }
                if err != nil {
                        // IsNotExist is an expected error and may be
                        // ignored. All other errors are logged. In
@@ -587,7 +611,7 @@ func GetBlock(hash string, buf []byte, resp http.ResponseWriter) (int, error) {
 
 // PutBlock Stores the BLOCK (identified by the content id HASH) in Keep.
 //
-// PutBlock(block, hash)
+// PutBlock(ctx, block, hash)
 //   Stores the BLOCK (identified by the content id HASH) in Keep.
 //
 //   The MD5 checksum of the block must be identical to the content id HASH.
@@ -612,7 +636,7 @@ func GetBlock(hash string, buf []byte, resp http.ResponseWriter) (int, error) {
 //          all writes failed). The text of the error message should
 //          provide as much detail as possible.
 //
-func PutBlock(block []byte, hash string) (int, error) {
+func PutBlock(ctx context.Context, block []byte, hash string) (int, error) {
        // Check that BLOCK's checksum matches HASH.
        blockhash := fmt.Sprintf("%x", md5.Sum(block))
        if blockhash != hash {
@@ -623,16 +647,21 @@ func PutBlock(block []byte, hash string) (int, error) {
        // If we already have this data, it's intact on disk, and we
        // can update its timestamp, return success. If we have
        // different data with the same hash, return failure.
-       if n, err := CompareAndTouch(hash, block); err == nil || err == CollisionError {
+       if n, err := CompareAndTouch(ctx, hash, block); err == nil || err == CollisionError {
                return n, err
+       } else if ctx.Err() != nil {
+               return 0, ErrClientDisconnect
        }
 
        // Choose a Keep volume to write to.
        // If this volume fails, try all of the volumes in order.
        if vol := KeepVM.NextWritable(); vol != nil {
-               if err := vol.Put(hash, block); err == nil {
+               if err := vol.Put(ctx, hash, block); err == nil {
                        return vol.Replication(), nil // success!
                }
+               if ctx.Err() != nil {
+                       return 0, ErrClientDisconnect
+               }
        }
 
        writables := KeepVM.AllWritable()
@@ -643,7 +672,10 @@ func PutBlock(block []byte, hash string) (int, error) {
 
        allFull := true
        for _, vol := range writables {
-               err := vol.Put(hash, block)
+               err := vol.Put(ctx, hash, block)
+               if ctx.Err() != nil {
+                       return 0, ErrClientDisconnect
+               }
                if err == nil {
                        return vol.Replication(), nil // success!
                }
@@ -669,10 +701,13 @@ func PutBlock(block []byte, hash string) (int, error) {
 // the relevant block's modification time in order to protect it from
 // premature garbage collection. Otherwise, it returns a non-nil
 // error.
-func CompareAndTouch(hash string, buf []byte) (int, error) {
+func CompareAndTouch(ctx context.Context, hash string, buf []byte) (int, error) {
        var bestErr error = NotFoundError
        for _, vol := range KeepVM.AllWritable() {
-               if err := vol.Compare(hash, buf); err == CollisionError {
+               err := vol.Compare(ctx, hash, buf)
+               if ctx.Err() != nil {
+                       return 0, ctx.Err()
+               } else if err == CollisionError {
                        // Stop if we have a block with same hash but
                        // different content. (It will be impossible
                        // to tell which one is wanted if we have
index dda7edcec3509e683465a93d5eb775bf18f16d19..181e651d3b4bbef40fa146b8fe06e6b93c206b05 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bytes"
+       "context"
 )
 
 // A TestableVolumeManagerFactory creates a volume manager with at least two TestableVolume instances.
@@ -46,7 +47,7 @@ func testGetBlock(t TB, factory TestableVolumeManagerFactory, testHash string, t
 
        // Get should pass
        buf := make([]byte, len(testBlock))
-       n, err := GetBlock(testHash, buf, nil)
+       n, err := GetBlock(context.Background(), testHash, buf, nil)
        if err != nil {
                t.Fatalf("Error while getting block %s", err)
        }
@@ -66,7 +67,7 @@ func testPutRawBadDataGetBlock(t TB, factory TestableVolumeManagerFactory,
 
        // Get should fail
        buf := make([]byte, BlockSize)
-       size, err := GetBlock(testHash, buf, nil)
+       size, err := GetBlock(context.Background(), testHash, buf, nil)
        if err == nil {
                t.Fatalf("Got %+q, expected error while getting corrupt block %v", buf[:size], testHash)
        }
@@ -77,18 +78,18 @@ func testPutBlock(t TB, factory TestableVolumeManagerFactory, testHash string, t
        setupHandlersWithGenericVolumeTest(t, factory)
 
        // PutBlock
-       if _, err := PutBlock(testBlock, testHash); err != nil {
+       if _, err := PutBlock(context.Background(), testBlock, testHash); err != nil {
                t.Fatalf("Error during PutBlock: %s", err)
        }
 
        // Check that PutBlock succeeds again even after CompareAndTouch
-       if _, err := PutBlock(testBlock, testHash); err != nil {
+       if _, err := PutBlock(context.Background(), testBlock, testHash); err != nil {
                t.Fatalf("Error during PutBlock: %s", err)
        }
 
        // Check that PutBlock stored the data as expected
        buf := make([]byte, BlockSize)
-       size, err := GetBlock(testHash, buf, nil)
+       size, err := GetBlock(context.Background(), testHash, buf, nil)
        if err != nil {
                t.Fatalf("Error during GetBlock for %q: %s", testHash, err)
        } else if bytes.Compare(buf[:size], testBlock) != 0 {
@@ -106,14 +107,14 @@ func testPutBlockCorrupt(t TB, factory TestableVolumeManagerFactory,
        testableVolumes[1].PutRaw(testHash, badData)
 
        // Check that PutBlock with good data succeeds
-       if _, err := PutBlock(testBlock, testHash); err != nil {
+       if _, err := PutBlock(context.Background(), testBlock, testHash); err != nil {
                t.Fatalf("Error during PutBlock for %q: %s", testHash, err)
        }
 
        // Put succeeded and overwrote the badData in one volume,
        // and Get should return the testBlock now, ignoring the bad data.
        buf := make([]byte, BlockSize)
-       size, err := GetBlock(testHash, buf, nil)
+       size, err := GetBlock(context.Background(), testHash, buf, nil)
        if err != nil {
                t.Fatalf("Error during GetBlock for %q: %s", testHash, err)
        } else if bytes.Compare(buf[:size], testBlock) != 0 {
index dc6af0fa0d651c79cd6694a006fd3ad83ba2d677..e1d1dc5cb3cf2eb6ed3bf0b1da0a18b154f03328 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bytes"
+       "context"
        "fmt"
        "io/ioutil"
        "os"
@@ -61,13 +62,13 @@ func TestGetBlock(t *testing.T) {
        defer KeepVM.Close()
 
        vols := KeepVM.AllReadable()
-       if err := vols[1].Put(TestHash, TestBlock); err != nil {
+       if err := vols[1].Put(context.Background(), TestHash, TestBlock); err != nil {
                t.Error(err)
        }
 
        // Check that GetBlock returns success.
        buf := make([]byte, BlockSize)
-       size, err := GetBlock(TestHash, buf, nil)
+       size, err := GetBlock(context.Background(), TestHash, buf, nil)
        if err != nil {
                t.Errorf("GetBlock error: %s", err)
        }
@@ -88,7 +89,7 @@ func TestGetBlockMissing(t *testing.T) {
 
        // Check that GetBlock returns failure.
        buf := make([]byte, BlockSize)
-       size, err := GetBlock(TestHash, buf, nil)
+       size, err := GetBlock(context.Background(), TestHash, buf, nil)
        if err != NotFoundError {
                t.Errorf("Expected NotFoundError, got %v, err %v", buf[:size], err)
        }
@@ -106,11 +107,11 @@ func TestGetBlockCorrupt(t *testing.T) {
        defer KeepVM.Close()
 
        vols := KeepVM.AllReadable()
-       vols[0].Put(TestHash, BadBlock)
+       vols[0].Put(context.Background(), TestHash, BadBlock)
 
        // Check that GetBlock returns failure.
        buf := make([]byte, BlockSize)
-       size, err := GetBlock(TestHash, buf, nil)
+       size, err := GetBlock(context.Background(), TestHash, buf, nil)
        if err != DiskHashError {
                t.Errorf("Expected DiskHashError, got %v (buf: %v)", err, buf[:size])
        }
@@ -131,13 +132,13 @@ func TestPutBlockOK(t *testing.T) {
        defer KeepVM.Close()
 
        // Check that PutBlock stores the data as expected.
-       if n, err := PutBlock(TestBlock, TestHash); err != nil || n < 1 {
+       if n, err := PutBlock(context.Background(), TestBlock, TestHash); err != nil || n < 1 {
                t.Fatalf("PutBlock: n %d err %v", n, err)
        }
 
        vols := KeepVM.AllReadable()
        buf := make([]byte, BlockSize)
-       n, err := vols[1].Get(TestHash, buf)
+       n, err := vols[1].Get(context.Background(), TestHash, buf)
        if err != nil {
                t.Fatalf("Volume #0 Get returned error: %v", err)
        }
@@ -162,12 +163,12 @@ func TestPutBlockOneVol(t *testing.T) {
        vols[0].(*MockVolume).Bad = true
 
        // Check that PutBlock stores the data as expected.
-       if n, err := PutBlock(TestBlock, TestHash); err != nil || n < 1 {
+       if n, err := PutBlock(context.Background(), TestBlock, TestHash); err != nil || n < 1 {
                t.Fatalf("PutBlock: n %d err %v", n, err)
        }
 
        buf := make([]byte, BlockSize)
-       size, err := GetBlock(TestHash, buf, nil)
+       size, err := GetBlock(context.Background(), TestHash, buf, nil)
        if err != nil {
                t.Fatalf("GetBlock: %v", err)
        }
@@ -190,12 +191,12 @@ func TestPutBlockMD5Fail(t *testing.T) {
 
        // Check that PutBlock returns the expected error when the hash does
        // not match the block.
-       if _, err := PutBlock(BadBlock, TestHash); err != RequestHashError {
+       if _, err := PutBlock(context.Background(), BadBlock, TestHash); err != RequestHashError {
                t.Errorf("Expected RequestHashError, got %v", err)
        }
 
        // Confirm that GetBlock fails to return anything.
-       if result, err := GetBlock(TestHash, make([]byte, BlockSize), nil); err != NotFoundError {
+       if result, err := GetBlock(context.Background(), TestHash, make([]byte, BlockSize), nil); err != NotFoundError {
                t.Errorf("GetBlock succeeded after a corrupt block store (result = %s, err = %v)",
                        string(result), err)
        }
@@ -214,14 +215,14 @@ func TestPutBlockCorrupt(t *testing.T) {
 
        // Store a corrupted block under TestHash.
        vols := KeepVM.AllWritable()
-       vols[0].Put(TestHash, BadBlock)
-       if n, err := PutBlock(TestBlock, TestHash); err != nil || n < 1 {
+       vols[0].Put(context.Background(), TestHash, BadBlock)
+       if n, err := PutBlock(context.Background(), TestBlock, TestHash); err != nil || n < 1 {
                t.Errorf("PutBlock: n %d err %v", n, err)
        }
 
        // The block on disk should now match TestBlock.
        buf := make([]byte, BlockSize)
-       if size, err := GetBlock(TestHash, buf, nil); err != nil {
+       if size, err := GetBlock(context.Background(), TestHash, buf, nil); err != nil {
                t.Errorf("GetBlock: %v", err)
        } else if bytes.Compare(buf[:size], TestBlock) != 0 {
                t.Errorf("Got %+q, expected %+q", buf[:size], TestBlock)
@@ -246,10 +247,10 @@ func TestPutBlockCollision(t *testing.T) {
 
        // Store one block, then attempt to store the other. Confirm that
        // PutBlock reported a CollisionError.
-       if _, err := PutBlock(b1, locator); err != nil {
+       if _, err := PutBlock(context.Background(), b1, locator); err != nil {
                t.Error(err)
        }
-       if _, err := PutBlock(b2, locator); err == nil {
+       if _, err := PutBlock(context.Background(), b2, locator); err == nil {
                t.Error("PutBlock did not report a collision")
        } else if err != CollisionError {
                t.Errorf("PutBlock returned %v", err)
@@ -271,7 +272,7 @@ func TestPutBlockTouchFails(t *testing.T) {
        // Store a block and then make the underlying volume bad,
        // so a subsequent attempt to update the file timestamp
        // will fail.
-       vols[0].Put(TestHash, BadBlock)
+       vols[0].Put(context.Background(), TestHash, BadBlock)
        oldMtime, err := vols[0].Mtime(TestHash)
        if err != nil {
                t.Fatalf("vols[0].Mtime(%s): %s\n", TestHash, err)
@@ -280,7 +281,7 @@ func TestPutBlockTouchFails(t *testing.T) {
        // vols[0].Touch will fail on the next call, so the volume
        // manager will store a copy on vols[1] instead.
        vols[0].(*MockVolume).Touchable = false
-       if n, err := PutBlock(TestBlock, TestHash); err != nil || n < 1 {
+       if n, err := PutBlock(context.Background(), TestBlock, TestHash); err != nil || n < 1 {
                t.Fatalf("PutBlock: n %d err %v", n, err)
        }
        vols[0].(*MockVolume).Touchable = true
@@ -296,7 +297,7 @@ func TestPutBlockTouchFails(t *testing.T) {
                        oldMtime, newMtime)
        }
        buf := make([]byte, BlockSize)
-       n, err := vols[1].Get(TestHash, buf)
+       n, err := vols[1].Get(context.Background(), TestHash, buf)
        if err != nil {
                t.Fatalf("vols[1]: %v", err)
        }
@@ -400,11 +401,11 @@ func TestIndex(t *testing.T) {
        defer KeepVM.Close()
 
        vols := KeepVM.AllReadable()
-       vols[0].Put(TestHash, TestBlock)
-       vols[1].Put(TestHash2, TestBlock2)
-       vols[0].Put(TestHash3, TestBlock3)
-       vols[0].Put(TestHash+".meta", []byte("metadata"))
-       vols[1].Put(TestHash2+".meta", []byte("metadata"))
+       vols[0].Put(context.Background(), TestHash, TestBlock)
+       vols[1].Put(context.Background(), TestHash2, TestBlock2)
+       vols[0].Put(context.Background(), TestHash3, TestBlock3)
+       vols[0].Put(context.Background(), TestHash+".meta", []byte("metadata"))
+       vols[1].Put(context.Background(), TestHash2+".meta", []byte("metadata"))
 
        buf := new(bytes.Buffer)
        vols[0].IndexTo("", buf)
index d53d1060e743e07d9d2bfba6b90c67376a1006ab..12860bb662d91a1e31191fed2bccace97bc2ac30 100644 (file)
@@ -1,6 +1,7 @@
 package main
 
 import (
+       "context"
        "crypto/rand"
        "fmt"
        "git.curoverse.com/arvados.git/sdk/go/keepclient"
@@ -94,6 +95,6 @@ func GenerateRandomAPIToken() string {
 
 // Put block
 var PutContent = func(content []byte, locator string) (err error) {
-       _, err = PutBlock(content, locator)
+       _, err = PutBlock(context.Background(), content, locator)
        return
 }
index ed1161c38d7bf977358de642aed390b1f410e089..17923f807dc8a8f11bc77ce8dc0732001a4a8ba8 100644 (file)
@@ -1,11 +1,14 @@
 package main
 
 import (
+       "bytes"
+       "context"
        "encoding/base64"
        "encoding/hex"
        "flag"
        "fmt"
        "io"
+       "io/ioutil"
        "log"
        "net/http"
        "os"
@@ -234,6 +237,27 @@ func (v *S3Volume) Start() error {
        return nil
 }
 
+func (v *S3Volume) getReaderWithContext(ctx context.Context, loc string) (rdr io.ReadCloser, err error) {
+       ready := make(chan bool)
+       go func() {
+               rdr, err = v.getReader(loc)
+               close(ready)
+       }()
+       select {
+       case <-ready:
+               return
+       case <-ctx.Done():
+               theConfig.debugLogf("s3: abandoning getReader(): %s", ctx.Err())
+               go func() {
+                       <-ready
+                       if err == nil {
+                               rdr.Close()
+                       }
+               }()
+               return nil, ctx.Err()
+       }
+}
+
 // getReader wraps (Bucket)GetReader.
 //
 // In situations where (Bucket)GetReader would fail because the block
@@ -266,50 +290,106 @@ func (v *S3Volume) getReader(loc string) (rdr io.ReadCloser, err error) {
 
 // Get a block: copy the block data into buf, and return the number of
 // bytes copied.
-func (v *S3Volume) Get(loc string, buf []byte) (int, error) {
-       rdr, err := v.getReader(loc)
+func (v *S3Volume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
+       rdr, err := v.getReaderWithContext(ctx, loc)
        if err != nil {
                return 0, err
        }
-       defer rdr.Close()
-       n, err := io.ReadFull(rdr, buf)
-       switch err {
-       case nil, io.EOF, io.ErrUnexpectedEOF:
-               return n, nil
-       default:
-               return 0, v.translateError(err)
+
+       var n int
+       ready := make(chan bool)
+       go func() {
+               defer close(ready)
+
+               defer rdr.Close()
+               n, err = io.ReadFull(rdr, buf)
+
+               switch err {
+               case nil, io.EOF, io.ErrUnexpectedEOF:
+                       err = nil
+               default:
+                       err = v.translateError(err)
+               }
+       }()
+       select {
+       case <-ctx.Done():
+               theConfig.debugLogf("s3: interrupting ReadFull() with Close() because %s", ctx.Err())
+               rdr.Close()
+               // Must wait for ReadFull to return, to ensure it
+               // doesn't write to buf after we return.
+               theConfig.debugLogf("s3: waiting for ReadFull() to fail")
+               <-ready
+               return 0, ctx.Err()
+       case <-ready:
+               return n, err
        }
 }
 
 // Compare the given data with the stored data.
-func (v *S3Volume) Compare(loc string, expect []byte) error {
-       rdr, err := v.getReader(loc)
+func (v *S3Volume) Compare(ctx context.Context, loc string, expect []byte) error {
+       rdr, err := v.getReaderWithContext(ctx, loc)
        if err != nil {
                return err
        }
        defer rdr.Close()
-       return v.translateError(compareReaderWithBuf(rdr, expect, loc[:32]))
+       return v.translateError(compareReaderWithBuf(ctx, rdr, expect, loc[:32]))
 }
 
 // Put writes a block.
-func (v *S3Volume) Put(loc string, block []byte) error {
+func (v *S3Volume) Put(ctx context.Context, loc string, block []byte) error {
        if v.ReadOnly {
                return MethodDisabledError
        }
        var opts s3.Options
-       if len(block) > 0 {
+       size := len(block)
+       if size > 0 {
                md5, err := hex.DecodeString(loc)
                if err != nil {
                        return err
                }
                opts.ContentMD5 = base64.StdEncoding.EncodeToString(md5)
        }
-       err := v.bucket.Put(loc, block, "application/octet-stream", s3ACL, opts)
-       if err != nil {
+
+       // Send the block data through a pipe, so that (if we need to)
+       // we can close the pipe early and abandon our PutReader()
+       // goroutine, without worrying about PutReader() accessing our
+       // block buffer after we release it.
+       bufr, bufw := io.Pipe()
+       go func() {
+               io.Copy(bufw, bytes.NewReader(block))
+               bufw.Close()
+       }()
+
+       var err error
+       ready := make(chan bool)
+       go func() {
+               defer func() {
+                       if ctx.Err() != nil {
+                               theConfig.debugLogf("%s: abandoned PutReader goroutine finished with err: %s", v, err)
+                       }
+               }()
+               defer close(ready)
+               err = v.bucket.PutReader(loc, bufr, int64(size), "application/octet-stream", s3ACL, opts)
+               if err != nil {
+                       return
+               }
+               err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
+       }()
+       select {
+       case <-ctx.Done():
+               theConfig.debugLogf("%s: taking PutReader's input away: %s", v, ctx.Err())
+               // Our pipe might be stuck in Write(), waiting for
+               // io.Copy() to read. If so, un-stick it. This means
+               // PutReader will get corrupt data, but that's OK: the
+               // size and MD5 won't match, so the write will fail.
+               go io.Copy(ioutil.Discard, bufr)
+               // CloseWithError() will return once pending I/O is done.
+               bufw.CloseWithError(ctx.Err())
+               theConfig.debugLogf("%s: abandoning PutReader goroutine", v)
+               return ctx.Err()
+       case <-ready:
                return v.translateError(err)
        }
-       err = v.bucket.Put("recent/"+loc, nil, "application/octet-stream", s3ACL, s3.Options{})
-       return v.translateError(err)
 }
 
 // Touch sets the timestamp for the given locator to the current time.
index 76dcbc9f9ea2f8fb680a25a31b84735f991b1b51..63b186220c30a562e900722d63d38be50bde05d6 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bytes"
+       "context"
        "crypto/md5"
        "fmt"
        "io/ioutil"
@@ -223,7 +224,7 @@ func (s *StubbedS3Suite) TestBackendStates(c *check.C) {
                // Check canGet
                loc, blk := setupScenario()
                buf := make([]byte, len(blk))
-               _, err := v.Get(loc, buf)
+               _, err := v.Get(context.Background(), loc, buf)
                c.Check(err == nil, check.Equals, scenario.canGet)
                if err != nil {
                        c.Check(os.IsNotExist(err), check.Equals, true)
@@ -233,7 +234,7 @@ func (s *StubbedS3Suite) TestBackendStates(c *check.C) {
                loc, blk = setupScenario()
                err = v.Trash(loc)
                c.Check(err == nil, check.Equals, scenario.canTrash)
-               _, err = v.Get(loc, buf)
+               _, err = v.Get(context.Background(), loc, buf)
                c.Check(err == nil, check.Equals, scenario.canGetAfterTrash)
                if err != nil {
                        c.Check(os.IsNotExist(err), check.Equals, true)
@@ -248,7 +249,7 @@ func (s *StubbedS3Suite) TestBackendStates(c *check.C) {
                        // should be able to Get after Untrash --
                        // regardless of timestamps, errors, race
                        // conditions, etc.
-                       _, err = v.Get(loc, buf)
+                       _, err = v.Get(context.Background(), loc, buf)
                        c.Check(err, check.IsNil)
                }
 
@@ -269,7 +270,7 @@ func (s *StubbedS3Suite) TestBackendStates(c *check.C) {
                // Check for current Mtime after Put (applies to all
                // scenarios)
                loc, blk = setupScenario()
-               err = v.Put(loc, blk)
+               err = v.Put(context.Background(), loc, blk)
                c.Check(err, check.IsNil)
                t, err := v.Mtime(loc)
                c.Check(err, check.IsNil)
index 5ec413d1bde899d606a6792f40ffd3afe65f3615..04b034a97976980c5ce66d59c361b44936dabbca 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "container/list"
+       "context"
        "testing"
        "time"
 )
@@ -219,15 +220,15 @@ func performTrashWorkerTest(testData TrashWorkerTestData, t *testing.T) {
        // Put test content
        vols := KeepVM.AllWritable()
        if testData.CreateData {
-               vols[0].Put(testData.Locator1, testData.Block1)
-               vols[0].Put(testData.Locator1+".meta", []byte("metadata"))
+               vols[0].Put(context.Background(), testData.Locator1, testData.Block1)
+               vols[0].Put(context.Background(), testData.Locator1+".meta", []byte("metadata"))
 
                if testData.CreateInVolume1 {
-                       vols[0].Put(testData.Locator2, testData.Block2)
-                       vols[0].Put(testData.Locator2+".meta", []byte("metadata"))
+                       vols[0].Put(context.Background(), testData.Locator2, testData.Block2)
+                       vols[0].Put(context.Background(), testData.Locator2+".meta", []byte("metadata"))
                } else {
-                       vols[1].Put(testData.Locator2, testData.Block2)
-                       vols[1].Put(testData.Locator2+".meta", []byte("metadata"))
+                       vols[1].Put(context.Background(), testData.Locator2, testData.Block2)
+                       vols[1].Put(context.Background(), testData.Locator2+".meta", []byte("metadata"))
                }
        }
 
@@ -291,7 +292,7 @@ func performTrashWorkerTest(testData TrashWorkerTestData, t *testing.T) {
 
        // Verify Locator1 to be un/deleted as expected
        buf := make([]byte, BlockSize)
-       size, err := GetBlock(testData.Locator1, buf, nil)
+       size, err := GetBlock(context.Background(), testData.Locator1, buf, nil)
        if testData.ExpectLocator1 {
                if size == 0 || err != nil {
                        t.Errorf("Expected Locator1 to be still present: %s", testData.Locator1)
@@ -304,7 +305,7 @@ func performTrashWorkerTest(testData TrashWorkerTestData, t *testing.T) {
 
        // Verify Locator2 to be un/deleted as expected
        if testData.Locator1 != testData.Locator2 {
-               size, err = GetBlock(testData.Locator2, buf, nil)
+               size, err = GetBlock(context.Background(), testData.Locator2, buf, nil)
                if testData.ExpectLocator2 {
                        if size == 0 || err != nil {
                                t.Errorf("Expected Locator2 to be still present: %s", testData.Locator2)
@@ -323,7 +324,7 @@ func performTrashWorkerTest(testData TrashWorkerTestData, t *testing.T) {
                locatorFoundIn := 0
                for _, volume := range KeepVM.AllReadable() {
                        buf := make([]byte, BlockSize)
-                       if _, err := volume.Get(testData.Locator1, buf); err == nil {
+                       if _, err := volume.Get(context.Background(), testData.Locator1, buf); err == nil {
                                locatorFoundIn = locatorFoundIn + 1
                        }
                }
index 6e01e75b879b339232603d38f93cb040ecc6d86c..57e18aba9f691ceb43f32a928a0e3a95e9d505ec 100644 (file)
@@ -1,6 +1,7 @@
 package main
 
 import (
+       "context"
        "io"
        "sync/atomic"
        "time"
@@ -47,14 +48,14 @@ type Volume interface {
        // any of the data.
        //
        // len(buf) will not exceed BlockSize.
-       Get(loc string, buf []byte) (int, error)
+       Get(ctx context.Context, loc string, buf []byte) (int, error)
 
        // Compare the given data with the stored data (i.e., what Get
        // would return). If equal, return nil. If not, return
        // CollisionError or DiskHashError (depending on whether the
        // data on disk matches the expected hash), or whatever error
        // was encountered opening/reading the stored data.
-       Compare(loc string, data []byte) error
+       Compare(ctx context.Context, loc string, data []byte) error
 
        // Put writes a block to an underlying storage device.
        //
@@ -84,7 +85,7 @@ type Volume interface {
        //
        // Put should not verify that loc==hash(block): this is the
        // caller's responsibility.
-       Put(loc string, block []byte) error
+       Put(ctx context.Context, loc string, block []byte) error
 
        // Touch sets the timestamp for the given locator to the
        // current time.
index 1738fe9b513bb4d86482ceede86a04539d29d418..7e72a8f246ee60410e7110417de3284ae4263ca3 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bytes"
+       "context"
        "crypto/md5"
        "fmt"
        "os"
@@ -92,7 +93,7 @@ func testGet(t TB, factory TestableVolumeFactory) {
        v.PutRaw(TestHash, TestBlock)
 
        buf := make([]byte, BlockSize)
-       n, err := v.Get(TestHash, buf)
+       n, err := v.Get(context.Background(), TestHash, buf)
        if err != nil {
                t.Fatal(err)
        }
@@ -109,7 +110,7 @@ func testGetNoSuchBlock(t TB, factory TestableVolumeFactory) {
        defer v.Teardown()
 
        buf := make([]byte, BlockSize)
-       if _, err := v.Get(TestHash2, buf); err == nil {
+       if _, err := v.Get(context.Background(), TestHash2, buf); err == nil {
                t.Errorf("Expected error while getting non-existing block %v", TestHash2)
        }
 }
@@ -121,7 +122,7 @@ func testCompareNonexistent(t TB, factory TestableVolumeFactory) {
        v := factory(t)
        defer v.Teardown()
 
-       err := v.Compare(TestHash, TestBlock)
+       err := v.Compare(context.Background(), TestHash, TestBlock)
        if err != os.ErrNotExist {
                t.Errorf("Got err %T %q, expected os.ErrNotExist", err, err)
        }
@@ -136,7 +137,7 @@ func testCompareSameContent(t TB, factory TestableVolumeFactory, testHash string
        v.PutRaw(testHash, testData)
 
        // Compare the block locator with same content
-       err := v.Compare(testHash, testData)
+       err := v.Compare(context.Background(), testHash, testData)
        if err != nil {
                t.Errorf("Got err %q, expected nil", err)
        }
@@ -154,7 +155,7 @@ func testCompareWithCollision(t TB, factory TestableVolumeFactory, testHash stri
        v.PutRaw(testHash, testDataA)
 
        // Compare the block locator with different content; collision
-       err := v.Compare(TestHash, testDataB)
+       err := v.Compare(context.Background(), TestHash, testDataB)
        if err == nil {
                t.Errorf("Got err nil, expected error due to collision")
        }
@@ -170,7 +171,7 @@ func testCompareWithCorruptStoredData(t TB, factory TestableVolumeFactory, testH
 
        v.PutRaw(TestHash, testDataB)
 
-       err := v.Compare(testHash, testDataA)
+       err := v.Compare(context.Background(), testHash, testDataA)
        if err == nil || err == CollisionError {
                t.Errorf("Got err %+v, expected non-collision error", err)
        }
@@ -186,12 +187,12 @@ func testPutBlockWithSameContent(t TB, factory TestableVolumeFactory, testHash s
                return
        }
 
-       err := v.Put(testHash, testData)
+       err := v.Put(context.Background(), testHash, testData)
        if err != nil {
                t.Errorf("Got err putting block %q: %q, expected nil", TestBlock, err)
        }
 
-       err = v.Put(testHash, testData)
+       err = v.Put(context.Background(), testHash, testData)
        if err != nil {
                t.Errorf("Got err putting block second time %q: %q, expected nil", TestBlock, err)
        }
@@ -209,9 +210,9 @@ func testPutBlockWithDifferentContent(t TB, factory TestableVolumeFactory, testH
 
        v.PutRaw(testHash, testDataA)
 
-       putErr := v.Put(testHash, testDataB)
+       putErr := v.Put(context.Background(), testHash, testDataB)
        buf := make([]byte, BlockSize)
-       n, getErr := v.Get(testHash, buf)
+       n, getErr := v.Get(context.Background(), testHash, buf)
        if putErr == nil {
                // Put must not return a nil error unless it has
                // overwritten the existing data.
@@ -238,23 +239,23 @@ func testPutMultipleBlocks(t TB, factory TestableVolumeFactory) {
                return
        }
 
-       err := v.Put(TestHash, TestBlock)
+       err := v.Put(context.Background(), TestHash, TestBlock)
        if err != nil {
                t.Errorf("Got err putting block %q: %q, expected nil", TestBlock, err)
        }
 
-       err = v.Put(TestHash2, TestBlock2)
+       err = v.Put(context.Background(), TestHash2, TestBlock2)
        if err != nil {
                t.Errorf("Got err putting block %q: %q, expected nil", TestBlock2, err)
        }
 
-       err = v.Put(TestHash3, TestBlock3)
+       err = v.Put(context.Background(), TestHash3, TestBlock3)
        if err != nil {
                t.Errorf("Got err putting block %q: %q, expected nil", TestBlock3, err)
        }
 
        data := make([]byte, BlockSize)
-       n, err := v.Get(TestHash, data)
+       n, err := v.Get(context.Background(), TestHash, data)
        if err != nil {
                t.Error(err)
        } else {
@@ -263,7 +264,7 @@ func testPutMultipleBlocks(t TB, factory TestableVolumeFactory) {
                }
        }
 
-       n, err = v.Get(TestHash2, data)
+       n, err = v.Get(context.Background(), TestHash2, data)
        if err != nil {
                t.Error(err)
        } else {
@@ -272,7 +273,7 @@ func testPutMultipleBlocks(t TB, factory TestableVolumeFactory) {
                }
        }
 
-       n, err = v.Get(TestHash3, data)
+       n, err = v.Get(context.Background(), TestHash3, data)
        if err != nil {
                t.Error(err)
        } else {
@@ -294,7 +295,7 @@ func testPutAndTouch(t TB, factory TestableVolumeFactory) {
                return
        }
 
-       if err := v.Put(TestHash, TestBlock); err != nil {
+       if err := v.Put(context.Background(), TestHash, TestBlock); err != nil {
                t.Error(err)
        }
 
@@ -314,7 +315,7 @@ func testPutAndTouch(t TB, factory TestableVolumeFactory) {
        }
 
        // Write the same block again.
-       if err := v.Put(TestHash, TestBlock); err != nil {
+       if err := v.Put(context.Background(), TestHash, TestBlock); err != nil {
                t.Error(err)
        }
 
@@ -437,13 +438,13 @@ func testDeleteNewBlock(t TB, factory TestableVolumeFactory) {
                return
        }
 
-       v.Put(TestHash, TestBlock)
+       v.Put(context.Background(), TestHash, TestBlock)
 
        if err := v.Trash(TestHash); err != nil {
                t.Error(err)
        }
        data := make([]byte, BlockSize)
-       n, err := v.Get(TestHash, data)
+       n, err := v.Get(context.Background(), TestHash, data)
        if err != nil {
                t.Error(err)
        } else if bytes.Compare(data[:n], TestBlock) != 0 {
@@ -463,14 +464,14 @@ func testDeleteOldBlock(t TB, factory TestableVolumeFactory) {
                return
        }
 
-       v.Put(TestHash, TestBlock)
+       v.Put(context.Background(), TestHash, TestBlock)
        v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
 
        if err := v.Trash(TestHash); err != nil {
                t.Error(err)
        }
        data := make([]byte, BlockSize)
-       if _, err := v.Get(TestHash, data); err == nil || !os.IsNotExist(err) {
+       if _, err := v.Get(context.Background(), TestHash, data); err == nil || !os.IsNotExist(err) {
                t.Errorf("os.IsNotExist(%v) should have been true", err)
        }
 
@@ -479,7 +480,7 @@ func testDeleteOldBlock(t TB, factory TestableVolumeFactory) {
                t.Fatalf("os.IsNotExist(%v) should have been true", err)
        }
 
-       err = v.Compare(TestHash, TestBlock)
+       err = v.Compare(context.Background(), TestHash, TestBlock)
        if err == nil || !os.IsNotExist(err) {
                t.Fatalf("os.IsNotExist(%v) should have been true", err)
        }
@@ -553,17 +554,17 @@ func testUpdateReadOnly(t TB, factory TestableVolumeFactory) {
        buf := make([]byte, BlockSize)
 
        // Get from read-only volume should succeed
-       _, err := v.Get(TestHash, buf)
+       _, err := v.Get(context.Background(), TestHash, buf)
        if err != nil {
                t.Errorf("got err %v, expected nil", err)
        }
 
        // Put a new block to read-only volume should result in error
-       err = v.Put(TestHash2, TestBlock2)
+       err = v.Put(context.Background(), TestHash2, TestBlock2)
        if err == nil {
                t.Errorf("Expected error when putting block in a read-only volume")
        }
-       _, err = v.Get(TestHash2, buf)
+       _, err = v.Get(context.Background(), TestHash2, buf)
        if err == nil {
                t.Errorf("Expected error when getting block whose put in read-only volume failed")
        }
@@ -581,7 +582,7 @@ func testUpdateReadOnly(t TB, factory TestableVolumeFactory) {
        }
 
        // Overwriting an existing block in read-only volume should result in error
-       err = v.Put(TestHash, TestBlock)
+       err = v.Put(context.Background(), TestHash, TestBlock)
        if err == nil {
                t.Errorf("Expected error when putting block in a read-only volume")
        }
@@ -600,7 +601,7 @@ func testGetConcurrent(t TB, factory TestableVolumeFactory) {
        sem := make(chan int)
        go func() {
                buf := make([]byte, BlockSize)
-               n, err := v.Get(TestHash, buf)
+               n, err := v.Get(context.Background(), TestHash, buf)
                if err != nil {
                        t.Errorf("err1: %v", err)
                }
@@ -612,7 +613,7 @@ func testGetConcurrent(t TB, factory TestableVolumeFactory) {
 
        go func() {
                buf := make([]byte, BlockSize)
-               n, err := v.Get(TestHash2, buf)
+               n, err := v.Get(context.Background(), TestHash2, buf)
                if err != nil {
                        t.Errorf("err2: %v", err)
                }
@@ -624,7 +625,7 @@ func testGetConcurrent(t TB, factory TestableVolumeFactory) {
 
        go func() {
                buf := make([]byte, BlockSize)
-               n, err := v.Get(TestHash3, buf)
+               n, err := v.Get(context.Background(), TestHash3, buf)
                if err != nil {
                        t.Errorf("err3: %v", err)
                }
@@ -652,7 +653,7 @@ func testPutConcurrent(t TB, factory TestableVolumeFactory) {
 
        sem := make(chan int)
        go func(sem chan int) {
-               err := v.Put(TestHash, TestBlock)
+               err := v.Put(context.Background(), TestHash, TestBlock)
                if err != nil {
                        t.Errorf("err1: %v", err)
                }
@@ -660,7 +661,7 @@ func testPutConcurrent(t TB, factory TestableVolumeFactory) {
        }(sem)
 
        go func(sem chan int) {
-               err := v.Put(TestHash2, TestBlock2)
+               err := v.Put(context.Background(), TestHash2, TestBlock2)
                if err != nil {
                        t.Errorf("err2: %v", err)
                }
@@ -668,7 +669,7 @@ func testPutConcurrent(t TB, factory TestableVolumeFactory) {
        }(sem)
 
        go func(sem chan int) {
-               err := v.Put(TestHash3, TestBlock3)
+               err := v.Put(context.Background(), TestHash3, TestBlock3)
                if err != nil {
                        t.Errorf("err3: %v", err)
                }
@@ -682,7 +683,7 @@ func testPutConcurrent(t TB, factory TestableVolumeFactory) {
 
        // Double check that we actually wrote the blocks we expected to write.
        buf := make([]byte, BlockSize)
-       n, err := v.Get(TestHash, buf)
+       n, err := v.Get(context.Background(), TestHash, buf)
        if err != nil {
                t.Errorf("Get #1: %v", err)
        }
@@ -690,7 +691,7 @@ func testPutConcurrent(t TB, factory TestableVolumeFactory) {
                t.Errorf("Get #1: expected %s, got %s", string(TestBlock), string(buf[:n]))
        }
 
-       n, err = v.Get(TestHash2, buf)
+       n, err = v.Get(context.Background(), TestHash2, buf)
        if err != nil {
                t.Errorf("Get #2: %v", err)
        }
@@ -698,7 +699,7 @@ func testPutConcurrent(t TB, factory TestableVolumeFactory) {
                t.Errorf("Get #2: expected %s, got %s", string(TestBlock2), string(buf[:n]))
        }
 
-       n, err = v.Get(TestHash3, buf)
+       n, err = v.Get(context.Background(), TestHash3, buf)
        if err != nil {
                t.Errorf("Get #3: %v", err)
        }
@@ -720,12 +721,12 @@ func testPutFullBlock(t TB, factory TestableVolumeFactory) {
        wdata[0] = 'a'
        wdata[BlockSize-1] = 'z'
        hash := fmt.Sprintf("%x", md5.Sum(wdata))
-       err := v.Put(hash, wdata)
+       err := v.Put(context.Background(), hash, wdata)
        if err != nil {
                t.Fatal(err)
        }
        buf := make([]byte, BlockSize)
-       n, err := v.Get(hash, buf)
+       n, err := v.Get(context.Background(), hash, buf)
        if err != nil {
                t.Error(err)
        }
@@ -752,7 +753,7 @@ func testTrashUntrash(t TB, factory TestableVolumeFactory) {
        v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
 
        buf := make([]byte, BlockSize)
-       n, err := v.Get(TestHash, buf)
+       n, err := v.Get(context.Background(), TestHash, buf)
        if err != nil {
                t.Fatal(err)
        }
@@ -771,7 +772,7 @@ func testTrashUntrash(t TB, factory TestableVolumeFactory) {
                        t.Fatal(err)
                }
        } else {
-               _, err = v.Get(TestHash, buf)
+               _, err = v.Get(context.Background(), TestHash, buf)
                if err == nil || !os.IsNotExist(err) {
                        t.Errorf("os.IsNotExist(%v) should have been true", err)
                }
@@ -784,7 +785,7 @@ func testTrashUntrash(t TB, factory TestableVolumeFactory) {
        }
 
        // Get the block - after trash and untrash sequence
-       n, err = v.Get(TestHash, buf)
+       n, err = v.Get(context.Background(), TestHash, buf)
        if err != nil {
                t.Fatal(err)
        }
@@ -802,7 +803,7 @@ func testTrashEmptyTrashUntrash(t TB, factory TestableVolumeFactory) {
 
        checkGet := func() error {
                buf := make([]byte, BlockSize)
-               n, err := v.Get(TestHash, buf)
+               n, err := v.Get(context.Background(), TestHash, buf)
                if err != nil {
                        return err
                }
@@ -815,7 +816,7 @@ func testTrashEmptyTrashUntrash(t TB, factory TestableVolumeFactory) {
                        return err
                }
 
-               err = v.Compare(TestHash, TestBlock)
+               err = v.Compare(context.Background(), TestHash, TestBlock)
                if err != nil {
                        return err
                }
index 6ab386aec4fcc7774af90c4fa5ca879258ac9404..931c10e69044c4715eb35ccab4d33872a848db5d 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bytes"
+       "context"
        "crypto/md5"
        "errors"
        "fmt"
@@ -95,7 +96,7 @@ func (v *MockVolume) gotCall(method string) {
        }
 }
 
-func (v *MockVolume) Compare(loc string, buf []byte) error {
+func (v *MockVolume) Compare(ctx context.Context, loc string, buf []byte) error {
        v.gotCall("Compare")
        <-v.Gate
        if v.Bad {
@@ -113,7 +114,7 @@ func (v *MockVolume) Compare(loc string, buf []byte) error {
        }
 }
 
-func (v *MockVolume) Get(loc string, buf []byte) (int, error) {
+func (v *MockVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
        v.gotCall("Get")
        <-v.Gate
        if v.Bad {
@@ -125,7 +126,7 @@ func (v *MockVolume) Get(loc string, buf []byte) (int, error) {
        return 0, os.ErrNotExist
 }
 
-func (v *MockVolume) Put(loc string, block []byte) error {
+func (v *MockVolume) Put(ctx context.Context, loc string, block []byte) error {
        v.gotCall("Put")
        <-v.Gate
        if v.Bad {
index b5753dec04638927162a328d2a43f2fd4e567a50..5239ed37402c93f25af0d6c65c03f6a953597cda 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bufio"
+       "context"
        "flag"
        "fmt"
        "io"
@@ -182,11 +183,14 @@ func (v *UnixVolume) Mtime(loc string) (time.Time, error) {
 
 // Lock the locker (if one is in use), open the file for reading, and
 // call the given function if and when the file is ready to read.
-func (v *UnixVolume) getFunc(path string, fn func(io.Reader) error) error {
+func (v *UnixVolume) getFunc(ctx context.Context, path string, fn func(io.Reader) error) error {
        if v.locker != nil {
                v.locker.Lock()
                defer v.locker.Unlock()
        }
+       if ctx.Err() != nil {
+               return ctx.Err()
+       }
        f, err := os.Open(path)
        if err != nil {
                return err
@@ -210,7 +214,7 @@ func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
 
 // Get retrieves a block, copies it to the given slice, and returns
 // the number of bytes copied.
-func (v *UnixVolume) Get(loc string, buf []byte) (int, error) {
+func (v *UnixVolume) Get(ctx context.Context, loc string, buf []byte) (int, error) {
        path := v.blockPath(loc)
        stat, err := v.stat(path)
        if err != nil {
@@ -221,7 +225,7 @@ func (v *UnixVolume) Get(loc string, buf []byte) (int, error) {
        }
        var read int
        size := int(stat.Size())
-       err = v.getFunc(path, func(rdr io.Reader) error {
+       err = v.getFunc(ctx, path, func(rdr io.Reader) error {
                read, err = io.ReadFull(rdr, buf[:size])
                return err
        })
@@ -231,13 +235,13 @@ func (v *UnixVolume) Get(loc string, buf []byte) (int, error) {
 // Compare returns nil if Get(loc) would return the same content as
 // expect. It is functionally equivalent to Get() followed by
 // bytes.Compare(), but uses less memory.
-func (v *UnixVolume) Compare(loc string, expect []byte) error {
+func (v *UnixVolume) Compare(ctx context.Context, loc string, expect []byte) error {
        path := v.blockPath(loc)
        if _, err := v.stat(path); err != nil {
                return v.translateError(err)
        }
-       return v.getFunc(path, func(rdr io.Reader) error {
-               return compareReaderWithBuf(rdr, expect, loc[:32])
+       return v.getFunc(ctx, path, func(rdr io.Reader) error {
+               return compareReaderWithBuf(ctx, rdr, expect, loc[:32])
        })
 }
 
@@ -245,7 +249,7 @@ func (v *UnixVolume) Compare(loc string, expect []byte) error {
 // "loc".  It returns nil on success.  If the volume is full, it
 // returns a FullError.  If the write fails due to some other error,
 // that error is returned.
-func (v *UnixVolume) Put(loc string, block []byte) error {
+func (v *UnixVolume) Put(ctx context.Context, loc string, block []byte) error {
        if v.ReadOnly {
                return MethodDisabledError
        }
@@ -270,6 +274,11 @@ func (v *UnixVolume) Put(loc string, block []byte) error {
                v.locker.Lock()
                defer v.locker.Unlock()
        }
+       select {
+       case <-ctx.Done():
+               return ctx.Err()
+       default:
+       }
        if _, err := tmpfile.Write(block); err != nil {
                log.Printf("%s: writing to %s: %s\n", v, bpath, err)
                tmpfile.Close()
index 887247d3c3956e9475edf8437c913b3e1fc922c9..3021d6bd362724e7136d1054095e49bb53778199 100644 (file)
@@ -2,6 +2,7 @@ package main
 
 import (
        "bytes"
+       "context"
        "errors"
        "fmt"
        "io"
@@ -45,7 +46,7 @@ func (v *TestableUnixVolume) PutRaw(locator string, data []byte) {
                v.ReadOnly = orig
        }(v.ReadOnly)
        v.ReadOnly = false
-       err := v.Put(locator, data)
+       err := v.Put(context.Background(), locator, data)
        if err != nil {
                v.t.Fatal(err)
        }
@@ -117,10 +118,10 @@ func TestReplicationDefault1(t *testing.T) {
 func TestGetNotFound(t *testing.T) {
        v := NewTestableUnixVolume(t, false, false)
        defer v.Teardown()
-       v.Put(TestHash, TestBlock)
+       v.Put(context.Background(), TestHash, TestBlock)
 
        buf := make([]byte, BlockSize)
-       n, err := v.Get(TestHash2, buf)
+       n, err := v.Get(context.Background(), TestHash2, buf)
        switch {
        case os.IsNotExist(err):
                break
@@ -135,7 +136,7 @@ func TestPut(t *testing.T) {
        v := NewTestableUnixVolume(t, false, false)
        defer v.Teardown()
 
-       err := v.Put(TestHash, TestBlock)
+       err := v.Put(context.Background(), TestHash, TestBlock)
        if err != nil {
                t.Error(err)
        }
@@ -153,7 +154,7 @@ func TestPutBadVolume(t *testing.T) {
        defer v.Teardown()
 
        os.Chmod(v.Root, 000)
-       err := v.Put(TestHash, TestBlock)
+       err := v.Put(context.Background(), TestHash, TestBlock)
        if err == nil {
                t.Error("Write should have failed")
        }
@@ -166,12 +167,12 @@ func TestUnixVolumeReadonly(t *testing.T) {
        v.PutRaw(TestHash, TestBlock)
 
        buf := make([]byte, BlockSize)
-       _, err := v.Get(TestHash, buf)
+       _, err := v.Get(context.Background(), TestHash, buf)
        if err != nil {
                t.Errorf("got err %v, expected nil", err)
        }
 
-       err = v.Put(TestHash, TestBlock)
+       err = v.Put(context.Background(), TestHash, TestBlock)
        if err != MethodDisabledError {
                t.Errorf("got err %v, expected MethodDisabledError", err)
        }
@@ -231,9 +232,9 @@ func TestUnixVolumeGetFuncWorkerError(t *testing.T) {
        v := NewTestableUnixVolume(t, false, false)
        defer v.Teardown()
 
-       v.Put(TestHash, TestBlock)
+       v.Put(context.Background(), TestHash, TestBlock)
        mockErr := errors.New("Mock error")
-       err := v.getFunc(v.blockPath(TestHash), func(rdr io.Reader) error {
+       err := v.getFunc(context.Background(), v.blockPath(TestHash), func(rdr io.Reader) error {
                return mockErr
        })
        if err != mockErr {
@@ -246,7 +247,7 @@ func TestUnixVolumeGetFuncFileError(t *testing.T) {
        defer v.Teardown()
 
        funcCalled := false
-       err := v.getFunc(v.blockPath(TestHash), func(rdr io.Reader) error {
+       err := v.getFunc(context.Background(), v.blockPath(TestHash), func(rdr io.Reader) error {
                funcCalled = true
                return nil
        })
@@ -262,13 +263,13 @@ func TestUnixVolumeGetFuncWorkerWaitsOnMutex(t *testing.T) {
        v := NewTestableUnixVolume(t, false, false)
        defer v.Teardown()
 
-       v.Put(TestHash, TestBlock)
+       v.Put(context.Background(), TestHash, TestBlock)
 
        mtx := NewMockMutex()
        v.locker = mtx
 
        funcCalled := make(chan struct{})
-       go v.getFunc(v.blockPath(TestHash), func(rdr io.Reader) error {
+       go v.getFunc(context.Background(), v.blockPath(TestHash), func(rdr io.Reader) error {
                funcCalled <- struct{}{}
                return nil
        })
@@ -297,26 +298,26 @@ func TestUnixVolumeCompare(t *testing.T) {
        v := NewTestableUnixVolume(t, false, false)
        defer v.Teardown()
 
-       v.Put(TestHash, TestBlock)
-       err := v.Compare(TestHash, TestBlock)
+       v.Put(context.Background(), TestHash, TestBlock)
+       err := v.Compare(context.Background(), TestHash, TestBlock)
        if err != nil {
                t.Errorf("Got err %q, expected nil", err)
        }
 
-       err = v.Compare(TestHash, []byte("baddata"))
+       err = v.Compare(context.Background(), TestHash, []byte("baddata"))
        if err != CollisionError {
                t.Errorf("Got err %q, expected %q", err, CollisionError)
        }
 
-       v.Put(TestHash, []byte("baddata"))
-       err = v.Compare(TestHash, TestBlock)
+       v.Put(context.Background(), TestHash, []byte("baddata"))
+       err = v.Compare(context.Background(), TestHash, TestBlock)
        if err != DiskHashError {
                t.Errorf("Got err %q, expected %q", err, DiskHashError)
        }
 
        p := fmt.Sprintf("%s/%s/%s", v.Root, TestHash[:3], TestHash)
        os.Chmod(p, 000)
-       err = v.Compare(TestHash, TestBlock)
+       err = v.Compare(context.Background(), TestHash, TestBlock)
        if err == nil || strings.Index(err.Error(), "permission denied") < 0 {
                t.Errorf("Got err %q, expected %q", err, "permission denied")
        }