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