Merge branch '2449-keep-write-blocks' into 2449-keep-flags
[arvados.git] / services / keep / keep_test.go
1 package main
2
3 import (
4         "bytes"
5         "fmt"
6         "io/ioutil"
7         "os"
8         "path"
9         "testing"
10 )
11
12 var TEST_BLOCK = []byte("The quick brown fox jumps over the lazy dog.")
13 var TEST_HASH = "e4d909c290d0fb1ca068ffaddf22cbd0"
14 var BAD_BLOCK = []byte("The magic words are squeamish ossifrage.")
15
16 // TODO(twp): Tests still to be written
17 //
18 //   * PutBlockFull
19 //       - test that PutBlock returns 503 Full if the filesystem is full.
20 //         (must mock FreeDiskSpace or Statfs? use a tmpfs?)
21 //
22 //   * PutBlockWriteErr
23 //       - test the behavior when Write returns an error.
24 //           - Possible solutions: use a small tmpfs and a high
25 //             MIN_FREE_KILOBYTES to trick PutBlock into attempting
26 //             to write a block larger than the amount of space left
27 //           - use an interface to mock ioutil.TempFile with a File
28 //             object that always returns an error on write
29 //
30 // ========================================
31 // GetBlock tests.
32 // ========================================
33
34 // TestGetBlock
35 //     Test that simple block reads succeed.
36 //
37 func TestGetBlock(t *testing.T) {
38         defer teardown()
39
40         // Prepare two test Keep volumes. Our block is stored on the second volume.
41         KeepVolumes = setup(t, 2)
42         store(t, KeepVolumes[1], TEST_HASH, TEST_BLOCK)
43
44         // Check that GetBlock returns success.
45         result, err := GetBlock(TEST_HASH)
46         if err != nil {
47                 t.Errorf("GetBlock error: %s", err)
48         }
49         if fmt.Sprint(result) != fmt.Sprint(TEST_BLOCK) {
50                 t.Errorf("expected %s, got %s", TEST_BLOCK, result)
51         }
52 }
53
54 // TestGetBlockMissing
55 //     GetBlock must return an error when the block is not found.
56 //
57 func TestGetBlockMissing(t *testing.T) {
58         defer teardown()
59
60         // Create two empty test Keep volumes.
61         KeepVolumes = setup(t, 2)
62
63         // Check that GetBlock returns failure.
64         result, err := GetBlock(TEST_HASH)
65         if err == nil {
66                 t.Errorf("GetBlock incorrectly returned success: ", result)
67         } else {
68                 ke := err.(*KeepError)
69                 if ke.HTTPCode != ErrNotFound {
70                         t.Errorf("GetBlock: %v", ke)
71                 }
72         }
73 }
74
75 // TestGetBlockCorrupt
76 //     GetBlock must return an error when a corrupted block is requested
77 //     (the contents of the file do not checksum to its hash).
78 //
79 func TestGetBlockCorrupt(t *testing.T) {
80         defer teardown()
81
82         // Create two test Keep volumes and store a block in each of them,
83         // but the hash of the block does not match the filename.
84         KeepVolumes = setup(t, 2)
85         for _, vol := range KeepVolumes {
86                 store(t, vol, TEST_HASH, BAD_BLOCK)
87         }
88
89         // Check that GetBlock returns failure.
90         result, err := GetBlock(TEST_HASH)
91         if err == nil {
92                 t.Errorf("GetBlock incorrectly returned success: %s", result)
93         }
94 }
95
96 // ========================================
97 // PutBlock tests
98 // ========================================
99
100 // TestPutBlockOK
101 //     PutBlock can perform a simple block write and returns success.
102 //
103 func TestPutBlockOK(t *testing.T) {
104         defer teardown()
105
106         // Create two test Keep volumes.
107         KeepVolumes = setup(t, 2)
108
109         // Check that PutBlock stores the data as expected.
110         if err := PutBlock(TEST_BLOCK, TEST_HASH); err != nil {
111                 t.Fatalf("PutBlock: %v", err)
112         }
113
114         result, err := GetBlock(TEST_HASH)
115         if err != nil {
116                 t.Fatalf("GetBlock: %s", err.Error())
117         }
118         if string(result) != string(TEST_BLOCK) {
119                 t.Error("PutBlock/GetBlock mismatch")
120                 t.Fatalf("PutBlock stored '%s', GetBlock retrieved '%s'",
121                         string(TEST_BLOCK), string(result))
122         }
123 }
124
125 // TestPutBlockOneVol
126 //     PutBlock still returns success even when only one of the known
127 //     volumes is online.
128 //
129 func TestPutBlockOneVol(t *testing.T) {
130         defer teardown()
131
132         // Create two test Keep volumes, but cripple one of them.
133         KeepVolumes = setup(t, 2)
134         os.Chmod(KeepVolumes[0], 000)
135
136         // Check that PutBlock stores the data as expected.
137         if err := PutBlock(TEST_BLOCK, TEST_HASH); err != nil {
138                 t.Fatalf("PutBlock: %v", err)
139         }
140
141         result, err := GetBlock(TEST_HASH)
142         if err != nil {
143                 t.Fatalf("GetBlock: %s", err.Error())
144         }
145         if string(result) != string(TEST_BLOCK) {
146                 t.Error("PutBlock/GetBlock mismatch")
147                 t.Fatalf("PutBlock stored '%s', GetBlock retrieved '%s'",
148                         string(TEST_BLOCK), string(result))
149         }
150 }
151
152 // TestPutBlockMD5Fail
153 //     Check that PutBlock returns an error if passed a block and hash that
154 //     do not match.
155 //
156 func TestPutBlockMD5Fail(t *testing.T) {
157         defer teardown()
158
159         // Create two test Keep volumes.
160         KeepVolumes = setup(t, 2)
161
162         // Check that PutBlock returns the expected error when the hash does
163         // not match the block.
164         if err := PutBlock(BAD_BLOCK, TEST_HASH); err == nil {
165                 t.Error("PutBlock succeeded despite a block mismatch")
166         } else {
167                 ke := err.(*KeepError)
168                 if ke.HTTPCode != ErrMD5Fail {
169                         t.Errorf("PutBlock returned the wrong error (%v)", ke)
170                 }
171         }
172
173         // Confirm that GetBlock fails to return anything.
174         if result, err := GetBlock(TEST_HASH); err == nil {
175                 t.Errorf("GetBlock succeded after a corrupt block store, returned '%s'",
176                         string(result))
177         }
178 }
179
180 // TestPutBlockCorrupt
181 //     PutBlock should overwrite corrupt blocks on disk when given
182 //     a PUT request with a good block.
183 //
184 func TestPutBlockCorrupt(t *testing.T) {
185         defer teardown()
186
187         // Create two test Keep volumes.
188         KeepVolumes = setup(t, 2)
189
190         // Store a corrupted block under TEST_HASH.
191         store(t, KeepVolumes[0], TEST_HASH, BAD_BLOCK)
192         if err := PutBlock(TEST_BLOCK, TEST_HASH); err != nil {
193                 t.Errorf("PutBlock: %v", err)
194         }
195
196         // The block on disk should now match TEST_BLOCK.
197         if block, err := GetBlock(TEST_HASH); err != nil {
198                 t.Errorf("GetBlock: %v", err)
199         } else if bytes.Compare(block, TEST_BLOCK) != 0 {
200                 t.Errorf("GetBlock returned: '%s'", string(block))
201         }
202 }
203
204 // PutBlockCollision
205 //     PutBlock returns a 400 Collision error when attempting to
206 //     store a block that collides with another block on disk.
207 //
208 func TestPutBlockCollision(t *testing.T) {
209         defer teardown()
210
211         // These blocks both hash to the MD5 digest cee9a457e790cf20d4bdaa6d69f01e41.
212         var b1 = []byte("\x0e0eaU\x9a\xa7\x87\xd0\x0b\xc6\xf7\x0b\xbd\xfe4\x04\xcf\x03e\x9epO\x854\xc0\x0f\xfbe\x9cL\x87@\xcc\x94/\xeb-\xa1\x15\xa3\xf4\x15\\\xbb\x86\x07Is\x86em}\x1f4\xa4 Y\xd7\x8fZ\x8d\xd1\xef")
213         var b2 = []byte("\x0e0eaU\x9a\xa7\x87\xd0\x0b\xc6\xf7\x0b\xbd\xfe4\x04\xcf\x03e\x9etO\x854\xc0\x0f\xfbe\x9cL\x87@\xcc\x94/\xeb-\xa1\x15\xa3\xf4\x15\xdc\xbb\x86\x07Is\x86em}\x1f4\xa4 Y\xd7\x8fZ\x8d\xd1\xef")
214         var locator = "cee9a457e790cf20d4bdaa6d69f01e41"
215
216         // Prepare two test Keep volumes. Store one block,
217         // then attempt to store the other.
218         KeepVolumes = setup(t, 2)
219         store(t, KeepVolumes[1], locator, b1)
220
221         if err := PutBlock(b2, locator); err == nil {
222                 t.Error("PutBlock did not report a collision")
223         } else if err.(*KeepError).HTTPCode != ErrCollision {
224                 t.Errorf("PutBlock returned %v", err)
225         }
226 }
227
228 // ========================================
229 // FindKeepVolumes tests.
230 // ========================================
231
232 // TestFindKeepVolumes
233 //     Confirms that FindKeepVolumes finds tmpfs volumes with "/keep"
234 //     directories at the top level.
235 //
236 func TestFindKeepVolumes(t *testing.T) {
237         defer teardown()
238
239         // Initialize two keep volumes.
240         var tempVols []string = setup(t, 2)
241
242         // Set up a bogus PROC_MOUNTS file.
243         if f, err := ioutil.TempFile("", "keeptest"); err == nil {
244                 for _, vol := range tempVols {
245                         fmt.Fprintf(f, "tmpfs %s tmpfs opts\n", path.Dir(vol))
246                 }
247                 f.Close()
248                 PROC_MOUNTS = f.Name()
249
250                 // Check that FindKeepVolumes finds the temp volumes.
251                 resultVols := FindKeepVolumes()
252                 if len(tempVols) != len(resultVols) {
253                         t.Fatalf("set up %d volumes, FindKeepVolumes found %d\n",
254                                 len(tempVols), len(resultVols))
255                 }
256                 for i := range tempVols {
257                         if tempVols[i] != resultVols[i] {
258                                 t.Errorf("FindKeepVolumes returned %s, expected %s\n",
259                                         resultVols[i], tempVols[i])
260                         }
261                 }
262
263                 os.Remove(f.Name())
264         }
265 }
266
267 // TestFindKeepVolumesFail
268 //     When no Keep volumes are present, FindKeepVolumes returns an empty slice.
269 //
270 func TestFindKeepVolumesFail(t *testing.T) {
271         defer teardown()
272
273         // Set up a bogus PROC_MOUNTS file with no Keep vols.
274         if f, err := ioutil.TempFile("", "keeptest"); err == nil {
275                 fmt.Fprintln(f, "rootfs / rootfs opts 0 0")
276                 fmt.Fprintln(f, "sysfs /sys sysfs opts 0 0")
277                 fmt.Fprintln(f, "proc /proc proc opts 0 0")
278                 fmt.Fprintln(f, "udev /dev devtmpfs opts 0 0")
279                 fmt.Fprintln(f, "devpts /dev/pts devpts opts 0 0")
280                 f.Close()
281                 PROC_MOUNTS = f.Name()
282
283                 // Check that FindKeepVolumes returns an empty array.
284                 resultVols := FindKeepVolumes()
285                 if len(resultVols) != 0 {
286                         t.Fatalf("FindKeepVolumes returned %v", resultVols)
287                 }
288
289                 os.Remove(PROC_MOUNTS)
290         }
291 }
292
293 // ========================================
294 // Helper functions for unit tests.
295 // ========================================
296
297 // setup
298 //     Create KeepVolumes for testing.
299 //     Returns a slice of pathnames to temporary Keep volumes.
300 //
301 func setup(t *testing.T, num_volumes int) []string {
302         vols := make([]string, num_volumes)
303         for i := range vols {
304                 if dir, err := ioutil.TempDir(os.TempDir(), "keeptest"); err == nil {
305                         vols[i] = dir + "/keep"
306                         os.Mkdir(vols[i], 0755)
307                 } else {
308                         t.Fatal(err)
309                 }
310         }
311         return vols
312 }
313
314 // teardown
315 //     Cleanup to perform after each test.
316 //
317 func teardown() {
318         for _, vol := range KeepVolumes {
319                 os.RemoveAll(path.Dir(vol))
320         }
321         KeepVolumes = nil
322 }
323
324 // store
325 //     Low-level code to write Keep blocks directly to disk for testing.
326 //
327 func store(t *testing.T, keepdir string, filename string, block []byte) {
328         blockdir := fmt.Sprintf("%s/%s", keepdir, filename[:3])
329         if err := os.MkdirAll(blockdir, 0755); err != nil {
330                 t.Fatal(err)
331         }
332
333         blockpath := fmt.Sprintf("%s/%s", blockdir, filename)
334         if f, err := os.Create(blockpath); err == nil {
335                 f.Write(block)
336                 f.Close()
337         } else {
338                 t.Fatal(err)
339         }
340 }