Merge branch '8206-gce-retry-init' closes #8206
[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         "strings"
11         "time"
12
13         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
14 )
15
16 type TB interface {
17         Error(args ...interface{})
18         Errorf(format string, args ...interface{})
19         Fail()
20         FailNow()
21         Failed() bool
22         Fatal(args ...interface{})
23         Fatalf(format string, args ...interface{})
24         Log(args ...interface{})
25         Logf(format string, args ...interface{})
26 }
27
28 // A TestableVolumeFactory returns a new TestableVolume. The factory
29 // function, and the TestableVolume it returns, can use "t" to write
30 // logs, fail the current test, etc.
31 type TestableVolumeFactory func(t TB) TestableVolume
32
33 // DoGenericVolumeTests runs a set of tests that every TestableVolume
34 // is expected to pass. It calls factory to create a new TestableVolume
35 // for each test case, to avoid leaking state between tests.
36 func DoGenericVolumeTests(t TB, factory TestableVolumeFactory) {
37         testGet(t, factory)
38         testGetNoSuchBlock(t, factory)
39
40         testCompareNonexistent(t, factory)
41         testCompareSameContent(t, factory, TestHash, TestBlock)
42         testCompareSameContent(t, factory, EmptyHash, EmptyBlock)
43         testCompareWithCollision(t, factory, TestHash, TestBlock, []byte("baddata"))
44         testCompareWithCollision(t, factory, TestHash, TestBlock, EmptyBlock)
45         testCompareWithCollision(t, factory, EmptyHash, EmptyBlock, TestBlock)
46         testCompareWithCorruptStoredData(t, factory, TestHash, TestBlock, []byte("baddata"))
47         testCompareWithCorruptStoredData(t, factory, TestHash, TestBlock, EmptyBlock)
48         testCompareWithCorruptStoredData(t, factory, EmptyHash, EmptyBlock, []byte("baddata"))
49
50         testPutBlockWithSameContent(t, factory, TestHash, TestBlock)
51         testPutBlockWithSameContent(t, factory, EmptyHash, EmptyBlock)
52         testPutBlockWithDifferentContent(t, factory, arvadostest.MD5CollisionMD5, arvadostest.MD5CollisionData[0], arvadostest.MD5CollisionData[1])
53         testPutBlockWithDifferentContent(t, factory, arvadostest.MD5CollisionMD5, EmptyBlock, arvadostest.MD5CollisionData[0])
54         testPutBlockWithDifferentContent(t, factory, arvadostest.MD5CollisionMD5, arvadostest.MD5CollisionData[0], EmptyBlock)
55         testPutBlockWithDifferentContent(t, factory, EmptyHash, EmptyBlock, arvadostest.MD5CollisionData[0])
56         testPutMultipleBlocks(t, factory)
57
58         testPutAndTouch(t, factory)
59         testTouchNoSuchBlock(t, factory)
60
61         testMtimeNoSuchBlock(t, factory)
62
63         testIndexTo(t, factory)
64
65         testDeleteNewBlock(t, factory)
66         testDeleteOldBlock(t, factory)
67         testDeleteNoSuchBlock(t, factory)
68
69         testStatus(t, factory)
70
71         testString(t, factory)
72
73         testUpdateReadOnly(t, factory)
74
75         testGetConcurrent(t, factory)
76         testPutConcurrent(t, factory)
77
78         testPutFullBlock(t, factory)
79 }
80
81 // Put a test block, get it and verify content
82 // Test should pass for both writable and read-only volumes
83 func testGet(t TB, factory TestableVolumeFactory) {
84         v := factory(t)
85         defer v.Teardown()
86
87         v.PutRaw(TestHash, TestBlock)
88
89         buf, err := v.Get(TestHash)
90         if err != nil {
91                 t.Fatal(err)
92         }
93
94         bufs.Put(buf)
95
96         if bytes.Compare(buf, TestBlock) != 0 {
97                 t.Errorf("expected %s, got %s", string(TestBlock), string(buf))
98         }
99 }
100
101 // Invoke get on a block that does not exist in volume; should result in error
102 // Test should pass for both writable and read-only volumes
103 func testGetNoSuchBlock(t TB, factory TestableVolumeFactory) {
104         v := factory(t)
105         defer v.Teardown()
106
107         if _, err := v.Get(TestHash2); err == nil {
108                 t.Errorf("Expected error while getting non-existing block %v", TestHash2)
109         }
110 }
111
112 // Compare() should return os.ErrNotExist if the block does not exist.
113 // Otherwise, writing new data causes CompareAndTouch() to generate
114 // error logs even though everything is working fine.
115 func testCompareNonexistent(t TB, factory TestableVolumeFactory) {
116         v := factory(t)
117         defer v.Teardown()
118
119         err := v.Compare(TestHash, TestBlock)
120         if err != os.ErrNotExist {
121                 t.Errorf("Got err %T %q, expected os.ErrNotExist", err, err)
122         }
123 }
124
125 // Put a test block and compare the locator with same content
126 // Test should pass for both writable and read-only volumes
127 func testCompareSameContent(t TB, factory TestableVolumeFactory, testHash string, testData []byte) {
128         v := factory(t)
129         defer v.Teardown()
130
131         v.PutRaw(testHash, testData)
132
133         // Compare the block locator with same content
134         err := v.Compare(testHash, testData)
135         if err != nil {
136                 t.Errorf("Got err %q, expected nil", err)
137         }
138 }
139
140 // Test behavior of Compare() when stored data matches expected
141 // checksum but differs from new data we need to store. Requires
142 // testHash = md5(testDataA).
143 //
144 // Test should pass for both writable and read-only volumes
145 func testCompareWithCollision(t TB, factory TestableVolumeFactory, testHash string, testDataA, testDataB []byte) {
146         v := factory(t)
147         defer v.Teardown()
148
149         v.PutRaw(testHash, testDataA)
150
151         // Compare the block locator with different content; collision
152         err := v.Compare(TestHash, testDataB)
153         if err == nil {
154                 t.Errorf("Got err nil, expected error due to collision")
155         }
156 }
157
158 // Test behavior of Compare() when stored data has become
159 // corrupted. Requires testHash = md5(testDataA) != md5(testDataB).
160 //
161 // Test should pass for both writable and read-only volumes
162 func testCompareWithCorruptStoredData(t TB, factory TestableVolumeFactory, testHash string, testDataA, testDataB []byte) {
163         v := factory(t)
164         defer v.Teardown()
165
166         v.PutRaw(TestHash, testDataB)
167
168         err := v.Compare(testHash, testDataA)
169         if err == nil || err == CollisionError {
170                 t.Errorf("Got err %+v, expected non-collision error", err)
171         }
172 }
173
174 // Put a block and put again with same content
175 // Test is intended for only writable volumes
176 func testPutBlockWithSameContent(t TB, factory TestableVolumeFactory, testHash string, testData []byte) {
177         v := factory(t)
178         defer v.Teardown()
179
180         if v.Writable() == false {
181                 return
182         }
183
184         err := v.Put(testHash, testData)
185         if err != nil {
186                 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock, err)
187         }
188
189         err = v.Put(testHash, testData)
190         if err != nil {
191                 t.Errorf("Got err putting block second time %q: %q, expected nil", TestBlock, err)
192         }
193 }
194
195 // Put a block and put again with different content
196 // Test is intended for only writable volumes
197 func testPutBlockWithDifferentContent(t TB, factory TestableVolumeFactory, testHash string, testDataA, testDataB []byte) {
198         v := factory(t)
199         defer v.Teardown()
200
201         if v.Writable() == false {
202                 return
203         }
204
205         v.PutRaw(testHash, testDataA)
206
207         putErr := v.Put(testHash, testDataB)
208         buf, getErr := v.Get(testHash)
209         if putErr == nil {
210                 // Put must not return a nil error unless it has
211                 // overwritten the existing data.
212                 if bytes.Compare(buf, testDataB) != 0 {
213                         t.Errorf("Put succeeded but Get returned %+q, expected %+q", buf, testDataB)
214                 }
215         } else {
216                 // It is permissible for Put to fail, but it must
217                 // leave us with either the original data, the new
218                 // data, or nothing at all.
219                 if getErr == nil && bytes.Compare(buf, testDataA) != 0 && bytes.Compare(buf, testDataB) != 0 {
220                         t.Errorf("Put failed but Get returned %+q, which is neither %+q nor %+q", buf, testDataA, testDataB)
221                 }
222         }
223         if getErr == nil {
224                 bufs.Put(buf)
225         }
226 }
227
228 // Put and get multiple blocks
229 // Test is intended for only writable volumes
230 func testPutMultipleBlocks(t TB, factory TestableVolumeFactory) {
231         v := factory(t)
232         defer v.Teardown()
233
234         if v.Writable() == false {
235                 return
236         }
237
238         err := v.Put(TestHash, TestBlock)
239         if err != nil {
240                 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock, err)
241         }
242
243         err = v.Put(TestHash2, TestBlock2)
244         if err != nil {
245                 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock2, err)
246         }
247
248         err = v.Put(TestHash3, TestBlock3)
249         if err != nil {
250                 t.Errorf("Got err putting block %q: %q, expected nil", TestBlock3, err)
251         }
252
253         data, err := v.Get(TestHash)
254         if err != nil {
255                 t.Error(err)
256         } else {
257                 if bytes.Compare(data, TestBlock) != 0 {
258                         t.Errorf("Block present, but got %+q, expected %+q", data, TestBlock)
259                 }
260                 bufs.Put(data)
261         }
262
263         data, err = v.Get(TestHash2)
264         if err != nil {
265                 t.Error(err)
266         } else {
267                 if bytes.Compare(data, TestBlock2) != 0 {
268                         t.Errorf("Block present, but got %+q, expected %+q", data, TestBlock2)
269                 }
270                 bufs.Put(data)
271         }
272
273         data, err = v.Get(TestHash3)
274         if err != nil {
275                 t.Error(err)
276         } else {
277                 if bytes.Compare(data, TestBlock3) != 0 {
278                         t.Errorf("Block present, but to %+q, expected %+q", data, TestBlock3)
279                 }
280                 bufs.Put(data)
281         }
282 }
283
284 // testPutAndTouch
285 //   Test that when applying PUT to a block that already exists,
286 //   the block's modification time is updated.
287 // Test is intended for only writable volumes
288 func testPutAndTouch(t TB, factory TestableVolumeFactory) {
289         v := factory(t)
290         defer v.Teardown()
291
292         if v.Writable() == false {
293                 return
294         }
295
296         if err := v.Put(TestHash, TestBlock); err != nil {
297                 t.Error(err)
298         }
299
300         // We'll verify { t0 < threshold < t1 }, where t0 is the
301         // existing block's timestamp on disk before Put() and t1 is
302         // its timestamp after Put().
303         threshold := time.Now().Add(-time.Second)
304
305         // Set the stored block's mtime far enough in the past that we
306         // can see the difference between "timestamp didn't change"
307         // and "timestamp granularity is too low".
308         v.TouchWithDate(TestHash, time.Now().Add(-20*time.Second))
309
310         // Make sure v.Mtime() agrees the above Utime really worked.
311         if t0, err := v.Mtime(TestHash); err != nil || t0.IsZero() || !t0.Before(threshold) {
312                 t.Errorf("Setting mtime failed: %v, %v", t0, err)
313         }
314
315         // Write the same block again.
316         if err := v.Put(TestHash, TestBlock); err != nil {
317                 t.Error(err)
318         }
319
320         // Verify threshold < t1
321         if t1, err := v.Mtime(TestHash); err != nil {
322                 t.Error(err)
323         } else if t1.Before(threshold) {
324                 t.Errorf("t1 %v should be >= threshold %v after v.Put ", t1, threshold)
325         }
326 }
327
328 // Touching a non-existing block should result in error.
329 // Test should pass for both writable and read-only volumes
330 func testTouchNoSuchBlock(t TB, factory TestableVolumeFactory) {
331         v := factory(t)
332         defer v.Teardown()
333
334         if err := v.Touch(TestHash); err == nil {
335                 t.Error("Expected error when attempted to touch a non-existing block")
336         }
337 }
338
339 // Invoking Mtime on a non-existing block should result in error.
340 // Test should pass for both writable and read-only volumes
341 func testMtimeNoSuchBlock(t TB, factory TestableVolumeFactory) {
342         v := factory(t)
343         defer v.Teardown()
344
345         if _, err := v.Mtime("12345678901234567890123456789012"); err == nil {
346                 t.Error("Expected error when updating Mtime on a non-existing block")
347         }
348 }
349
350 // Put a few blocks and invoke IndexTo with:
351 // * no prefix
352 // * with a prefix
353 // * with no such prefix
354 // Test should pass for both writable and read-only volumes
355 func testIndexTo(t TB, factory TestableVolumeFactory) {
356         v := factory(t)
357         defer v.Teardown()
358
359         v.PutRaw(TestHash, TestBlock)
360         v.PutRaw(TestHash2, TestBlock2)
361         v.PutRaw(TestHash3, TestBlock3)
362
363         // Blocks whose names aren't Keep hashes should be omitted from
364         // index
365         v.PutRaw("fffffffffnotreallyahashfffffffff", nil)
366         v.PutRaw("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", nil)
367         v.PutRaw("f0000000000000000000000000000000f", nil)
368         v.PutRaw("f00", nil)
369
370         buf := new(bytes.Buffer)
371         v.IndexTo("", buf)
372         indexRows := strings.Split(string(buf.Bytes()), "\n")
373         sort.Strings(indexRows)
374         sortedIndex := strings.Join(indexRows, "\n")
375         m, err := regexp.MatchString(
376                 `^\n`+TestHash+`\+\d+ \d+\n`+
377                         TestHash3+`\+\d+ \d+\n`+
378                         TestHash2+`\+\d+ \d+$`,
379                 sortedIndex)
380         if err != nil {
381                 t.Error(err)
382         } else if !m {
383                 t.Errorf("Got index %q for empty prefix", sortedIndex)
384         }
385
386         for _, prefix := range []string{"f", "f15", "f15ac"} {
387                 buf = new(bytes.Buffer)
388                 v.IndexTo(prefix, buf)
389
390                 m, err := regexp.MatchString(`^`+TestHash2+`\+\d+ \d+\n$`, string(buf.Bytes()))
391                 if err != nil {
392                         t.Error(err)
393                 } else if !m {
394                         t.Errorf("Got index %q for prefix %s", string(buf.Bytes()), prefix)
395                 }
396         }
397
398         for _, prefix := range []string{"zero", "zip", "zilch"} {
399                 buf = new(bytes.Buffer)
400                 v.IndexTo(prefix, buf)
401                 if err != nil {
402                         t.Errorf("Got error on IndexTo with no such prefix %v", err.Error())
403                 } else if buf.Len() != 0 {
404                         t.Errorf("Expected empty list for IndexTo with no such prefix %s", prefix)
405                 }
406         }
407 }
408
409 // Calling Delete() for a block immediately after writing it (not old enough)
410 // should neither delete the data nor return an error.
411 // Test is intended for only writable volumes
412 func testDeleteNewBlock(t TB, factory TestableVolumeFactory) {
413         v := factory(t)
414         defer v.Teardown()
415         blobSignatureTTL = 300 * time.Second
416
417         if v.Writable() == false {
418                 return
419         }
420
421         v.Put(TestHash, TestBlock)
422
423         if err := v.Trash(TestHash); err != nil {
424                 t.Error(err)
425         }
426         data, err := v.Get(TestHash)
427         if err != nil {
428                 t.Error(err)
429         } else {
430                 if bytes.Compare(data, TestBlock) != 0 {
431                         t.Errorf("Got data %+q, expected %+q", data, TestBlock)
432                 }
433                 bufs.Put(data)
434         }
435 }
436
437 // Calling Delete() for a block with a timestamp older than
438 // blobSignatureTTL seconds in the past should delete the data.
439 // Test is intended for only writable volumes
440 func testDeleteOldBlock(t TB, factory TestableVolumeFactory) {
441         v := factory(t)
442         defer v.Teardown()
443         blobSignatureTTL = 300 * time.Second
444
445         if v.Writable() == false {
446                 return
447         }
448
449         v.Put(TestHash, TestBlock)
450         v.TouchWithDate(TestHash, time.Now().Add(-2*blobSignatureTTL))
451
452         if err := v.Trash(TestHash); err != nil {
453                 t.Error(err)
454         }
455         if _, err := v.Get(TestHash); err == nil || !os.IsNotExist(err) {
456                 t.Errorf("os.IsNotExist(%v) should have been true", err)
457         }
458 }
459
460 // Calling Delete() for a block that does not exist should result in error.
461 // Test should pass for both writable and read-only volumes
462 func testDeleteNoSuchBlock(t TB, factory TestableVolumeFactory) {
463         v := factory(t)
464         defer v.Teardown()
465
466         if err := v.Trash(TestHash2); err == nil {
467                 t.Errorf("Expected error when attempting to delete a non-existing block")
468         }
469 }
470
471 // Invoke Status and verify that VolumeStatus is returned
472 // Test should pass for both writable and read-only volumes
473 func testStatus(t TB, factory TestableVolumeFactory) {
474         v := factory(t)
475         defer v.Teardown()
476
477         // Get node status and make a basic sanity check.
478         status := v.Status()
479         if status.DeviceNum == 0 {
480                 t.Errorf("uninitialized device_num in %v", status)
481         }
482
483         if status.BytesFree == 0 {
484                 t.Errorf("uninitialized bytes_free in %v", status)
485         }
486
487         if status.BytesUsed == 0 {
488                 t.Errorf("uninitialized bytes_used in %v", status)
489         }
490 }
491
492 // Invoke String for the volume; expect non-empty result
493 // Test should pass for both writable and read-only volumes
494 func testString(t TB, factory TestableVolumeFactory) {
495         v := factory(t)
496         defer v.Teardown()
497
498         if id := v.String(); len(id) == 0 {
499                 t.Error("Got empty string for v.String()")
500         }
501 }
502
503 // Putting, updating, touching, and deleting blocks from a read-only volume result in error.
504 // Test is intended for only read-only volumes
505 func testUpdateReadOnly(t TB, factory TestableVolumeFactory) {
506         v := factory(t)
507         defer v.Teardown()
508
509         if v.Writable() == true {
510                 return
511         }
512
513         v.PutRaw(TestHash, TestBlock)
514
515         // Get from read-only volume should succeed
516         _, err := v.Get(TestHash)
517         if err != nil {
518                 t.Errorf("got err %v, expected nil", err)
519         }
520
521         // Put a new block to read-only volume should result in error
522         err = v.Put(TestHash2, TestBlock2)
523         if err == nil {
524                 t.Errorf("Expected error when putting block in a read-only volume")
525         }
526         _, err = v.Get(TestHash2)
527         if err == nil {
528                 t.Errorf("Expected error when getting block whose put in read-only volume failed")
529         }
530
531         // Touch a block in read-only volume should result in error
532         err = v.Touch(TestHash)
533         if err == nil {
534                 t.Errorf("Expected error when touching block in a read-only volume")
535         }
536
537         // Delete a block from a read-only volume should result in error
538         err = v.Trash(TestHash)
539         if err == nil {
540                 t.Errorf("Expected error when deleting block from a read-only volume")
541         }
542
543         // Overwriting an existing block in read-only volume should result in error
544         err = v.Put(TestHash, TestBlock)
545         if err == nil {
546                 t.Errorf("Expected error when putting block in a read-only volume")
547         }
548 }
549
550 // Launch concurrent Gets
551 // Test should pass for both writable and read-only volumes
552 func testGetConcurrent(t TB, factory TestableVolumeFactory) {
553         v := factory(t)
554         defer v.Teardown()
555
556         v.PutRaw(TestHash, TestBlock)
557         v.PutRaw(TestHash2, TestBlock2)
558         v.PutRaw(TestHash3, TestBlock3)
559
560         sem := make(chan int)
561         go func(sem chan int) {
562                 buf, err := v.Get(TestHash)
563                 if err != nil {
564                         t.Errorf("err1: %v", err)
565                 }
566                 bufs.Put(buf)
567                 if bytes.Compare(buf, TestBlock) != 0 {
568                         t.Errorf("buf should be %s, is %s", string(TestBlock), string(buf))
569                 }
570                 sem <- 1
571         }(sem)
572
573         go func(sem chan int) {
574                 buf, err := v.Get(TestHash2)
575                 if err != nil {
576                         t.Errorf("err2: %v", err)
577                 }
578                 bufs.Put(buf)
579                 if bytes.Compare(buf, TestBlock2) != 0 {
580                         t.Errorf("buf should be %s, is %s", string(TestBlock2), string(buf))
581                 }
582                 sem <- 1
583         }(sem)
584
585         go func(sem chan int) {
586                 buf, err := v.Get(TestHash3)
587                 if err != nil {
588                         t.Errorf("err3: %v", err)
589                 }
590                 bufs.Put(buf)
591                 if bytes.Compare(buf, TestBlock3) != 0 {
592                         t.Errorf("buf should be %s, is %s", string(TestBlock3), string(buf))
593                 }
594                 sem <- 1
595         }(sem)
596
597         // Wait for all goroutines to finish
598         for done := 0; done < 3; {
599                 done += <-sem
600         }
601 }
602
603 // Launch concurrent Puts
604 // Test is intended for only writable volumes
605 func testPutConcurrent(t TB, factory TestableVolumeFactory) {
606         v := factory(t)
607         defer v.Teardown()
608
609         if v.Writable() == false {
610                 return
611         }
612
613         sem := make(chan int)
614         go func(sem chan int) {
615                 err := v.Put(TestHash, TestBlock)
616                 if err != nil {
617                         t.Errorf("err1: %v", err)
618                 }
619                 sem <- 1
620         }(sem)
621
622         go func(sem chan int) {
623                 err := v.Put(TestHash2, TestBlock2)
624                 if err != nil {
625                         t.Errorf("err2: %v", err)
626                 }
627                 sem <- 1
628         }(sem)
629
630         go func(sem chan int) {
631                 err := v.Put(TestHash3, TestBlock3)
632                 if err != nil {
633                         t.Errorf("err3: %v", err)
634                 }
635                 sem <- 1
636         }(sem)
637
638         // Wait for all goroutines to finish
639         for done := 0; done < 3; {
640                 done += <-sem
641         }
642
643         // Double check that we actually wrote the blocks we expected to write.
644         buf, err := v.Get(TestHash)
645         if err != nil {
646                 t.Errorf("Get #1: %v", err)
647         }
648         bufs.Put(buf)
649         if bytes.Compare(buf, TestBlock) != 0 {
650                 t.Errorf("Get #1: expected %s, got %s", string(TestBlock), string(buf))
651         }
652
653         buf, err = v.Get(TestHash2)
654         if err != nil {
655                 t.Errorf("Get #2: %v", err)
656         }
657         bufs.Put(buf)
658         if bytes.Compare(buf, TestBlock2) != 0 {
659                 t.Errorf("Get #2: expected %s, got %s", string(TestBlock2), string(buf))
660         }
661
662         buf, err = v.Get(TestHash3)
663         if err != nil {
664                 t.Errorf("Get #3: %v", err)
665         }
666         bufs.Put(buf)
667         if bytes.Compare(buf, TestBlock3) != 0 {
668                 t.Errorf("Get #3: expected %s, got %s", string(TestBlock3), string(buf))
669         }
670 }
671
672 // Write and read back a full size block
673 func testPutFullBlock(t TB, factory TestableVolumeFactory) {
674         v := factory(t)
675         defer v.Teardown()
676
677         if !v.Writable() {
678                 return
679         }
680
681         wdata := make([]byte, BlockSize)
682         wdata[0] = 'a'
683         wdata[BlockSize-1] = 'z'
684         hash := fmt.Sprintf("%x", md5.Sum(wdata))
685         err := v.Put(hash, wdata)
686         if err != nil {
687                 t.Fatal(err)
688         }
689         rdata, err := v.Get(hash)
690         if err != nil {
691                 t.Error(err)
692         } else {
693                 defer bufs.Put(rdata)
694         }
695         if bytes.Compare(rdata, wdata) != 0 {
696                 t.Error("rdata != wdata")
697         }
698 }