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