1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.arvados.org/arvados.git/sdk/go/arvados"
20 "git.arvados.org/arvados.git/sdk/go/arvadostest"
21 "git.arvados.org/arvados.git/sdk/go/ctxlog"
22 "github.com/prometheus/client_golang/prometheus"
23 dto "github.com/prometheus/client_model/go"
24 "github.com/sirupsen/logrus"
28 Error(args ...interface{})
29 Errorf(format string, args ...interface{})
33 Fatal(args ...interface{})
34 Fatalf(format string, args ...interface{})
35 Log(args ...interface{})
36 Logf(format string, args ...interface{})
39 // A TestableVolumeFactory returns a new TestableVolume. The factory
40 // function, and the TestableVolume it returns, can use "t" to write
41 // logs, fail the current test, etc.
42 type TestableVolumeFactory func(t TB, cluster *arvados.Cluster, volume arvados.Volume, logger logrus.FieldLogger, metrics *volumeMetricsVecs) TestableVolume
44 // DoGenericVolumeTests runs a set of tests that every TestableVolume
45 // is expected to pass. It calls factory to create a new TestableVolume
46 // for each test case, to avoid leaking state between tests.
47 func DoGenericVolumeTests(t TB, readonly bool, factory TestableVolumeFactory) {
48 var s genericVolumeSuite
49 s.volume.ReadOnly = readonly
52 s.testGetNoSuchBlock(t, factory)
54 s.testCompareNonexistent(t, factory)
55 s.testCompareSameContent(t, factory, TestHash, TestBlock)
56 s.testCompareSameContent(t, factory, EmptyHash, EmptyBlock)
57 s.testCompareWithCollision(t, factory, TestHash, TestBlock, []byte("baddata"))
58 s.testCompareWithCollision(t, factory, TestHash, TestBlock, EmptyBlock)
59 s.testCompareWithCollision(t, factory, EmptyHash, EmptyBlock, TestBlock)
60 s.testCompareWithCorruptStoredData(t, factory, TestHash, TestBlock, []byte("baddata"))
61 s.testCompareWithCorruptStoredData(t, factory, TestHash, TestBlock, EmptyBlock)
62 s.testCompareWithCorruptStoredData(t, factory, EmptyHash, EmptyBlock, []byte("baddata"))
65 s.testPutBlockWithSameContent(t, factory, TestHash, TestBlock)
66 s.testPutBlockWithSameContent(t, factory, EmptyHash, EmptyBlock)
67 s.testPutBlockWithDifferentContent(t, factory, arvadostest.MD5CollisionMD5, arvadostest.MD5CollisionData[0], arvadostest.MD5CollisionData[1])
68 s.testPutBlockWithDifferentContent(t, factory, arvadostest.MD5CollisionMD5, EmptyBlock, arvadostest.MD5CollisionData[0])
69 s.testPutBlockWithDifferentContent(t, factory, arvadostest.MD5CollisionMD5, arvadostest.MD5CollisionData[0], EmptyBlock)
70 s.testPutBlockWithDifferentContent(t, factory, EmptyHash, EmptyBlock, arvadostest.MD5CollisionData[0])
71 s.testPutMultipleBlocks(t, factory)
73 s.testPutAndTouch(t, factory)
75 s.testTouchNoSuchBlock(t, factory)
77 s.testMtimeNoSuchBlock(t, factory)
79 s.testIndexTo(t, factory)
82 s.testDeleteNewBlock(t, factory)
83 s.testDeleteOldBlock(t, factory)
85 s.testDeleteNoSuchBlock(t, factory)
87 s.testStatus(t, factory)
89 s.testMetrics(t, readonly, factory)
91 s.testString(t, factory)
94 s.testUpdateReadOnly(t, factory)
97 s.testGetConcurrent(t, factory)
99 s.testPutConcurrent(t, factory)
101 s.testPutFullBlock(t, factory)
104 s.testTrashUntrash(t, readonly, factory)
105 s.testTrashEmptyTrashUntrash(t, factory)
108 type genericVolumeSuite struct {
109 cluster *arvados.Cluster
110 volume arvados.Volume
111 logger logrus.FieldLogger
112 metrics *volumeMetricsVecs
113 registry *prometheus.Registry
116 func (s *genericVolumeSuite) setup(t TB) {
117 s.cluster = testCluster(t)
118 s.logger = ctxlog.TestLogger(t)
119 s.registry = prometheus.NewRegistry()
120 s.metrics = newVolumeMetricsVecs(s.registry)
123 func (s *genericVolumeSuite) newVolume(t TB, factory TestableVolumeFactory) TestableVolume {
124 return factory(t, s.cluster, s.volume, s.logger, s.metrics)
127 // Put a test block, get it and verify content
128 // Test should pass for both writable and read-only volumes
129 func (s *genericVolumeSuite) testGet(t TB, factory TestableVolumeFactory) {
131 v := s.newVolume(t, factory)
134 v.PutRaw(TestHash, TestBlock)
136 buf := make([]byte, BlockSize)
137 n, err := v.Get(context.Background(), TestHash, buf)
142 if bytes.Compare(buf[:n], TestBlock) != 0 {
143 t.Errorf("expected %s, got %s", string(TestBlock), string(buf))
147 // Invoke get on a block that does not exist in volume; should result in error
148 // Test should pass for both writable and read-only volumes
149 func (s *genericVolumeSuite) testGetNoSuchBlock(t TB, factory TestableVolumeFactory) {
151 v := s.newVolume(t, factory)
154 buf := make([]byte, BlockSize)
155 if _, err := v.Get(context.Background(), TestHash2, buf); err == nil {
156 t.Errorf("Expected error while getting non-existing block %v", TestHash2)
160 // Compare() should return os.ErrNotExist if the block does not exist.
161 // Otherwise, writing new data causes CompareAndTouch() to generate
162 // error logs even though everything is working fine.
163 func (s *genericVolumeSuite) testCompareNonexistent(t TB, factory TestableVolumeFactory) {
165 v := s.newVolume(t, factory)
168 err := v.Compare(context.Background(), TestHash, TestBlock)
169 if err != os.ErrNotExist {
170 t.Errorf("Got err %T %q, expected os.ErrNotExist", err, err)
174 // Put a test block and compare the locator with same content
175 // Test should pass for both writable and read-only volumes
176 func (s *genericVolumeSuite) testCompareSameContent(t TB, factory TestableVolumeFactory, testHash string, testData []byte) {
178 v := s.newVolume(t, factory)
181 v.PutRaw(testHash, testData)
183 // Compare the block locator with same content
184 err := v.Compare(context.Background(), testHash, testData)
186 t.Errorf("Got err %q, expected nil", err)
190 // Test behavior of Compare() when stored data matches expected
191 // checksum but differs from new data we need to store. Requires
192 // testHash = md5(testDataA).
194 // Test should pass for both writable and read-only volumes
195 func (s *genericVolumeSuite) testCompareWithCollision(t TB, factory TestableVolumeFactory, testHash string, testDataA, testDataB []byte) {
197 v := s.newVolume(t, factory)
200 v.PutRaw(testHash, testDataA)
202 // Compare the block locator with different content; collision
203 err := v.Compare(context.Background(), TestHash, testDataB)
205 t.Errorf("Got err nil, expected error due to collision")
209 // Test behavior of Compare() when stored data has become
210 // corrupted. Requires testHash = md5(testDataA) != md5(testDataB).
212 // Test should pass for both writable and read-only volumes
213 func (s *genericVolumeSuite) testCompareWithCorruptStoredData(t TB, factory TestableVolumeFactory, testHash string, testDataA, testDataB []byte) {
215 v := s.newVolume(t, factory)
218 v.PutRaw(TestHash, testDataB)
220 err := v.Compare(context.Background(), testHash, testDataA)
221 if err == nil || err == CollisionError {
222 t.Errorf("Got err %+v, expected non-collision error", err)
226 // Put a block and put again with same content
227 // Test is intended for only writable volumes
228 func (s *genericVolumeSuite) testPutBlockWithSameContent(t TB, factory TestableVolumeFactory, testHash string, testData []byte) {
230 v := s.newVolume(t, factory)
233 err := v.Put(context.Background(), testHash, testData)
235 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock, err)
238 err = v.Put(context.Background(), testHash, testData)
240 t.Errorf("Got err putting block second time %q: %q, expected nil", TestBlock, err)
244 // Put a block and put again with different content
245 // Test is intended for only writable volumes
246 func (s *genericVolumeSuite) testPutBlockWithDifferentContent(t TB, factory TestableVolumeFactory, testHash string, testDataA, testDataB []byte) {
248 v := s.newVolume(t, factory)
251 v.PutRaw(testHash, testDataA)
253 putErr := v.Put(context.Background(), testHash, testDataB)
254 buf := make([]byte, BlockSize)
255 n, getErr := v.Get(context.Background(), testHash, buf)
257 // Put must not return a nil error unless it has
258 // overwritten the existing data.
259 if bytes.Compare(buf[:n], testDataB) != 0 {
260 t.Errorf("Put succeeded but Get returned %+q, expected %+q", buf[:n], testDataB)
263 // It is permissible for Put to fail, but it must
264 // leave us with either the original data, the new
265 // data, or nothing at all.
266 if getErr == nil && bytes.Compare(buf[:n], testDataA) != 0 && bytes.Compare(buf[:n], testDataB) != 0 {
267 t.Errorf("Put failed but Get returned %+q, which is neither %+q nor %+q", buf[:n], testDataA, testDataB)
272 // Put and get multiple blocks
273 // Test is intended for only writable volumes
274 func (s *genericVolumeSuite) testPutMultipleBlocks(t TB, factory TestableVolumeFactory) {
276 v := s.newVolume(t, factory)
279 err := v.Put(context.Background(), TestHash, TestBlock)
281 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock, err)
284 err = v.Put(context.Background(), TestHash2, TestBlock2)
286 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock2, err)
289 err = v.Put(context.Background(), TestHash3, TestBlock3)
291 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock3, err)
294 data := make([]byte, BlockSize)
295 n, err := v.Get(context.Background(), TestHash, data)
299 if bytes.Compare(data[:n], TestBlock) != 0 {
300 t.Errorf("Block present, but got %+q, expected %+q", data[:n], TestBlock)
304 n, err = v.Get(context.Background(), TestHash2, data)
308 if bytes.Compare(data[:n], TestBlock2) != 0 {
309 t.Errorf("Block present, but got %+q, expected %+q", data[:n], TestBlock2)
313 n, err = v.Get(context.Background(), TestHash3, data)
317 if bytes.Compare(data[:n], TestBlock3) != 0 {
318 t.Errorf("Block present, but to %+q, expected %+q", data[:n], TestBlock3)
324 // Test that when applying PUT to a block that already exists,
325 // the block's modification time is updated.
326 // Test is intended for only writable volumes
327 func (s *genericVolumeSuite) testPutAndTouch(t TB, factory TestableVolumeFactory) {
329 v := s.newVolume(t, factory)
332 if err := v.Put(context.Background(), TestHash, TestBlock); err != nil {
336 // We'll verify { t0 < threshold < t1 }, where t0 is the
337 // existing block's timestamp on disk before Put() and t1 is
338 // its timestamp after Put().
339 threshold := time.Now().Add(-time.Second)
341 // Set the stored block's mtime far enough in the past that we
342 // can see the difference between "timestamp didn't change"
343 // and "timestamp granularity is too low".
344 v.TouchWithDate(TestHash, time.Now().Add(-20*time.Second))
346 // Make sure v.Mtime() agrees the above Utime really worked.
347 if t0, err := v.Mtime(TestHash); err != nil || t0.IsZero() || !t0.Before(threshold) {
348 t.Errorf("Setting mtime failed: %v, %v", t0, err)
351 // Write the same block again.
352 if err := v.Put(context.Background(), TestHash, TestBlock); err != nil {
356 // Verify threshold < t1
357 if t1, err := v.Mtime(TestHash); err != nil {
359 } else if t1.Before(threshold) {
360 t.Errorf("t1 %v should be >= threshold %v after v.Put ", t1, threshold)
364 // Touching a non-existing block should result in error.
365 // Test should pass for both writable and read-only volumes
366 func (s *genericVolumeSuite) testTouchNoSuchBlock(t TB, factory TestableVolumeFactory) {
368 v := s.newVolume(t, factory)
371 if err := v.Touch(TestHash); err == nil {
372 t.Error("Expected error when attempted to touch a non-existing block")
376 // Invoking Mtime on a non-existing block should result in error.
377 // Test should pass for both writable and read-only volumes
378 func (s *genericVolumeSuite) testMtimeNoSuchBlock(t TB, factory TestableVolumeFactory) {
380 v := s.newVolume(t, factory)
383 if _, err := v.Mtime("12345678901234567890123456789012"); err == nil {
384 t.Error("Expected error when updating Mtime on a non-existing block")
388 // Put a few blocks and invoke IndexTo with:
391 // * with no such prefix
392 // Test should pass for both writable and read-only volumes
393 func (s *genericVolumeSuite) testIndexTo(t TB, factory TestableVolumeFactory) {
395 v := s.newVolume(t, factory)
398 // minMtime and maxMtime are the minimum and maximum
399 // acceptable values the index can report for our test
400 // blocks. 1-second precision is acceptable.
401 minMtime := time.Now().UTC().UnixNano()
402 minMtime -= minMtime % 1e9
404 v.PutRaw(TestHash, TestBlock)
405 v.PutRaw(TestHash2, TestBlock2)
406 v.PutRaw(TestHash3, TestBlock3)
408 maxMtime := time.Now().UTC().UnixNano()
409 if maxMtime%1e9 > 0 {
410 maxMtime -= maxMtime % 1e9
414 // Blocks whose names aren't Keep hashes should be omitted from
416 v.PutRaw("fffffffffnotreallyahashfffffffff", nil)
417 v.PutRaw("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", nil)
418 v.PutRaw("f0000000000000000000000000000000f", nil)
421 buf := new(bytes.Buffer)
423 indexRows := strings.Split(string(buf.Bytes()), "\n")
424 sort.Strings(indexRows)
425 sortedIndex := strings.Join(indexRows, "\n")
426 m := regexp.MustCompile(
427 `^\n` + TestHash + `\+\d+ (\d+)\n` +
428 TestHash3 + `\+\d+ \d+\n` +
429 TestHash2 + `\+\d+ \d+$`,
430 ).FindStringSubmatch(sortedIndex)
432 t.Errorf("Got index %q for empty prefix", sortedIndex)
434 mtime, err := strconv.ParseInt(m[1], 10, 64)
437 } else if mtime < minMtime || mtime > maxMtime {
438 t.Errorf("got %d for TestHash timestamp, expected %d <= t <= %d",
439 mtime, minMtime, maxMtime)
443 for _, prefix := range []string{"f", "f15", "f15ac"} {
444 buf = new(bytes.Buffer)
445 v.IndexTo(prefix, buf)
447 m, err := regexp.MatchString(`^`+TestHash2+`\+\d+ \d+\n$`, string(buf.Bytes()))
451 t.Errorf("Got index %q for prefix %s", string(buf.Bytes()), prefix)
455 for _, prefix := range []string{"zero", "zip", "zilch"} {
456 buf = new(bytes.Buffer)
457 err := v.IndexTo(prefix, buf)
459 t.Errorf("Got error on IndexTo with no such prefix %v", err.Error())
460 } else if buf.Len() != 0 {
461 t.Errorf("Expected empty list for IndexTo with no such prefix %s", prefix)
466 // Calling Delete() for a block immediately after writing it (not old enough)
467 // should neither delete the data nor return an error.
468 // Test is intended for only writable volumes
469 func (s *genericVolumeSuite) testDeleteNewBlock(t TB, factory TestableVolumeFactory) {
471 s.cluster.Collections.BlobSigningTTL.Set("5m")
472 v := s.newVolume(t, factory)
475 v.Put(context.Background(), TestHash, TestBlock)
477 if err := v.Trash(TestHash); err != nil {
480 data := make([]byte, BlockSize)
481 n, err := v.Get(context.Background(), TestHash, data)
484 } else if bytes.Compare(data[:n], TestBlock) != 0 {
485 t.Errorf("Got data %+q, expected %+q", data[:n], TestBlock)
489 // Calling Delete() for a block with a timestamp older than
490 // BlobSigningTTL seconds in the past should delete the data. Test is
491 // intended for only writable volumes
492 func (s *genericVolumeSuite) testDeleteOldBlock(t TB, factory TestableVolumeFactory) {
494 s.cluster.Collections.BlobSigningTTL.Set("5m")
495 v := s.newVolume(t, factory)
498 v.Put(context.Background(), TestHash, TestBlock)
499 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
501 if err := v.Trash(TestHash); err != nil {
504 data := make([]byte, BlockSize)
505 if _, err := v.Get(context.Background(), TestHash, data); err == nil || !os.IsNotExist(err) {
506 t.Errorf("os.IsNotExist(%v) should have been true", err)
509 _, err := v.Mtime(TestHash)
510 if err == nil || !os.IsNotExist(err) {
511 t.Fatalf("os.IsNotExist(%v) should have been true", err)
514 err = v.Compare(context.Background(), TestHash, TestBlock)
515 if err == nil || !os.IsNotExist(err) {
516 t.Fatalf("os.IsNotExist(%v) should have been true", err)
519 indexBuf := new(bytes.Buffer)
520 v.IndexTo("", indexBuf)
521 if strings.Contains(string(indexBuf.Bytes()), TestHash) {
522 t.Fatalf("Found trashed block in IndexTo")
525 err = v.Touch(TestHash)
526 if err == nil || !os.IsNotExist(err) {
527 t.Fatalf("os.IsNotExist(%v) should have been true", err)
531 // Calling Delete() for a block that does not exist should result in error.
532 // Test should pass for both writable and read-only volumes
533 func (s *genericVolumeSuite) testDeleteNoSuchBlock(t TB, factory TestableVolumeFactory) {
535 v := s.newVolume(t, factory)
538 if err := v.Trash(TestHash2); err == nil {
539 t.Errorf("Expected error when attempting to delete a non-existing block")
543 // Invoke Status and verify that VolumeStatus is returned
544 // Test should pass for both writable and read-only volumes
545 func (s *genericVolumeSuite) testStatus(t TB, factory TestableVolumeFactory) {
547 v := s.newVolume(t, factory)
550 // Get node status and make a basic sanity check.
552 if status.DeviceNum == 0 {
553 t.Errorf("uninitialized device_num in %v", status)
556 if status.BytesFree == 0 {
557 t.Errorf("uninitialized bytes_free in %v", status)
560 if status.BytesUsed == 0 {
561 t.Errorf("uninitialized bytes_used in %v", status)
565 func getValueFrom(cv *prometheus.CounterVec, lbls prometheus.Labels) float64 {
566 c, _ := cv.GetMetricWith(lbls)
569 return pb.GetCounter().GetValue()
572 func (s *genericVolumeSuite) testMetrics(t TB, readonly bool, factory TestableVolumeFactory) {
576 v := s.newVolume(t, factory)
579 opsC, _, ioC := s.metrics.getCounterVecsFor(prometheus.Labels{"device_id": v.GetDeviceID()})
582 t.Error("ioBytes CounterVec is nil")
586 if getValueFrom(ioC, prometheus.Labels{"direction": "out"})+
587 getValueFrom(ioC, prometheus.Labels{"direction": "in"}) > 0 {
588 t.Error("ioBytes counter should be zero")
592 t.Error("opsCounter CounterVec is nil")
596 var c, writeOpCounter, readOpCounter float64
598 readOpType, writeOpType := v.ReadWriteOperationLabelValues()
599 writeOpCounter = getValueFrom(opsC, prometheus.Labels{"operation": writeOpType})
600 readOpCounter = getValueFrom(opsC, prometheus.Labels{"operation": readOpType})
602 // Test Put if volume is writable
604 err = v.Put(context.Background(), TestHash, TestBlock)
606 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock, err)
608 // Check that the write operations counter increased
609 c = getValueFrom(opsC, prometheus.Labels{"operation": writeOpType})
610 if c <= writeOpCounter {
611 t.Error("Operation(s) not counted on Put")
613 // Check that bytes counter is > 0
614 if getValueFrom(ioC, prometheus.Labels{"direction": "out"}) == 0 {
615 t.Error("ioBytes{direction=out} counter shouldn't be zero")
618 v.PutRaw(TestHash, TestBlock)
621 buf := make([]byte, BlockSize)
622 _, err = v.Get(context.Background(), TestHash, buf)
627 // Check that the operations counter increased
628 c = getValueFrom(opsC, prometheus.Labels{"operation": readOpType})
629 if c <= readOpCounter {
630 t.Error("Operation(s) not counted on Get")
632 // Check that the bytes "in" counter is > 0
633 if getValueFrom(ioC, prometheus.Labels{"direction": "in"}) == 0 {
634 t.Error("ioBytes{direction=in} counter shouldn't be zero")
638 // Invoke String for the volume; expect non-empty result
639 // Test should pass for both writable and read-only volumes
640 func (s *genericVolumeSuite) testString(t TB, factory TestableVolumeFactory) {
642 v := s.newVolume(t, factory)
645 if id := v.String(); len(id) == 0 {
646 t.Error("Got empty string for v.String()")
650 // Putting, updating, touching, and deleting blocks from a read-only volume result in error.
651 // Test is intended for only read-only volumes
652 func (s *genericVolumeSuite) testUpdateReadOnly(t TB, factory TestableVolumeFactory) {
654 v := s.newVolume(t, factory)
657 v.PutRaw(TestHash, TestBlock)
658 buf := make([]byte, BlockSize)
660 // Get from read-only volume should succeed
661 _, err := v.Get(context.Background(), TestHash, buf)
663 t.Errorf("got err %v, expected nil", err)
666 // Put a new block to read-only volume should result in error
667 err = v.Put(context.Background(), TestHash2, TestBlock2)
669 t.Errorf("Expected error when putting block in a read-only volume")
671 _, err = v.Get(context.Background(), TestHash2, buf)
673 t.Errorf("Expected error when getting block whose put in read-only volume failed")
676 // Touch a block in read-only volume should result in error
677 err = v.Touch(TestHash)
679 t.Errorf("Expected error when touching block in a read-only volume")
682 // Delete a block from a read-only volume should result in error
683 err = v.Trash(TestHash)
685 t.Errorf("Expected error when deleting block from a read-only volume")
688 // Overwriting an existing block in read-only volume should result in error
689 err = v.Put(context.Background(), TestHash, TestBlock)
691 t.Errorf("Expected error when putting block in a read-only volume")
695 // Launch concurrent Gets
696 // Test should pass for both writable and read-only volumes
697 func (s *genericVolumeSuite) testGetConcurrent(t TB, factory TestableVolumeFactory) {
699 v := s.newVolume(t, factory)
702 v.PutRaw(TestHash, TestBlock)
703 v.PutRaw(TestHash2, TestBlock2)
704 v.PutRaw(TestHash3, TestBlock3)
706 sem := make(chan int)
708 buf := make([]byte, BlockSize)
709 n, err := v.Get(context.Background(), TestHash, buf)
711 t.Errorf("err1: %v", err)
713 if bytes.Compare(buf[:n], TestBlock) != 0 {
714 t.Errorf("buf should be %s, is %s", string(TestBlock), string(buf[:n]))
720 buf := make([]byte, BlockSize)
721 n, err := v.Get(context.Background(), TestHash2, buf)
723 t.Errorf("err2: %v", err)
725 if bytes.Compare(buf[:n], TestBlock2) != 0 {
726 t.Errorf("buf should be %s, is %s", string(TestBlock2), string(buf[:n]))
732 buf := make([]byte, BlockSize)
733 n, err := v.Get(context.Background(), TestHash3, buf)
735 t.Errorf("err3: %v", err)
737 if bytes.Compare(buf[:n], TestBlock3) != 0 {
738 t.Errorf("buf should be %s, is %s", string(TestBlock3), string(buf[:n]))
743 // Wait for all goroutines to finish
744 for done := 0; done < 3; done++ {
749 // Launch concurrent Puts
750 // Test is intended for only writable volumes
751 func (s *genericVolumeSuite) testPutConcurrent(t TB, factory TestableVolumeFactory) {
753 v := s.newVolume(t, factory)
756 sem := make(chan int)
757 go func(sem chan int) {
758 err := v.Put(context.Background(), TestHash, TestBlock)
760 t.Errorf("err1: %v", err)
765 go func(sem chan int) {
766 err := v.Put(context.Background(), TestHash2, TestBlock2)
768 t.Errorf("err2: %v", err)
773 go func(sem chan int) {
774 err := v.Put(context.Background(), TestHash3, TestBlock3)
776 t.Errorf("err3: %v", err)
781 // Wait for all goroutines to finish
782 for done := 0; done < 3; done++ {
786 // Double check that we actually wrote the blocks we expected to write.
787 buf := make([]byte, BlockSize)
788 n, err := v.Get(context.Background(), TestHash, buf)
790 t.Errorf("Get #1: %v", err)
792 if bytes.Compare(buf[:n], TestBlock) != 0 {
793 t.Errorf("Get #1: expected %s, got %s", string(TestBlock), string(buf[:n]))
796 n, err = v.Get(context.Background(), TestHash2, buf)
798 t.Errorf("Get #2: %v", err)
800 if bytes.Compare(buf[:n], TestBlock2) != 0 {
801 t.Errorf("Get #2: expected %s, got %s", string(TestBlock2), string(buf[:n]))
804 n, err = v.Get(context.Background(), TestHash3, buf)
806 t.Errorf("Get #3: %v", err)
808 if bytes.Compare(buf[:n], TestBlock3) != 0 {
809 t.Errorf("Get #3: expected %s, got %s", string(TestBlock3), string(buf[:n]))
813 // Write and read back a full size block
814 func (s *genericVolumeSuite) testPutFullBlock(t TB, factory TestableVolumeFactory) {
816 v := s.newVolume(t, factory)
819 wdata := make([]byte, BlockSize)
821 wdata[BlockSize-1] = 'z'
822 hash := fmt.Sprintf("%x", md5.Sum(wdata))
823 err := v.Put(context.Background(), hash, wdata)
827 buf := make([]byte, BlockSize)
828 n, err := v.Get(context.Background(), hash, buf)
832 if bytes.Compare(buf[:n], wdata) != 0 {
833 t.Error("buf %+q != wdata %+q", buf[:n], wdata)
837 // With BlobTrashLifetime != 0, perform:
838 // Trash an old block - which either raises ErrNotImplemented or succeeds
839 // Untrash - which either raises ErrNotImplemented or succeeds
840 // Get - which must succeed
841 func (s *genericVolumeSuite) testTrashUntrash(t TB, readonly bool, factory TestableVolumeFactory) {
843 s.cluster.Collections.BlobTrashLifetime.Set("1h")
844 v := s.newVolume(t, factory)
847 // put block and backdate it
848 v.PutRaw(TestHash, TestBlock)
849 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
851 buf := make([]byte, BlockSize)
852 n, err := v.Get(context.Background(), TestHash, buf)
856 if bytes.Compare(buf[:n], TestBlock) != 0 {
857 t.Errorf("Got data %+q, expected %+q", buf[:n], TestBlock)
861 err = v.Trash(TestHash)
863 if err != MethodDisabledError {
866 } else if err != nil {
867 if err != ErrNotImplemented {
871 _, err = v.Get(context.Background(), TestHash, buf)
872 if err == nil || !os.IsNotExist(err) {
873 t.Errorf("os.IsNotExist(%v) should have been true", err)
877 err = v.Untrash(TestHash)
883 // Get the block - after trash and untrash sequence
884 n, err = v.Get(context.Background(), TestHash, buf)
888 if bytes.Compare(buf[:n], TestBlock) != 0 {
889 t.Errorf("Got data %+q, expected %+q", buf[:n], TestBlock)
893 func (s *genericVolumeSuite) testTrashEmptyTrashUntrash(t TB, factory TestableVolumeFactory) {
895 v := s.newVolume(t, factory)
898 checkGet := func() error {
899 buf := make([]byte, BlockSize)
900 n, err := v.Get(context.Background(), TestHash, buf)
904 if bytes.Compare(buf[:n], TestBlock) != 0 {
905 t.Fatalf("Got data %+q, expected %+q", buf[:n], TestBlock)
908 _, err = v.Mtime(TestHash)
913 err = v.Compare(context.Background(), TestHash, TestBlock)
918 indexBuf := new(bytes.Buffer)
919 v.IndexTo("", indexBuf)
920 if !strings.Contains(string(indexBuf.Bytes()), TestHash) {
921 return os.ErrNotExist
927 // First set: EmptyTrash before reaching the trash deadline.
929 s.cluster.Collections.BlobTrashLifetime.Set("1h")
931 v.PutRaw(TestHash, TestBlock)
932 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
940 err = v.Trash(TestHash)
941 if err == MethodDisabledError || err == ErrNotImplemented {
942 // Skip the trash tests for read-only volumes, and
943 // volume types that don't support
944 // BlobTrashLifetime>0.
949 if err == nil || !os.IsNotExist(err) {
950 t.Fatalf("os.IsNotExist(%v) should have been true", err)
953 err = v.Touch(TestHash)
954 if err == nil || !os.IsNotExist(err) {
955 t.Fatalf("os.IsNotExist(%v) should have been true", err)
960 // Even after emptying the trash, we can untrash our block
961 // because the deadline hasn't been reached.
962 err = v.Untrash(TestHash)
972 err = v.Touch(TestHash)
977 // Because we Touch'ed, need to backdate again for next set of tests
978 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
980 // If the only block in the trash has already been untrashed,
981 // most volumes will fail a subsequent Untrash with a 404, but
982 // it's also acceptable for Untrash to succeed.
983 err = v.Untrash(TestHash)
984 if err != nil && !os.IsNotExist(err) {
985 t.Fatalf("Expected success or os.IsNotExist(), but got: %v", err)
988 // The additional Untrash should not interfere with our
989 // already-untrashed copy.
995 // Untrash might have updated the timestamp, so backdate again
996 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
998 // Second set: EmptyTrash after the trash deadline has passed.
1000 s.cluster.Collections.BlobTrashLifetime.Set("1ns")
1002 err = v.Trash(TestHash)
1007 if err == nil || !os.IsNotExist(err) {
1008 t.Fatalf("os.IsNotExist(%v) should have been true", err)
1011 // Even though 1ns has passed, we can untrash because we
1012 // haven't called EmptyTrash yet.
1013 err = v.Untrash(TestHash)
1022 // Trash it again, and this time call EmptyTrash so it really
1024 // (In Azure volumes, un/trash changes Mtime, so first backdate again)
1025 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
1026 _ = v.Trash(TestHash)
1028 if err == nil || !os.IsNotExist(err) {
1029 t.Fatalf("os.IsNotExist(%v) should have been true", err)
1033 // Untrash won't find it
1034 err = v.Untrash(TestHash)
1035 if err == nil || !os.IsNotExist(err) {
1036 t.Fatalf("os.IsNotExist(%v) should have been true", err)
1039 // Get block won't find it
1041 if err == nil || !os.IsNotExist(err) {
1042 t.Fatalf("os.IsNotExist(%v) should have been true", err)
1045 // Third set: If the same data block gets written again after
1046 // being trashed, and then the trash gets emptied, the newer
1047 // un-trashed copy doesn't get deleted along with it.
1049 v.PutRaw(TestHash, TestBlock)
1050 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
1052 s.cluster.Collections.BlobTrashLifetime.Set("1ns")
1053 err = v.Trash(TestHash)
1058 if err == nil || !os.IsNotExist(err) {
1059 t.Fatalf("os.IsNotExist(%v) should have been true", err)
1062 v.PutRaw(TestHash, TestBlock)
1063 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
1065 // EmptyTrash should not delete the untrashed copy.
1072 // Fourth set: If the same data block gets trashed twice with
1073 // different deadlines A and C, and then the trash is emptied
1074 // at intermediate time B (A < B < C), it is still possible to
1075 // untrash the block whose deadline is "C".
1077 v.PutRaw(TestHash, TestBlock)
1078 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
1080 s.cluster.Collections.BlobTrashLifetime.Set("1ns")
1081 err = v.Trash(TestHash)
1086 v.PutRaw(TestHash, TestBlock)
1087 v.TouchWithDate(TestHash, time.Now().Add(-2*s.cluster.Collections.BlobSigningTTL.Duration()))
1089 s.cluster.Collections.BlobTrashLifetime.Set("1h")
1090 err = v.Trash(TestHash)
1095 // EmptyTrash should not prevent us from recovering the
1096 // time.Hour ("C") trash
1098 err = v.Untrash(TestHash)