Merge branch '13076-r-autogen-api'
[arvados.git] / services / keepstore / volume_generic_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "bytes"
9         "context"
10         "crypto/md5"
11         "fmt"
12         "os"
13         "regexp"
14         "sort"
15         "strconv"
16         "strings"
17         "time"
18
19         "git.curoverse.com/arvados.git/sdk/go/arvados"
20         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
21 )
22
23 type TB interface {
24         Error(args ...interface{})
25         Errorf(format string, args ...interface{})
26         Fail()
27         FailNow()
28         Failed() bool
29         Fatal(args ...interface{})
30         Fatalf(format string, args ...interface{})
31         Log(args ...interface{})
32         Logf(format string, args ...interface{})
33 }
34
35 // A TestableVolumeFactory returns a new TestableVolume. The factory
36 // function, and the TestableVolume it returns, can use "t" to write
37 // logs, fail the current test, etc.
38 type TestableVolumeFactory func(t TB) TestableVolume
39
40 // DoGenericVolumeTests runs a set of tests that every TestableVolume
41 // is expected to pass. It calls factory to create a new TestableVolume
42 // for each test case, to avoid leaking state between tests.
43 func DoGenericVolumeTests(t TB, factory TestableVolumeFactory) {
44         testGet(t, factory)
45         testGetNoSuchBlock(t, factory)
46
47         testCompareNonexistent(t, factory)
48         testCompareSameContent(t, factory, TestHash, TestBlock)
49         testCompareSameContent(t, factory, EmptyHash, EmptyBlock)
50         testCompareWithCollision(t, factory, TestHash, TestBlock, []byte("baddata"))
51         testCompareWithCollision(t, factory, TestHash, TestBlock, EmptyBlock)
52         testCompareWithCollision(t, factory, EmptyHash, EmptyBlock, TestBlock)
53         testCompareWithCorruptStoredData(t, factory, TestHash, TestBlock, []byte("baddata"))
54         testCompareWithCorruptStoredData(t, factory, TestHash, TestBlock, EmptyBlock)
55         testCompareWithCorruptStoredData(t, factory, EmptyHash, EmptyBlock, []byte("baddata"))
56
57         testPutBlockWithSameContent(t, factory, TestHash, TestBlock)
58         testPutBlockWithSameContent(t, factory, EmptyHash, EmptyBlock)
59         testPutBlockWithDifferentContent(t, factory, arvadostest.MD5CollisionMD5, arvadostest.MD5CollisionData[0], arvadostest.MD5CollisionData[1])
60         testPutBlockWithDifferentContent(t, factory, arvadostest.MD5CollisionMD5, EmptyBlock, arvadostest.MD5CollisionData[0])
61         testPutBlockWithDifferentContent(t, factory, arvadostest.MD5CollisionMD5, arvadostest.MD5CollisionData[0], EmptyBlock)
62         testPutBlockWithDifferentContent(t, factory, EmptyHash, EmptyBlock, arvadostest.MD5CollisionData[0])
63         testPutMultipleBlocks(t, factory)
64
65         testPutAndTouch(t, factory)
66         testTouchNoSuchBlock(t, factory)
67
68         testMtimeNoSuchBlock(t, factory)
69
70         testIndexTo(t, factory)
71
72         testDeleteNewBlock(t, factory)
73         testDeleteOldBlock(t, factory)
74         testDeleteNoSuchBlock(t, factory)
75
76         testStatus(t, factory)
77
78         testString(t, factory)
79
80         testUpdateReadOnly(t, factory)
81
82         testGetConcurrent(t, factory)
83         testPutConcurrent(t, factory)
84
85         testPutFullBlock(t, factory)
86
87         testTrashUntrash(t, factory)
88         testTrashEmptyTrashUntrash(t, factory)
89 }
90
91 // Put a test block, get it and verify content
92 // Test should pass for both writable and read-only volumes
93 func testGet(t TB, factory TestableVolumeFactory) {
94         v := factory(t)
95         defer v.Teardown()
96
97         v.PutRaw(TestHash, TestBlock)
98
99         buf := make([]byte, BlockSize)
100         n, err := v.Get(context.Background(), TestHash, buf)
101         if err != nil {
102                 t.Fatal(err)
103         }
104
105         if bytes.Compare(buf[:n], TestBlock) != 0 {
106                 t.Errorf("expected %s, got %s", string(TestBlock), string(buf))
107         }
108 }
109
110 // Invoke get on a block that does not exist in volume; should result in error
111 // Test should pass for both writable and read-only volumes
112 func testGetNoSuchBlock(t TB, factory TestableVolumeFactory) {
113         v := factory(t)
114         defer v.Teardown()
115
116         buf := make([]byte, BlockSize)
117         if _, err := v.Get(context.Background(), TestHash2, buf); err == nil {
118                 t.Errorf("Expected error while getting non-existing block %v", TestHash2)
119         }
120 }
121
122 // Compare() should return os.ErrNotExist if the block does not exist.
123 // Otherwise, writing new data causes CompareAndTouch() to generate
124 // error logs even though everything is working fine.
125 func testCompareNonexistent(t TB, factory TestableVolumeFactory) {
126         v := factory(t)
127         defer v.Teardown()
128
129         err := v.Compare(context.Background(), TestHash, TestBlock)
130         if err != os.ErrNotExist {
131                 t.Errorf("Got err %T %q, expected os.ErrNotExist", err, err)
132         }
133 }
134
135 // Put a test block and compare the locator with same content
136 // Test should pass for both writable and read-only volumes
137 func testCompareSameContent(t TB, factory TestableVolumeFactory, testHash string, testData []byte) {
138         v := factory(t)
139         defer v.Teardown()
140
141         v.PutRaw(testHash, testData)
142
143         // Compare the block locator with same content
144         err := v.Compare(context.Background(), testHash, testData)
145         if err != nil {
146                 t.Errorf("Got err %q, expected nil", err)
147         }
148 }
149
150 // Test behavior of Compare() when stored data matches expected
151 // checksum but differs from new data we need to store. Requires
152 // testHash = md5(testDataA).
153 //
154 // Test should pass for both writable and read-only volumes
155 func testCompareWithCollision(t TB, factory TestableVolumeFactory, testHash string, testDataA, testDataB []byte) {
156         v := factory(t)
157         defer v.Teardown()
158
159         v.PutRaw(testHash, testDataA)
160
161         // Compare the block locator with different content; collision
162         err := v.Compare(context.Background(), TestHash, testDataB)
163         if err == nil {
164                 t.Errorf("Got err nil, expected error due to collision")
165         }
166 }
167
168 // Test behavior of Compare() when stored data has become
169 // corrupted. Requires testHash = md5(testDataA) != md5(testDataB).
170 //
171 // Test should pass for both writable and read-only volumes
172 func testCompareWithCorruptStoredData(t TB, factory TestableVolumeFactory, testHash string, testDataA, testDataB []byte) {
173         v := factory(t)
174         defer v.Teardown()
175
176         v.PutRaw(TestHash, testDataB)
177
178         err := v.Compare(context.Background(), testHash, testDataA)
179         if err == nil || err == CollisionError {
180                 t.Errorf("Got err %+v, expected non-collision error", err)
181         }
182 }
183
184 // Put a block and put again with same content
185 // Test is intended for only writable volumes
186 func testPutBlockWithSameContent(t TB, factory TestableVolumeFactory, testHash string, testData []byte) {
187         v := factory(t)
188         defer v.Teardown()
189
190         if v.Writable() == false {
191                 return
192         }
193
194         err := v.Put(context.Background(), testHash, testData)
195         if err != nil {
196                 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock, err)
197         }
198
199         err = v.Put(context.Background(), testHash, testData)
200         if err != nil {
201                 t.Errorf("Got err putting block second time %q: %q, expected nil", TestBlock, err)
202         }
203 }
204
205 // Put a block and put again with different content
206 // Test is intended for only writable volumes
207 func testPutBlockWithDifferentContent(t TB, factory TestableVolumeFactory, testHash string, testDataA, testDataB []byte) {
208         v := factory(t)
209         defer v.Teardown()
210
211         if v.Writable() == false {
212                 return
213         }
214
215         v.PutRaw(testHash, testDataA)
216
217         putErr := v.Put(context.Background(), testHash, testDataB)
218         buf := make([]byte, BlockSize)
219         n, getErr := v.Get(context.Background(), testHash, buf)
220         if putErr == nil {
221                 // Put must not return a nil error unless it has
222                 // overwritten the existing data.
223                 if bytes.Compare(buf[:n], testDataB) != 0 {
224                         t.Errorf("Put succeeded but Get returned %+q, expected %+q", buf[:n], testDataB)
225                 }
226         } else {
227                 // It is permissible for Put to fail, but it must
228                 // leave us with either the original data, the new
229                 // data, or nothing at all.
230                 if getErr == nil && bytes.Compare(buf[:n], testDataA) != 0 && bytes.Compare(buf[:n], testDataB) != 0 {
231                         t.Errorf("Put failed but Get returned %+q, which is neither %+q nor %+q", buf[:n], testDataA, testDataB)
232                 }
233         }
234 }
235
236 // Put and get multiple blocks
237 // Test is intended for only writable volumes
238 func testPutMultipleBlocks(t TB, factory TestableVolumeFactory) {
239         v := factory(t)
240         defer v.Teardown()
241
242         if v.Writable() == false {
243                 return
244         }
245
246         err := v.Put(context.Background(), TestHash, TestBlock)
247         if err != nil {
248                 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock, err)
249         }
250
251         err = v.Put(context.Background(), TestHash2, TestBlock2)
252         if err != nil {
253                 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock2, err)
254         }
255
256         err = v.Put(context.Background(), TestHash3, TestBlock3)
257         if err != nil {
258                 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock3, err)
259         }
260
261         data := make([]byte, BlockSize)
262         n, err := v.Get(context.Background(), TestHash, data)
263         if err != nil {
264                 t.Error(err)
265         } else {
266                 if bytes.Compare(data[:n], TestBlock) != 0 {
267                         t.Errorf("Block present, but got %+q, expected %+q", data[:n], TestBlock)
268                 }
269         }
270
271         n, err = v.Get(context.Background(), TestHash2, data)
272         if err != nil {
273                 t.Error(err)
274         } else {
275                 if bytes.Compare(data[:n], TestBlock2) != 0 {
276                         t.Errorf("Block present, but got %+q, expected %+q", data[:n], TestBlock2)
277                 }
278         }
279
280         n, err = v.Get(context.Background(), TestHash3, data)
281         if err != nil {
282                 t.Error(err)
283         } else {
284                 if bytes.Compare(data[:n], TestBlock3) != 0 {
285                         t.Errorf("Block present, but to %+q, expected %+q", data[:n], TestBlock3)
286                 }
287         }
288 }
289
290 // testPutAndTouch
291 //   Test that when applying PUT to a block that already exists,
292 //   the block's modification time is updated.
293 // Test is intended for only writable volumes
294 func testPutAndTouch(t TB, factory TestableVolumeFactory) {
295         v := factory(t)
296         defer v.Teardown()
297
298         if v.Writable() == false {
299                 return
300         }
301
302         if err := v.Put(context.Background(), TestHash, TestBlock); err != nil {
303                 t.Error(err)
304         }
305
306         // We'll verify { t0 < threshold < t1 }, where t0 is the
307         // existing block's timestamp on disk before Put() and t1 is
308         // its timestamp after Put().
309         threshold := time.Now().Add(-time.Second)
310
311         // Set the stored block's mtime far enough in the past that we
312         // can see the difference between "timestamp didn't change"
313         // and "timestamp granularity is too low".
314         v.TouchWithDate(TestHash, time.Now().Add(-20*time.Second))
315
316         // Make sure v.Mtime() agrees the above Utime really worked.
317         if t0, err := v.Mtime(TestHash); err != nil || t0.IsZero() || !t0.Before(threshold) {
318                 t.Errorf("Setting mtime failed: %v, %v", t0, err)
319         }
320
321         // Write the same block again.
322         if err := v.Put(context.Background(), TestHash, TestBlock); err != nil {
323                 t.Error(err)
324         }
325
326         // Verify threshold < t1
327         if t1, err := v.Mtime(TestHash); err != nil {
328                 t.Error(err)
329         } else if t1.Before(threshold) {
330                 t.Errorf("t1 %v should be >= threshold %v after v.Put ", t1, threshold)
331         }
332 }
333
334 // Touching a non-existing block should result in error.
335 // Test should pass for both writable and read-only volumes
336 func testTouchNoSuchBlock(t TB, factory TestableVolumeFactory) {
337         v := factory(t)
338         defer v.Teardown()
339
340         if err := v.Touch(TestHash); err == nil {
341                 t.Error("Expected error when attempted to touch a non-existing block")
342         }
343 }
344
345 // Invoking Mtime on a non-existing block should result in error.
346 // Test should pass for both writable and read-only volumes
347 func testMtimeNoSuchBlock(t TB, factory TestableVolumeFactory) {
348         v := factory(t)
349         defer v.Teardown()
350
351         if _, err := v.Mtime("12345678901234567890123456789012"); err == nil {
352                 t.Error("Expected error when updating Mtime on a non-existing block")
353         }
354 }
355
356 // Put a few blocks and invoke IndexTo with:
357 // * no prefix
358 // * with a prefix
359 // * with no such prefix
360 // Test should pass for both writable and read-only volumes
361 func testIndexTo(t TB, factory TestableVolumeFactory) {
362         v := factory(t)
363         defer v.Teardown()
364
365         // minMtime and maxMtime are the minimum and maximum
366         // acceptable values the index can report for our test
367         // blocks. 1-second precision is acceptable.
368         minMtime := time.Now().UTC().UnixNano()
369         minMtime -= minMtime % 1e9
370
371         v.PutRaw(TestHash, TestBlock)
372         v.PutRaw(TestHash2, TestBlock2)
373         v.PutRaw(TestHash3, TestBlock3)
374
375         maxMtime := time.Now().UTC().UnixNano()
376         if maxMtime%1e9 > 0 {
377                 maxMtime -= maxMtime % 1e9
378                 maxMtime += 1e9
379         }
380
381         // Blocks whose names aren't Keep hashes should be omitted from
382         // index
383         v.PutRaw("fffffffffnotreallyahashfffffffff", nil)
384         v.PutRaw("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", nil)
385         v.PutRaw("f0000000000000000000000000000000f", nil)
386         v.PutRaw("f00", nil)
387
388         buf := new(bytes.Buffer)
389         v.IndexTo("", buf)
390         indexRows := strings.Split(string(buf.Bytes()), "\n")
391         sort.Strings(indexRows)
392         sortedIndex := strings.Join(indexRows, "\n")
393         m := regexp.MustCompile(
394                 `^\n` + TestHash + `\+\d+ (\d+)\n` +
395                         TestHash3 + `\+\d+ \d+\n` +
396                         TestHash2 + `\+\d+ \d+$`,
397         ).FindStringSubmatch(sortedIndex)
398         if m == nil {
399                 t.Errorf("Got index %q for empty prefix", sortedIndex)
400         } else {
401                 mtime, err := strconv.ParseInt(m[1], 10, 64)
402                 if err != nil {
403                         t.Error(err)
404                 } else if mtime < minMtime || mtime > maxMtime {
405                         t.Errorf("got %d for TestHash timestamp, expected %d <= t <= %d",
406                                 mtime, minMtime, maxMtime)
407                 }
408         }
409
410         for _, prefix := range []string{"f", "f15", "f15ac"} {
411                 buf = new(bytes.Buffer)
412                 v.IndexTo(prefix, buf)
413
414                 m, err := regexp.MatchString(`^`+TestHash2+`\+\d+ \d+\n$`, string(buf.Bytes()))
415                 if err != nil {
416                         t.Error(err)
417                 } else if !m {
418                         t.Errorf("Got index %q for prefix %s", string(buf.Bytes()), prefix)
419                 }
420         }
421
422         for _, prefix := range []string{"zero", "zip", "zilch"} {
423                 buf = new(bytes.Buffer)
424                 err := v.IndexTo(prefix, buf)
425                 if err != nil {
426                         t.Errorf("Got error on IndexTo with no such prefix %v", err.Error())
427                 } else if buf.Len() != 0 {
428                         t.Errorf("Expected empty list for IndexTo with no such prefix %s", prefix)
429                 }
430         }
431 }
432
433 // Calling Delete() for a block immediately after writing it (not old enough)
434 // should neither delete the data nor return an error.
435 // Test is intended for only writable volumes
436 func testDeleteNewBlock(t TB, factory TestableVolumeFactory) {
437         v := factory(t)
438         defer v.Teardown()
439         theConfig.BlobSignatureTTL.Set("5m")
440
441         if v.Writable() == false {
442                 return
443         }
444
445         v.Put(context.Background(), TestHash, TestBlock)
446
447         if err := v.Trash(TestHash); err != nil {
448                 t.Error(err)
449         }
450         data := make([]byte, BlockSize)
451         n, err := v.Get(context.Background(), TestHash, data)
452         if err != nil {
453                 t.Error(err)
454         } else if bytes.Compare(data[:n], TestBlock) != 0 {
455                 t.Errorf("Got data %+q, expected %+q", data[:n], TestBlock)
456         }
457 }
458
459 // Calling Delete() for a block with a timestamp older than
460 // BlobSignatureTTL seconds in the past should delete the data.
461 // Test is intended for only writable volumes
462 func testDeleteOldBlock(t TB, factory TestableVolumeFactory) {
463         v := factory(t)
464         defer v.Teardown()
465         theConfig.BlobSignatureTTL.Set("5m")
466
467         if v.Writable() == false {
468                 return
469         }
470
471         v.Put(context.Background(), TestHash, TestBlock)
472         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
473
474         if err := v.Trash(TestHash); err != nil {
475                 t.Error(err)
476         }
477         data := make([]byte, BlockSize)
478         if _, err := v.Get(context.Background(), TestHash, data); err == nil || !os.IsNotExist(err) {
479                 t.Errorf("os.IsNotExist(%v) should have been true", err)
480         }
481
482         _, err := v.Mtime(TestHash)
483         if err == nil || !os.IsNotExist(err) {
484                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
485         }
486
487         err = v.Compare(context.Background(), TestHash, TestBlock)
488         if err == nil || !os.IsNotExist(err) {
489                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
490         }
491
492         indexBuf := new(bytes.Buffer)
493         v.IndexTo("", indexBuf)
494         if strings.Contains(string(indexBuf.Bytes()), TestHash) {
495                 t.Fatalf("Found trashed block in IndexTo")
496         }
497
498         err = v.Touch(TestHash)
499         if err == nil || !os.IsNotExist(err) {
500                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
501         }
502 }
503
504 // Calling Delete() for a block that does not exist should result in error.
505 // Test should pass for both writable and read-only volumes
506 func testDeleteNoSuchBlock(t TB, factory TestableVolumeFactory) {
507         v := factory(t)
508         defer v.Teardown()
509
510         if err := v.Trash(TestHash2); err == nil {
511                 t.Errorf("Expected error when attempting to delete a non-existing block")
512         }
513 }
514
515 // Invoke Status and verify that VolumeStatus is returned
516 // Test should pass for both writable and read-only volumes
517 func testStatus(t TB, factory TestableVolumeFactory) {
518         v := factory(t)
519         defer v.Teardown()
520
521         // Get node status and make a basic sanity check.
522         status := v.Status()
523         if status.DeviceNum == 0 {
524                 t.Errorf("uninitialized device_num in %v", status)
525         }
526
527         if status.BytesFree == 0 {
528                 t.Errorf("uninitialized bytes_free in %v", status)
529         }
530
531         if status.BytesUsed == 0 {
532                 t.Errorf("uninitialized bytes_used in %v", status)
533         }
534 }
535
536 // Invoke String for the volume; expect non-empty result
537 // Test should pass for both writable and read-only volumes
538 func testString(t TB, factory TestableVolumeFactory) {
539         v := factory(t)
540         defer v.Teardown()
541
542         if id := v.String(); len(id) == 0 {
543                 t.Error("Got empty string for v.String()")
544         }
545 }
546
547 // Putting, updating, touching, and deleting blocks from a read-only volume result in error.
548 // Test is intended for only read-only volumes
549 func testUpdateReadOnly(t TB, factory TestableVolumeFactory) {
550         v := factory(t)
551         defer v.Teardown()
552
553         if v.Writable() == true {
554                 return
555         }
556
557         v.PutRaw(TestHash, TestBlock)
558         buf := make([]byte, BlockSize)
559
560         // Get from read-only volume should succeed
561         _, err := v.Get(context.Background(), TestHash, buf)
562         if err != nil {
563                 t.Errorf("got err %v, expected nil", err)
564         }
565
566         // Put a new block to read-only volume should result in error
567         err = v.Put(context.Background(), TestHash2, TestBlock2)
568         if err == nil {
569                 t.Errorf("Expected error when putting block in a read-only volume")
570         }
571         _, err = v.Get(context.Background(), TestHash2, buf)
572         if err == nil {
573                 t.Errorf("Expected error when getting block whose put in read-only volume failed")
574         }
575
576         // Touch a block in read-only volume should result in error
577         err = v.Touch(TestHash)
578         if err == nil {
579                 t.Errorf("Expected error when touching block in a read-only volume")
580         }
581
582         // Delete a block from a read-only volume should result in error
583         err = v.Trash(TestHash)
584         if err == nil {
585                 t.Errorf("Expected error when deleting block from a read-only volume")
586         }
587
588         // Overwriting an existing block in read-only volume should result in error
589         err = v.Put(context.Background(), TestHash, TestBlock)
590         if err == nil {
591                 t.Errorf("Expected error when putting block in a read-only volume")
592         }
593 }
594
595 // Launch concurrent Gets
596 // Test should pass for both writable and read-only volumes
597 func testGetConcurrent(t TB, factory TestableVolumeFactory) {
598         v := factory(t)
599         defer v.Teardown()
600
601         v.PutRaw(TestHash, TestBlock)
602         v.PutRaw(TestHash2, TestBlock2)
603         v.PutRaw(TestHash3, TestBlock3)
604
605         sem := make(chan int)
606         go func() {
607                 buf := make([]byte, BlockSize)
608                 n, err := v.Get(context.Background(), TestHash, buf)
609                 if err != nil {
610                         t.Errorf("err1: %v", err)
611                 }
612                 if bytes.Compare(buf[:n], TestBlock) != 0 {
613                         t.Errorf("buf should be %s, is %s", string(TestBlock), string(buf[:n]))
614                 }
615                 sem <- 1
616         }()
617
618         go func() {
619                 buf := make([]byte, BlockSize)
620                 n, err := v.Get(context.Background(), TestHash2, buf)
621                 if err != nil {
622                         t.Errorf("err2: %v", err)
623                 }
624                 if bytes.Compare(buf[:n], TestBlock2) != 0 {
625                         t.Errorf("buf should be %s, is %s", string(TestBlock2), string(buf[:n]))
626                 }
627                 sem <- 1
628         }()
629
630         go func() {
631                 buf := make([]byte, BlockSize)
632                 n, err := v.Get(context.Background(), TestHash3, buf)
633                 if err != nil {
634                         t.Errorf("err3: %v", err)
635                 }
636                 if bytes.Compare(buf[:n], TestBlock3) != 0 {
637                         t.Errorf("buf should be %s, is %s", string(TestBlock3), string(buf[:n]))
638                 }
639                 sem <- 1
640         }()
641
642         // Wait for all goroutines to finish
643         for done := 0; done < 3; done++ {
644                 <-sem
645         }
646 }
647
648 // Launch concurrent Puts
649 // Test is intended for only writable volumes
650 func testPutConcurrent(t TB, factory TestableVolumeFactory) {
651         v := factory(t)
652         defer v.Teardown()
653
654         if v.Writable() == false {
655                 return
656         }
657
658         sem := make(chan int)
659         go func(sem chan int) {
660                 err := v.Put(context.Background(), TestHash, TestBlock)
661                 if err != nil {
662                         t.Errorf("err1: %v", err)
663                 }
664                 sem <- 1
665         }(sem)
666
667         go func(sem chan int) {
668                 err := v.Put(context.Background(), TestHash2, TestBlock2)
669                 if err != nil {
670                         t.Errorf("err2: %v", err)
671                 }
672                 sem <- 1
673         }(sem)
674
675         go func(sem chan int) {
676                 err := v.Put(context.Background(), TestHash3, TestBlock3)
677                 if err != nil {
678                         t.Errorf("err3: %v", err)
679                 }
680                 sem <- 1
681         }(sem)
682
683         // Wait for all goroutines to finish
684         for done := 0; done < 3; done++ {
685                 <-sem
686         }
687
688         // Double check that we actually wrote the blocks we expected to write.
689         buf := make([]byte, BlockSize)
690         n, err := v.Get(context.Background(), TestHash, buf)
691         if err != nil {
692                 t.Errorf("Get #1: %v", err)
693         }
694         if bytes.Compare(buf[:n], TestBlock) != 0 {
695                 t.Errorf("Get #1: expected %s, got %s", string(TestBlock), string(buf[:n]))
696         }
697
698         n, err = v.Get(context.Background(), TestHash2, buf)
699         if err != nil {
700                 t.Errorf("Get #2: %v", err)
701         }
702         if bytes.Compare(buf[:n], TestBlock2) != 0 {
703                 t.Errorf("Get #2: expected %s, got %s", string(TestBlock2), string(buf[:n]))
704         }
705
706         n, err = v.Get(context.Background(), TestHash3, buf)
707         if err != nil {
708                 t.Errorf("Get #3: %v", err)
709         }
710         if bytes.Compare(buf[:n], TestBlock3) != 0 {
711                 t.Errorf("Get #3: expected %s, got %s", string(TestBlock3), string(buf[:n]))
712         }
713 }
714
715 // Write and read back a full size block
716 func testPutFullBlock(t TB, factory TestableVolumeFactory) {
717         v := factory(t)
718         defer v.Teardown()
719
720         if !v.Writable() {
721                 return
722         }
723
724         wdata := make([]byte, BlockSize)
725         wdata[0] = 'a'
726         wdata[BlockSize-1] = 'z'
727         hash := fmt.Sprintf("%x", md5.Sum(wdata))
728         err := v.Put(context.Background(), hash, wdata)
729         if err != nil {
730                 t.Fatal(err)
731         }
732         buf := make([]byte, BlockSize)
733         n, err := v.Get(context.Background(), hash, buf)
734         if err != nil {
735                 t.Error(err)
736         }
737         if bytes.Compare(buf[:n], wdata) != 0 {
738                 t.Error("buf %+q != wdata %+q", buf[:n], wdata)
739         }
740 }
741
742 // With TrashLifetime != 0, perform:
743 // Trash an old block - which either raises ErrNotImplemented or succeeds
744 // Untrash -  which either raises ErrNotImplemented or succeeds
745 // Get - which must succeed
746 func testTrashUntrash(t TB, factory TestableVolumeFactory) {
747         v := factory(t)
748         defer v.Teardown()
749         defer func() {
750                 theConfig.TrashLifetime = 0
751         }()
752
753         theConfig.TrashLifetime.Set("1h")
754
755         // put block and backdate it
756         v.PutRaw(TestHash, TestBlock)
757         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
758
759         buf := make([]byte, BlockSize)
760         n, err := v.Get(context.Background(), TestHash, buf)
761         if err != nil {
762                 t.Fatal(err)
763         }
764         if bytes.Compare(buf[:n], TestBlock) != 0 {
765                 t.Errorf("Got data %+q, expected %+q", buf[:n], TestBlock)
766         }
767
768         // Trash
769         err = v.Trash(TestHash)
770         if v.Writable() == false {
771                 if err != MethodDisabledError {
772                         t.Fatal(err)
773                 }
774         } else if err != nil {
775                 if err != ErrNotImplemented {
776                         t.Fatal(err)
777                 }
778         } else {
779                 _, err = v.Get(context.Background(), TestHash, buf)
780                 if err == nil || !os.IsNotExist(err) {
781                         t.Errorf("os.IsNotExist(%v) should have been true", err)
782                 }
783
784                 // Untrash
785                 err = v.Untrash(TestHash)
786                 if err != nil {
787                         t.Fatal(err)
788                 }
789         }
790
791         // Get the block - after trash and untrash sequence
792         n, err = v.Get(context.Background(), TestHash, buf)
793         if err != nil {
794                 t.Fatal(err)
795         }
796         if bytes.Compare(buf[:n], TestBlock) != 0 {
797                 t.Errorf("Got data %+q, expected %+q", buf[:n], TestBlock)
798         }
799 }
800
801 func testTrashEmptyTrashUntrash(t TB, factory TestableVolumeFactory) {
802         v := factory(t)
803         defer v.Teardown()
804         defer func(orig arvados.Duration) {
805                 theConfig.TrashLifetime = orig
806         }(theConfig.TrashLifetime)
807
808         checkGet := func() error {
809                 buf := make([]byte, BlockSize)
810                 n, err := v.Get(context.Background(), TestHash, buf)
811                 if err != nil {
812                         return err
813                 }
814                 if bytes.Compare(buf[:n], TestBlock) != 0 {
815                         t.Fatalf("Got data %+q, expected %+q", buf[:n], TestBlock)
816                 }
817
818                 _, err = v.Mtime(TestHash)
819                 if err != nil {
820                         return err
821                 }
822
823                 err = v.Compare(context.Background(), TestHash, TestBlock)
824                 if err != nil {
825                         return err
826                 }
827
828                 indexBuf := new(bytes.Buffer)
829                 v.IndexTo("", indexBuf)
830                 if !strings.Contains(string(indexBuf.Bytes()), TestHash) {
831                         return os.ErrNotExist
832                 }
833
834                 return nil
835         }
836
837         // First set: EmptyTrash before reaching the trash deadline.
838
839         theConfig.TrashLifetime.Set("1h")
840
841         v.PutRaw(TestHash, TestBlock)
842         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
843
844         err := checkGet()
845         if err != nil {
846                 t.Fatal(err)
847         }
848
849         // Trash the block
850         err = v.Trash(TestHash)
851         if err == MethodDisabledError || err == ErrNotImplemented {
852                 // Skip the trash tests for read-only volumes, and
853                 // volume types that don't support TrashLifetime>0.
854                 return
855         }
856
857         err = checkGet()
858         if err == nil || !os.IsNotExist(err) {
859                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
860         }
861
862         err = v.Touch(TestHash)
863         if err == nil || !os.IsNotExist(err) {
864                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
865         }
866
867         v.EmptyTrash()
868
869         // Even after emptying the trash, we can untrash our block
870         // because the deadline hasn't been reached.
871         err = v.Untrash(TestHash)
872         if err != nil {
873                 t.Fatal(err)
874         }
875
876         err = checkGet()
877         if err != nil {
878                 t.Fatal(err)
879         }
880
881         err = v.Touch(TestHash)
882         if err != nil {
883                 t.Fatal(err)
884         }
885
886         // Because we Touch'ed, need to backdate again for next set of tests
887         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
888
889         // If the only block in the trash has already been untrashed,
890         // most volumes will fail a subsequent Untrash with a 404, but
891         // it's also acceptable for Untrash to succeed.
892         err = v.Untrash(TestHash)
893         if err != nil && !os.IsNotExist(err) {
894                 t.Fatalf("Expected success or os.IsNotExist(), but got: %v", err)
895         }
896
897         // The additional Untrash should not interfere with our
898         // already-untrashed copy.
899         err = checkGet()
900         if err != nil {
901                 t.Fatal(err)
902         }
903
904         // Untrash might have updated the timestamp, so backdate again
905         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
906
907         // Second set: EmptyTrash after the trash deadline has passed.
908
909         theConfig.TrashLifetime.Set("1ns")
910
911         err = v.Trash(TestHash)
912         if err != nil {
913                 t.Fatal(err)
914         }
915         err = checkGet()
916         if err == nil || !os.IsNotExist(err) {
917                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
918         }
919
920         // Even though 1ns has passed, we can untrash because we
921         // haven't called EmptyTrash yet.
922         err = v.Untrash(TestHash)
923         if err != nil {
924                 t.Fatal(err)
925         }
926         err = checkGet()
927         if err != nil {
928                 t.Fatal(err)
929         }
930
931         // Trash it again, and this time call EmptyTrash so it really
932         // goes away.
933         // (In Azure volumes, un/trash changes Mtime, so first backdate again)
934         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
935         _ = v.Trash(TestHash)
936         err = checkGet()
937         if err == nil || !os.IsNotExist(err) {
938                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
939         }
940         v.EmptyTrash()
941
942         // Untrash won't find it
943         err = v.Untrash(TestHash)
944         if err == nil || !os.IsNotExist(err) {
945                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
946         }
947
948         // Get block won't find it
949         err = checkGet()
950         if err == nil || !os.IsNotExist(err) {
951                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
952         }
953
954         // Third set: If the same data block gets written again after
955         // being trashed, and then the trash gets emptied, the newer
956         // un-trashed copy doesn't get deleted along with it.
957
958         v.PutRaw(TestHash, TestBlock)
959         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
960
961         theConfig.TrashLifetime.Set("1ns")
962         err = v.Trash(TestHash)
963         if err != nil {
964                 t.Fatal(err)
965         }
966         err = checkGet()
967         if err == nil || !os.IsNotExist(err) {
968                 t.Fatalf("os.IsNotExist(%v) should have been true", err)
969         }
970
971         v.PutRaw(TestHash, TestBlock)
972         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
973
974         // EmptyTrash should not delete the untrashed copy.
975         v.EmptyTrash()
976         err = checkGet()
977         if err != nil {
978                 t.Fatal(err)
979         }
980
981         // Fourth set: If the same data block gets trashed twice with
982         // different deadlines A and C, and then the trash is emptied
983         // at intermediate time B (A < B < C), it is still possible to
984         // untrash the block whose deadline is "C".
985
986         v.PutRaw(TestHash, TestBlock)
987         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
988
989         theConfig.TrashLifetime.Set("1ns")
990         err = v.Trash(TestHash)
991         if err != nil {
992                 t.Fatal(err)
993         }
994
995         v.PutRaw(TestHash, TestBlock)
996         v.TouchWithDate(TestHash, time.Now().Add(-2*theConfig.BlobSignatureTTL.Duration()))
997
998         theConfig.TrashLifetime.Set("1h")
999         err = v.Trash(TestHash)
1000         if err != nil {
1001                 t.Fatal(err)
1002         }
1003
1004         // EmptyTrash should not prevent us from recovering the
1005         // time.Hour ("C") trash
1006         v.EmptyTrash()
1007         err = v.Untrash(TestHash)
1008         if err != nil {
1009                 t.Fatal(err)
1010         }
1011         err = checkGet()
1012         if err != nil {
1013                 t.Fatal(err)
1014         }
1015 }