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