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