Merge branch '11345-nodemanager-retry-after' refs #11345
[arvados.git] / tools / keep-block-check / keep-block-check_test.go
1 package main
2
3 import (
4         "bytes"
5         "fmt"
6         "io"
7         "io/ioutil"
8         "log"
9         "os"
10         "regexp"
11         "strings"
12         "testing"
13         "time"
14
15         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
16         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
17         "git.curoverse.com/arvados.git/sdk/go/keepclient"
18
19         . "gopkg.in/check.v1"
20 )
21
22 // Gocheck boilerplate
23 func Test(t *testing.T) {
24         TestingT(t)
25 }
26
27 // Gocheck boilerplate
28 var _ = Suite(&ServerRequiredSuite{})
29 var _ = Suite(&DoMainTestSuite{})
30
31 type ServerRequiredSuite struct{}
32 type DoMainTestSuite struct{}
33
34 var kc *keepclient.KeepClient
35 var logBuffer bytes.Buffer
36
37 var TestHash = "aaaa09c290d0fb1ca068ffaddf22cbd0"
38 var TestHash2 = "aaaac516f788aec4f30932ffb6395c39"
39
40 var blobSignatureTTL = time.Duration(2*7*24) * time.Hour
41
42 func (s *ServerRequiredSuite) SetUpSuite(c *C) {
43         arvadostest.StartAPI()
44 }
45
46 func (s *ServerRequiredSuite) TearDownSuite(c *C) {
47         arvadostest.StopAPI()
48         arvadostest.ResetEnv()
49 }
50
51 func (s *ServerRequiredSuite) SetUpTest(c *C) {
52         logOutput := io.MultiWriter(&logBuffer)
53         log.SetOutput(logOutput)
54 }
55
56 func (s *ServerRequiredSuite) TearDownTest(c *C) {
57         arvadostest.StopKeep(2)
58         log.SetOutput(os.Stdout)
59         log.Printf("%v", logBuffer.String())
60 }
61
62 func (s *DoMainTestSuite) SetUpSuite(c *C) {
63 }
64
65 func (s *DoMainTestSuite) SetUpTest(c *C) {
66         logOutput := io.MultiWriter(&logBuffer)
67         log.SetOutput(logOutput)
68         keepclient.RefreshServiceDiscovery()
69 }
70
71 func (s *DoMainTestSuite) TearDownTest(c *C) {
72         log.SetOutput(os.Stdout)
73         log.Printf("%v", logBuffer.String())
74 }
75
76 func setupKeepBlockCheck(c *C, enforcePermissions bool, keepServicesJSON string) {
77         setupKeepBlockCheckWithTTL(c, enforcePermissions, keepServicesJSON, blobSignatureTTL)
78 }
79
80 func setupKeepBlockCheckWithTTL(c *C, enforcePermissions bool, keepServicesJSON string, ttl time.Duration) {
81         var config apiConfig
82         config.APIHost = os.Getenv("ARVADOS_API_HOST")
83         config.APIToken = arvadostest.DataManagerToken
84         config.APIHostInsecure = arvadosclient.StringBool(os.Getenv("ARVADOS_API_HOST_INSECURE"))
85
86         // Start Keep servers
87         arvadostest.StartKeep(2, enforcePermissions)
88
89         // setup keepclients
90         var err error
91         kc, ttl, err = setupKeepClient(config, keepServicesJSON, ttl)
92         c.Assert(ttl, Equals, blobSignatureTTL)
93         c.Check(err, IsNil)
94
95         keepclient.RefreshServiceDiscovery()
96 }
97
98 // Setup test data
99 func setupTestData(c *C) []string {
100         allLocators := []string{}
101
102         // Put a few blocks
103         for i := 0; i < 5; i++ {
104                 hash, _, err := kc.PutB([]byte(fmt.Sprintf("keep-block-check-test-data-%d", i)))
105                 c.Check(err, IsNil)
106                 allLocators = append(allLocators, strings.Split(hash, "+A")[0])
107         }
108
109         return allLocators
110 }
111
112 func setupConfigFile(c *C, fileName string) string {
113         // Setup a config file
114         file, err := ioutil.TempFile(os.TempDir(), fileName)
115         c.Check(err, IsNil)
116
117         // Add config to file. While at it, throw some extra white space
118         fileContent := "ARVADOS_API_HOST=" + os.Getenv("ARVADOS_API_HOST") + "\n"
119         fileContent += "ARVADOS_API_TOKEN=" + arvadostest.DataManagerToken + "\n"
120         fileContent += "\n"
121         fileContent += "ARVADOS_API_HOST_INSECURE=" + os.Getenv("ARVADOS_API_HOST_INSECURE") + "\n"
122         fileContent += " ARVADOS_EXTERNAL_CLIENT = false \n"
123         fileContent += " NotANameValuePairAndShouldGetIgnored \n"
124         fileContent += "ARVADOS_BLOB_SIGNING_KEY=abcdefg\n"
125
126         _, err = file.Write([]byte(fileContent))
127         c.Check(err, IsNil)
128
129         return file.Name()
130 }
131
132 func setupBlockHashFile(c *C, name string, blocks []string) string {
133         // Setup a block hash file
134         file, err := ioutil.TempFile(os.TempDir(), name)
135         c.Check(err, IsNil)
136
137         // Add the hashes to the file. While at it, throw some extra white space
138         fileContent := ""
139         for _, hash := range blocks {
140                 fileContent += fmt.Sprintf(" %s \n", hash)
141         }
142         fileContent += "\n"
143         _, err = file.Write([]byte(fileContent))
144         c.Check(err, IsNil)
145
146         return file.Name()
147 }
148
149 func checkErrorLog(c *C, blocks []string, prefix, suffix string) {
150         for _, hash := range blocks {
151                 expected := `(?ms).*` + prefix + `.*` + hash + `.*` + suffix + `.*`
152                 c.Check(logBuffer.String(), Matches, expected)
153         }
154 }
155
156 func checkNoErrorsLogged(c *C, prefix, suffix string) {
157         expected := prefix + `.*` + suffix
158         match, _ := regexp.MatchString(expected, logBuffer.String())
159         c.Assert(match, Equals, false)
160 }
161
162 func (s *ServerRequiredSuite) TestBlockCheck(c *C) {
163         setupKeepBlockCheck(c, false, "")
164         allLocators := setupTestData(c)
165         err := performKeepBlockCheck(kc, blobSignatureTTL, "", allLocators, true)
166         c.Check(err, IsNil)
167         checkNoErrorsLogged(c, "Error verifying block", "Block not found")
168 }
169
170 func (s *ServerRequiredSuite) TestBlockCheckWithBlobSigning(c *C) {
171         setupKeepBlockCheck(c, true, "")
172         allLocators := setupTestData(c)
173         err := performKeepBlockCheck(kc, blobSignatureTTL, arvadostest.BlobSigningKey, allLocators, true)
174         c.Check(err, IsNil)
175         checkNoErrorsLogged(c, "Error verifying block", "Block not found")
176 }
177
178 func (s *ServerRequiredSuite) TestBlockCheckWithBlobSigningAndTTLFromDiscovery(c *C) {
179         setupKeepBlockCheckWithTTL(c, true, "", 0)
180         allLocators := setupTestData(c)
181         err := performKeepBlockCheck(kc, blobSignatureTTL, arvadostest.BlobSigningKey, allLocators, true)
182         c.Check(err, IsNil)
183         checkNoErrorsLogged(c, "Error verifying block", "Block not found")
184 }
185
186 func (s *ServerRequiredSuite) TestBlockCheck_NoSuchBlock(c *C) {
187         setupKeepBlockCheck(c, false, "")
188         allLocators := setupTestData(c)
189         allLocators = append(allLocators, TestHash)
190         allLocators = append(allLocators, TestHash2)
191         err := performKeepBlockCheck(kc, blobSignatureTTL, "", allLocators, true)
192         c.Check(err, NotNil)
193         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 7 blocks with matching prefix.")
194         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "Block not found")
195 }
196
197 func (s *ServerRequiredSuite) TestBlockCheck_NoSuchBlock_WithMatchingPrefix(c *C) {
198         setupKeepBlockCheck(c, false, "")
199         allLocators := setupTestData(c)
200         allLocators = append(allLocators, TestHash)
201         allLocators = append(allLocators, TestHash2)
202         locatorFile := setupBlockHashFile(c, "block-hash", allLocators)
203         defer os.Remove(locatorFile)
204         locators, err := getBlockLocators(locatorFile, "aaa")
205         c.Check(err, IsNil)
206         err = performKeepBlockCheck(kc, blobSignatureTTL, "", locators, true)
207         c.Check(err, NotNil)
208         // Of the 7 blocks in allLocators, only two match the prefix and hence only those are checked
209         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 2 blocks with matching prefix.")
210         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "Block not found")
211 }
212
213 func (s *ServerRequiredSuite) TestBlockCheck_NoSuchBlock_WithPrefixMismatch(c *C) {
214         setupKeepBlockCheck(c, false, "")
215         allLocators := setupTestData(c)
216         allLocators = append(allLocators, TestHash)
217         allLocators = append(allLocators, TestHash2)
218         locatorFile := setupBlockHashFile(c, "block-hash", allLocators)
219         defer os.Remove(locatorFile)
220         locators, err := getBlockLocators(locatorFile, "999")
221         c.Check(err, IsNil)
222         err = performKeepBlockCheck(kc, blobSignatureTTL, "", locators, true)
223         c.Check(err, IsNil) // there were no matching locators in file and hence nothing was checked
224 }
225
226 func (s *ServerRequiredSuite) TestBlockCheck_BadSignature(c *C) {
227         setupKeepBlockCheck(c, true, "")
228         setupTestData(c)
229         err := performKeepBlockCheck(kc, blobSignatureTTL, "badblobsigningkey", []string{TestHash, TestHash2}, false)
230         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 2 blocks with matching prefix.")
231         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "HTTP 403")
232         // verbose logging not requested
233         c.Assert(strings.Contains(logBuffer.String(), "Verifying block 1 of 2"), Equals, false)
234 }
235
236 var testKeepServicesJSON = `{
237   "kind":"arvados#keepServiceList",
238   "etag":"",
239   "self_link":"",
240   "offset":null, "limit":null,
241   "items":[
242     {"href":"/keep_services/zzzzz-bi6l4-123456789012340",
243      "kind":"arvados#keepService",
244      "uuid":"zzzzz-bi6l4-123456789012340",
245      "service_host":"keep0.zzzzz.arvadosapi.com",
246      "service_port":25107,
247      "service_ssl_flag":false,
248      "service_type":"disk",
249      "read_only":false },
250     {"href":"/keep_services/zzzzz-bi6l4-123456789012341",
251      "kind":"arvados#keepService",
252      "uuid":"zzzzz-bi6l4-123456789012341",
253      "service_host":"keep0.zzzzz.arvadosapi.com",
254      "service_port":25108,
255      "service_ssl_flag":false,
256      "service_type":"disk",
257      "read_only":false }
258     ],
259   "items_available":2 }`
260
261 // Setup block-check using keepServicesJSON with fake keepservers.
262 // Expect error during performKeepBlockCheck due to unreachable keepservers.
263 func (s *ServerRequiredSuite) TestErrorDuringKeepBlockCheck_FakeKeepservers(c *C) {
264         setupKeepBlockCheck(c, false, testKeepServicesJSON)
265         err := performKeepBlockCheck(kc, blobSignatureTTL, "", []string{TestHash, TestHash2}, true)
266         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 2 blocks with matching prefix.")
267         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "")
268 }
269
270 // Test keep-block-check initialization with keepServicesJSON
271 func (s *ServerRequiredSuite) TestKeepBlockCheck_InitializeWithKeepServicesJSON(c *C) {
272         setupKeepBlockCheck(c, false, testKeepServicesJSON)
273         found := 0
274         for k := range kc.LocalRoots() {
275                 if k == "zzzzz-bi6l4-123456789012340" || k == "zzzzz-bi6l4-123456789012341" {
276                         found++
277                 }
278         }
279         c.Check(found, Equals, 2)
280 }
281
282 // Test loadConfig func
283 func (s *ServerRequiredSuite) TestLoadConfig(c *C) {
284         // Setup config file
285         configFile := setupConfigFile(c, "config")
286         defer os.Remove(configFile)
287
288         // load configuration from the file
289         config, blobSigningKey, err := loadConfig(configFile)
290         c.Check(err, IsNil)
291
292         c.Assert(config.APIHost, Equals, os.Getenv("ARVADOS_API_HOST"))
293         c.Assert(config.APIToken, Equals, arvadostest.DataManagerToken)
294         c.Assert(config.APIHostInsecure, Equals, arvadosclient.StringBool(os.Getenv("ARVADOS_API_HOST_INSECURE")))
295         c.Assert(config.ExternalClient, Equals, false)
296         c.Assert(blobSigningKey, Equals, "abcdefg")
297 }
298
299 func (s *DoMainTestSuite) Test_doMain_WithNoConfig(c *C) {
300         args := []string{"-prefix", "a"}
301         err := doMain(args)
302         c.Check(err, NotNil)
303         c.Assert(strings.Contains(err.Error(), "config file not specified"), Equals, true)
304 }
305
306 func (s *DoMainTestSuite) Test_doMain_WithNoSuchConfigFile(c *C) {
307         args := []string{"-config", "no-such-file"}
308         err := doMain(args)
309         c.Check(err, NotNil)
310         c.Assert(strings.Contains(err.Error(), "no such file or directory"), Equals, true)
311 }
312
313 func (s *DoMainTestSuite) Test_doMain_WithNoBlockHashFile(c *C) {
314         config := setupConfigFile(c, "config")
315         defer os.Remove(config)
316
317         // Start keepservers.
318         arvadostest.StartKeep(2, false)
319         defer arvadostest.StopKeep(2)
320
321         args := []string{"-config", config}
322         err := doMain(args)
323         c.Assert(strings.Contains(err.Error(), "block-hash-file not specified"), Equals, true)
324 }
325
326 func (s *DoMainTestSuite) Test_doMain_WithNoSuchBlockHashFile(c *C) {
327         config := setupConfigFile(c, "config")
328         defer os.Remove(config)
329
330         arvadostest.StartKeep(2, false)
331         defer arvadostest.StopKeep(2)
332
333         args := []string{"-config", config, "-block-hash-file", "no-such-file"}
334         err := doMain(args)
335         c.Assert(strings.Contains(err.Error(), "no such file or directory"), Equals, true)
336 }
337
338 func (s *DoMainTestSuite) Test_doMain(c *C) {
339         // Start keepservers.
340         arvadostest.StartKeep(2, false)
341         defer arvadostest.StopKeep(2)
342
343         config := setupConfigFile(c, "config")
344         defer os.Remove(config)
345
346         locatorFile := setupBlockHashFile(c, "block-hash", []string{TestHash, TestHash2})
347         defer os.Remove(locatorFile)
348
349         args := []string{"-config", config, "-block-hash-file", locatorFile, "-v"}
350         err := doMain(args)
351         c.Check(err, NotNil)
352         c.Assert(err.Error(), Equals, "Block verification failed for 2 out of 2 blocks with matching prefix.")
353         checkErrorLog(c, []string{TestHash, TestHash2}, "Error verifying block", "Block not found")
354         c.Assert(strings.Contains(logBuffer.String(), "Verifying block 1 of 2"), Equals, true)
355 }