Merge branch 'master' into 8936-ttl-in-signing-key
[arvados.git] / tools / keep-rsync / keep-rsync_test.go
1 package main
2
3 import (
4         "crypto/md5"
5         "fmt"
6         "io/ioutil"
7         "log"
8         "os"
9         "strings"
10         "testing"
11         "time"
12
13         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
14         "git.curoverse.com/arvados.git/sdk/go/keepclient"
15
16         . "gopkg.in/check.v1"
17 )
18
19 // Gocheck boilerplate
20 func Test(t *testing.T) {
21         TestingT(t)
22 }
23
24 // Gocheck boilerplate
25 var _ = Suite(&ServerRequiredSuite{})
26 var _ = Suite(&ServerNotRequiredSuite{})
27 var _ = Suite(&DoMainTestSuite{})
28
29 // Tests that require the Keep server running
30 type ServerRequiredSuite struct{}
31 type ServerNotRequiredSuite struct{}
32 type DoMainTestSuite struct{}
33
34 func (s *ServerRequiredSuite) SetUpSuite(c *C) {
35         // Start API server
36         arvadostest.StartAPI()
37 }
38
39 func (s *ServerRequiredSuite) TearDownSuite(c *C) {
40         arvadostest.StopAPI()
41         arvadostest.ResetEnv()
42 }
43
44 var initialArgs []string
45
46 func (s *DoMainTestSuite) SetUpSuite(c *C) {
47         initialArgs = os.Args
48 }
49
50 var kcSrc, kcDst *keepclient.KeepClient
51 var srcKeepServicesJSON, dstKeepServicesJSON, blobSigningKey string
52 var blobSignatureTTL = time.Duration(2*7*24) * time.Hour
53
54 func (s *ServerRequiredSuite) SetUpTest(c *C) {
55         // reset all variables between tests
56         blobSigningKey = ""
57         srcKeepServicesJSON = ""
58         dstKeepServicesJSON = ""
59         kcSrc = &keepclient.KeepClient{}
60         kcDst = &keepclient.KeepClient{}
61 }
62
63 func (s *ServerRequiredSuite) TearDownTest(c *C) {
64         arvadostest.StopKeep(3)
65 }
66
67 func (s *DoMainTestSuite) SetUpTest(c *C) {
68         args := []string{"keep-rsync"}
69         os.Args = args
70 }
71
72 func (s *DoMainTestSuite) TearDownTest(c *C) {
73         os.Args = initialArgs
74 }
75
76 var testKeepServicesJSON = "{ \"kind\":\"arvados#keepServiceList\", \"etag\":\"\", \"self_link\":\"\", \"offset\":null, \"limit\":null, \"items\":[ { \"href\":\"/keep_services/zzzzz-bi6l4-123456789012340\", \"kind\":\"arvados#keepService\", \"etag\":\"641234567890enhj7hzx432e5\", \"uuid\":\"zzzzz-bi6l4-123456789012340\", \"owner_uuid\":\"zzzzz-tpzed-123456789012345\", \"service_host\":\"keep0.zzzzz.arvadosapi.com\", \"service_port\":25107, \"service_ssl_flag\":false, \"service_type\":\"disk\", \"read_only\":false }, { \"href\":\"/keep_services/zzzzz-bi6l4-123456789012341\", \"kind\":\"arvados#keepService\", \"etag\":\"641234567890enhj7hzx432e5\", \"uuid\":\"zzzzz-bi6l4-123456789012341\", \"owner_uuid\":\"zzzzz-tpzed-123456789012345\", \"service_host\":\"keep0.zzzzz.arvadosapi.com\", \"service_port\":25108, \"service_ssl_flag\":false, \"service_type\":\"disk\", \"read_only\":false } ], \"items_available\":2 }"
77
78 // Testing keep-rsync needs two sets of keep services: src and dst.
79 // The test setup hence creates 3 servers instead of the default 2,
80 // and uses the first 2 as src and the 3rd as dst keep servers.
81 func setupRsync(c *C, enforcePermissions bool, replications int) {
82         // srcConfig
83         var srcConfig apiConfig
84         srcConfig.APIHost = os.Getenv("ARVADOS_API_HOST")
85         srcConfig.APIToken = arvadostest.DataManagerToken
86         srcConfig.APIHostInsecure = matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
87
88         // dstConfig
89         var dstConfig apiConfig
90         dstConfig.APIHost = os.Getenv("ARVADOS_API_HOST")
91         dstConfig.APIToken = arvadostest.DataManagerToken
92         dstConfig.APIHostInsecure = matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
93
94         if enforcePermissions {
95                 blobSigningKey = arvadostest.BlobSigningKey
96         }
97
98         // Start Keep servers
99         arvadostest.StartKeep(3, enforcePermissions)
100
101         // setup keepclients
102         var err error
103         kcSrc, _, err = setupKeepClient(srcConfig, srcKeepServicesJSON, false, 0, blobSignatureTTL)
104         c.Check(err, IsNil)
105
106         kcDst, _, err = setupKeepClient(dstConfig, dstKeepServicesJSON, true, replications, 0)
107         c.Check(err, IsNil)
108
109         for uuid := range kcSrc.LocalRoots() {
110                 if strings.HasSuffix(uuid, "02") {
111                         delete(kcSrc.LocalRoots(), uuid)
112                 }
113         }
114         for uuid := range kcSrc.GatewayRoots() {
115                 if strings.HasSuffix(uuid, "02") {
116                         delete(kcSrc.GatewayRoots(), uuid)
117                 }
118         }
119         for uuid := range kcSrc.WritableLocalRoots() {
120                 if strings.HasSuffix(uuid, "02") {
121                         delete(kcSrc.WritableLocalRoots(), uuid)
122                 }
123         }
124
125         for uuid := range kcDst.LocalRoots() {
126                 if strings.HasSuffix(uuid, "00") || strings.HasSuffix(uuid, "01") {
127                         delete(kcDst.LocalRoots(), uuid)
128                 }
129         }
130         for uuid := range kcDst.GatewayRoots() {
131                 if strings.HasSuffix(uuid, "00") || strings.HasSuffix(uuid, "01") {
132                         delete(kcDst.GatewayRoots(), uuid)
133                 }
134         }
135         for uuid := range kcDst.WritableLocalRoots() {
136                 if strings.HasSuffix(uuid, "00") || strings.HasSuffix(uuid, "01") {
137                         delete(kcDst.WritableLocalRoots(), uuid)
138                 }
139         }
140
141         if replications == 0 {
142                 // Must have got default replications value of 2 from dst discovery document
143                 c.Assert(kcDst.Want_replicas, Equals, 2)
144         } else {
145                 // Since replications value is provided, it is used
146                 c.Assert(kcDst.Want_replicas, Equals, replications)
147         }
148 }
149
150 func (s *ServerRequiredSuite) TestRsyncPutInOne_GetFromOtherShouldFail(c *C) {
151         setupRsync(c, false, 1)
152
153         // Put a block in src and verify that it is not found in dst
154         testNoCrosstalk(c, "test-data-1", kcSrc, kcDst)
155
156         // Put a block in dst and verify that it is not found in src
157         testNoCrosstalk(c, "test-data-2", kcDst, kcSrc)
158 }
159
160 func (s *ServerRequiredSuite) TestRsyncWithBlobSigning_PutInOne_GetFromOtherShouldFail(c *C) {
161         setupRsync(c, true, 1)
162
163         // Put a block in src and verify that it is not found in dst
164         testNoCrosstalk(c, "test-data-1", kcSrc, kcDst)
165
166         // Put a block in dst and verify that it is not found in src
167         testNoCrosstalk(c, "test-data-2", kcDst, kcSrc)
168 }
169
170 // Do a Put in the first and Get from the second,
171 // which should raise block not found error.
172 func testNoCrosstalk(c *C, testData string, kc1, kc2 *keepclient.KeepClient) {
173         // Put a block using kc1
174         locator, _, err := kc1.PutB([]byte(testData))
175         c.Assert(err, Equals, nil)
176
177         locator = strings.Split(locator, "+")[0]
178         _, _, _, err = kc2.Get(keepclient.SignLocator(locator, kc2.Arvados.ApiToken, time.Now().AddDate(0, 0, 1), blobSignatureTTL, []byte(blobSigningKey)))
179         c.Assert(err, NotNil)
180         c.Check(err.Error(), Equals, "Block not found")
181 }
182
183 // Test keep-rsync initialization, with srcKeepServicesJSON
184 func (s *ServerRequiredSuite) TestRsyncInitializeWithKeepServicesJSON(c *C) {
185         srcKeepServicesJSON = testKeepServicesJSON
186
187         setupRsync(c, false, 1)
188
189         localRoots := kcSrc.LocalRoots()
190         c.Check(localRoots, NotNil)
191
192         foundIt := false
193         for k := range localRoots {
194                 if k == "zzzzz-bi6l4-123456789012340" {
195                         foundIt = true
196                 }
197         }
198         c.Check(foundIt, Equals, true)
199
200         foundIt = false
201         for k := range localRoots {
202                 if k == "zzzzz-bi6l4-123456789012341" {
203                         foundIt = true
204                 }
205         }
206         c.Check(foundIt, Equals, true)
207 }
208
209 // Test keep-rsync initialization with default replications count
210 func (s *ServerRequiredSuite) TestInitializeRsyncDefaultReplicationsCount(c *C) {
211         setupRsync(c, false, 0)
212 }
213
214 // Test keep-rsync initialization with replications count argument
215 func (s *ServerRequiredSuite) TestInitializeRsyncReplicationsCount(c *C) {
216         setupRsync(c, false, 3)
217 }
218
219 // Put some blocks in Src and some more in Dst
220 // And copy missing blocks from Src to Dst
221 func (s *ServerRequiredSuite) TestKeepRsync(c *C) {
222         testKeepRsync(c, false, "")
223 }
224
225 // Put some blocks in Src and some more in Dst with blob signing enabled.
226 // And copy missing blocks from Src to Dst
227 func (s *ServerRequiredSuite) TestKeepRsync_WithBlobSigning(c *C) {
228         testKeepRsync(c, true, "")
229 }
230
231 // Put some blocks in Src and some more in Dst
232 // Use prefix while doing rsync
233 // And copy missing blocks from Src to Dst
234 func (s *ServerRequiredSuite) TestKeepRsync_WithPrefix(c *C) {
235         data := []byte("test-data-4")
236         hash := fmt.Sprintf("%x", md5.Sum(data))
237
238         testKeepRsync(c, false, hash[0:3])
239         c.Check(len(dstIndex) > len(dstLocators), Equals, true)
240 }
241
242 // Put some blocks in Src and some more in Dst
243 // Use prefix not in src while doing rsync
244 // And copy missing blocks from Src to Dst
245 func (s *ServerRequiredSuite) TestKeepRsync_WithNoSuchPrefixInSrc(c *C) {
246         testKeepRsync(c, false, "999")
247         c.Check(len(dstIndex), Equals, len(dstLocators))
248 }
249
250 // Put 5 blocks in src. Put 2 of those blocks in dst
251 // Hence there are 3 additional blocks in src
252 // Also, put 2 extra blocks in dst; they are hence only in dst
253 // Run rsync and verify that those 7 blocks are now available in dst
254 func testKeepRsync(c *C, enforcePermissions bool, prefix string) {
255         setupRsync(c, enforcePermissions, 1)
256
257         // setupTestData
258         setupTestData(c, prefix)
259
260         err := performKeepRsync(kcSrc, kcDst, blobSignatureTTL, blobSigningKey, prefix)
261         c.Check(err, IsNil)
262
263         // Now GetIndex from dst and verify that all 5 from src and the 2 extra blocks are found
264         dstIndex, err = getUniqueLocators(kcDst, "")
265         c.Check(err, IsNil)
266
267         for _, locator := range srcLocatorsMatchingPrefix {
268                 _, ok := dstIndex[locator]
269                 c.Assert(ok, Equals, true)
270         }
271
272         for _, locator := range extraDstLocators {
273                 _, ok := dstIndex[locator]
274                 c.Assert(ok, Equals, true)
275         }
276
277         if prefix == "" {
278                 // all blocks from src and the two extra blocks
279                 c.Assert(len(dstIndex), Equals, len(srcLocators)+len(extraDstLocators))
280         } else {
281                 // 1 matching prefix and copied over, 2 that were initially copied into dst along with src, and the 2 extra blocks
282                 c.Assert(len(dstIndex), Equals, len(srcLocatorsMatchingPrefix)+len(extraDstLocators)+2)
283         }
284 }
285
286 // Setup test data in src and dst.
287 var srcLocators, srcLocatorsMatchingPrefix, dstLocators, extraDstLocators []string
288 var dstIndex map[string]bool
289
290 func setupTestData(c *C, indexPrefix string) {
291         srcLocators = []string{}
292         srcLocatorsMatchingPrefix = []string{}
293         dstLocators = []string{}
294         extraDstLocators = []string{}
295         dstIndex = make(map[string]bool)
296
297         // Put a few blocks in src using kcSrc
298         for i := 0; i < 5; i++ {
299                 hash, _, err := kcSrc.PutB([]byte(fmt.Sprintf("test-data-%d", i)))
300                 c.Check(err, IsNil)
301
302                 srcLocators = append(srcLocators, strings.Split(hash, "+A")[0])
303                 if strings.HasPrefix(hash, indexPrefix) {
304                         srcLocatorsMatchingPrefix = append(srcLocatorsMatchingPrefix, strings.Split(hash, "+A")[0])
305                 }
306         }
307
308         // Put first two of those src blocks in dst using kcDst
309         for i := 0; i < 2; i++ {
310                 hash, _, err := kcDst.PutB([]byte(fmt.Sprintf("test-data-%d", i)))
311                 c.Check(err, IsNil)
312                 dstLocators = append(dstLocators, strings.Split(hash, "+A")[0])
313         }
314
315         // Put two more blocks in dst; they are not in src at all
316         for i := 0; i < 2; i++ {
317                 hash, _, err := kcDst.PutB([]byte(fmt.Sprintf("other-data-%d", i)))
318                 c.Check(err, IsNil)
319                 dstLocators = append(dstLocators, strings.Split(hash, "+A")[0])
320                 extraDstLocators = append(extraDstLocators, strings.Split(hash, "+A")[0])
321         }
322 }
323
324 // Setup rsync using srcKeepServicesJSON with fake keepservers.
325 // Expect error during performKeepRsync due to unreachable src keepservers.
326 func (s *ServerRequiredSuite) TestErrorDuringRsync_FakeSrcKeepservers(c *C) {
327         srcKeepServicesJSON = testKeepServicesJSON
328
329         setupRsync(c, false, 1)
330
331         err := performKeepRsync(kcSrc, kcDst, blobSignatureTTL, "", "")
332         log.Printf("Err = %v", err)
333         c.Check(strings.Contains(err.Error(), "no such host"), Equals, true)
334 }
335
336 // Setup rsync using dstKeepServicesJSON with fake keepservers.
337 // Expect error during performKeepRsync due to unreachable dst keepservers.
338 func (s *ServerRequiredSuite) TestErrorDuringRsync_FakeDstKeepservers(c *C) {
339         dstKeepServicesJSON = testKeepServicesJSON
340
341         setupRsync(c, false, 1)
342
343         err := performKeepRsync(kcSrc, kcDst, blobSignatureTTL, "", "")
344         log.Printf("Err = %v", err)
345         c.Check(strings.Contains(err.Error(), "no such host"), Equals, true)
346 }
347
348 // Test rsync with signature error during Get from src.
349 func (s *ServerRequiredSuite) TestErrorDuringRsync_ErrorGettingBlockFromSrc(c *C) {
350         setupRsync(c, true, 1)
351
352         // put some blocks in src and dst
353         setupTestData(c, "")
354
355         // Change blob signing key to a fake key, so that Get from src fails
356         blobSigningKey = "thisisfakeblobsigningkey"
357
358         err := performKeepRsync(kcSrc, kcDst, blobSignatureTTL, blobSigningKey, "")
359         c.Check(strings.Contains(err.Error(), "HTTP 403 \"Forbidden\""), Equals, true)
360 }
361
362 // Test rsync with error during Put to src.
363 func (s *ServerRequiredSuite) TestErrorDuringRsync_ErrorPuttingBlockInDst(c *C) {
364         setupRsync(c, false, 1)
365
366         // put some blocks in src and dst
367         setupTestData(c, "")
368
369         // Increase Want_replicas on dst to result in insufficient replicas error during Put
370         kcDst.Want_replicas = 2
371
372         err := performKeepRsync(kcSrc, kcDst, blobSignatureTTL, blobSigningKey, "")
373         c.Check(strings.Contains(err.Error(), "Could not write sufficient replicas"), Equals, true)
374 }
375
376 // Test loadConfig func
377 func (s *ServerNotRequiredSuite) TestLoadConfig(c *C) {
378         // Setup a src config file
379         srcFile := setupConfigFile(c, "src-config")
380         defer os.Remove(srcFile.Name())
381         srcConfigFile := srcFile.Name()
382
383         // Setup a dst config file
384         dstFile := setupConfigFile(c, "dst-config")
385         defer os.Remove(dstFile.Name())
386         dstConfigFile := dstFile.Name()
387
388         // load configuration from those files
389         srcConfig, srcBlobSigningKey, err := loadConfig(srcConfigFile)
390         c.Check(err, IsNil)
391
392         c.Assert(srcConfig.APIHost, Equals, os.Getenv("ARVADOS_API_HOST"))
393         c.Assert(srcConfig.APIToken, Equals, arvadostest.DataManagerToken)
394         c.Assert(srcConfig.APIHostInsecure, Equals, matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")))
395         c.Assert(srcConfig.ExternalClient, Equals, false)
396
397         dstConfig, _, err := loadConfig(dstConfigFile)
398         c.Check(err, IsNil)
399
400         c.Assert(dstConfig.APIHost, Equals, os.Getenv("ARVADOS_API_HOST"))
401         c.Assert(dstConfig.APIToken, Equals, arvadostest.DataManagerToken)
402         c.Assert(dstConfig.APIHostInsecure, Equals, matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE")))
403         c.Assert(dstConfig.ExternalClient, Equals, false)
404
405         c.Assert(srcBlobSigningKey, Equals, "abcdefg")
406 }
407
408 // Test loadConfig func without setting up the config files
409 func (s *ServerNotRequiredSuite) TestLoadConfig_MissingSrcConfig(c *C) {
410         _, _, err := loadConfig("")
411         c.Assert(err.Error(), Equals, "config file not specified")
412 }
413
414 // Test loadConfig func - error reading config
415 func (s *ServerNotRequiredSuite) TestLoadConfig_ErrorLoadingSrcConfig(c *C) {
416         _, _, err := loadConfig("no-such-config-file")
417         c.Assert(strings.Contains(err.Error(), "no such file or directory"), Equals, true)
418 }
419
420 func (s *ServerNotRequiredSuite) TestSetupKeepClient_NoBlobSignatureTTL(c *C) {
421         var srcConfig apiConfig
422         srcConfig.APIHost = os.Getenv("ARVADOS_API_HOST")
423         srcConfig.APIToken = arvadostest.DataManagerToken
424         srcConfig.APIHostInsecure = matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
425         arvadostest.StartKeep(2, false)
426
427         _, ttl, err := setupKeepClient(srcConfig, srcKeepServicesJSON, false, 0, 0)
428         c.Check(err, IsNil)
429         c.Assert(ttl, Equals, blobSignatureTTL)
430 }
431
432 func setupConfigFile(c *C, name string) *os.File {
433         // Setup a config file
434         file, err := ioutil.TempFile(os.TempDir(), name)
435         c.Check(err, IsNil)
436
437         fileContent := "ARVADOS_API_HOST=" + os.Getenv("ARVADOS_API_HOST") + "\n"
438         fileContent += "ARVADOS_API_TOKEN=" + arvadostest.DataManagerToken + "\n"
439         fileContent += "ARVADOS_API_HOST_INSECURE=" + os.Getenv("ARVADOS_API_HOST_INSECURE") + "\n"
440         fileContent += "ARVADOS_EXTERNAL_CLIENT=false\n"
441         fileContent += "ARVADOS_BLOB_SIGNING_KEY=abcdefg"
442
443         _, err = file.Write([]byte(fileContent))
444         c.Check(err, IsNil)
445
446         return file
447 }
448
449 func (s *DoMainTestSuite) Test_doMain_NoSrcConfig(c *C) {
450         err := doMain()
451         c.Check(err, NotNil)
452         c.Assert(err.Error(), Equals, "Error loading src configuration from file: config file not specified")
453 }
454
455 func (s *DoMainTestSuite) Test_doMain_SrcButNoDstConfig(c *C) {
456         srcConfig := setupConfigFile(c, "src")
457         args := []string{"-replications", "3", "-src", srcConfig.Name()}
458         os.Args = append(os.Args, args...)
459         err := doMain()
460         c.Check(err, NotNil)
461         c.Assert(err.Error(), Equals, "Error loading dst configuration from file: config file not specified")
462 }
463
464 func (s *DoMainTestSuite) Test_doMain_BadSrcConfig(c *C) {
465         args := []string{"-src", "abcd"}
466         os.Args = append(os.Args, args...)
467         err := doMain()
468         c.Check(err, NotNil)
469         c.Assert(strings.HasPrefix(err.Error(), "Error loading src configuration from file: Error reading config file"), Equals, true)
470 }
471
472 func (s *DoMainTestSuite) Test_doMain_WithReplicationsButNoSrcConfig(c *C) {
473         args := []string{"-replications", "3"}
474         os.Args = append(os.Args, args...)
475         err := doMain()
476         c.Check(err, NotNil)
477         c.Assert(err.Error(), Equals, "Error loading src configuration from file: config file not specified")
478 }
479
480 func (s *DoMainTestSuite) Test_doMainWithSrcAndDstConfig(c *C) {
481         srcConfig := setupConfigFile(c, "src")
482         dstConfig := setupConfigFile(c, "dst")
483         args := []string{"-src", srcConfig.Name(), "-dst", dstConfig.Name()}
484         os.Args = append(os.Args, args...)
485
486         // Start keepservers. Since we are not doing any tweaking as
487         // in setupRsync func, kcSrc and kcDst will be the same and no
488         // actual copying to dst will happen, but that's ok.
489         arvadostest.StartKeep(2, false)
490         defer arvadostest.StopKeep(2)
491
492         err := doMain()
493         c.Check(err, IsNil)
494 }