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