1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.curoverse.com/arvados.git/sdk/go/arvados"
19 "github.com/Sirupsen/logrus"
20 check "gopkg.in/check.v1"
23 var _ = check.Suite(&runSuite{})
25 type reqTracker struct {
30 func (rt *reqTracker) Count() int {
36 func (rt *reqTracker) Add(req *http.Request) int {
39 rt.reqs = append(rt.reqs, *req)
43 var stubServices = []arvados.KeepService{
45 UUID: "zzzzz-bi6l4-000000000000000",
46 ServiceHost: "keep0.zzzzz.arvadosapi.com",
48 ServiceSSLFlag: false,
52 UUID: "zzzzz-bi6l4-000000000000001",
53 ServiceHost: "keep1.zzzzz.arvadosapi.com",
55 ServiceSSLFlag: false,
59 UUID: "zzzzz-bi6l4-000000000000002",
60 ServiceHost: "keep2.zzzzz.arvadosapi.com",
62 ServiceSSLFlag: false,
66 UUID: "zzzzz-bi6l4-000000000000003",
67 ServiceHost: "keep3.zzzzz.arvadosapi.com",
69 ServiceSSLFlag: false,
73 UUID: "zzzzz-bi6l4-h0a0xwut9qa6g3a",
74 ServiceHost: "keep.zzzzz.arvadosapi.com",
81 var stubMounts = map[string][]arvados.KeepMount{
82 "keep0.zzzzz.arvadosapi.com:25107": {{
83 UUID: "zzzzz-ivpuk-000000000000000",
84 DeviceID: "keep0-vol0",
86 "keep1.zzzzz.arvadosapi.com:25107": {{
87 UUID: "zzzzz-ivpuk-100000000000000",
88 DeviceID: "keep1-vol0",
90 "keep2.zzzzz.arvadosapi.com:25107": {{
91 UUID: "zzzzz-ivpuk-200000000000000",
92 DeviceID: "keep2-vol0",
94 "keep3.zzzzz.arvadosapi.com:25107": {{
95 UUID: "zzzzz-ivpuk-300000000000000",
96 DeviceID: "keep3-vol0",
100 // stubServer is an HTTP transport that intercepts and processes all
101 // requests using its own handlers.
102 type stubServer struct {
107 logf func(string, ...interface{})
110 // Start initializes the stub server and returns an *http.Client that
111 // uses the stub server to handle all requests.
113 // A stubServer that has been started should eventually be shut down
115 func (s *stubServer) Start() *http.Client {
116 // Set up a config.Client that forwards all requests to s.mux
117 // via s.srv. Test cases will attach handlers to s.mux to get
118 // the desired responses.
119 s.mux = http.NewServeMux()
120 s.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
124 w.Header().Set("Content-Type", "application/json")
125 s.mux.ServeHTTP(w, r)
127 return &http.Client{Transport: s}
130 func (s *stubServer) RoundTrip(req *http.Request) (*http.Response, error) {
131 w := httptest.NewRecorder()
132 s.mux.ServeHTTP(w, req)
133 return &http.Response{
135 Status: fmt.Sprintf("%d %s", w.Code, http.StatusText(w.Code)),
137 Body: ioutil.NopCloser(w.Body)}, nil
140 // Close releases resources used by the server.
141 func (s *stubServer) Close() {
145 func (s *stubServer) serveStatic(path, data string) *reqTracker {
147 s.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
150 ioutil.ReadAll(r.Body)
153 io.WriteString(w, data)
158 func (s *stubServer) serveCurrentUserAdmin() *reqTracker {
159 return s.serveStatic("/arvados/v1/users/current",
160 `{"uuid":"zzzzz-tpzed-000000000000000","is_admin":true,"is_active":true}`)
163 func (s *stubServer) serveCurrentUserNotAdmin() *reqTracker {
164 return s.serveStatic("/arvados/v1/users/current",
165 `{"uuid":"zzzzz-tpzed-000000000000000","is_admin":false,"is_active":true}`)
168 func (s *stubServer) serveDiscoveryDoc() *reqTracker {
169 return s.serveStatic("/discovery/v1/apis/arvados/v1/rest",
170 `{"defaultCollectionReplication":2}`)
173 func (s *stubServer) serveZeroCollections() *reqTracker {
174 return s.serveStatic("/arvados/v1/collections",
175 `{"items":[],"items_available":0}`)
178 func (s *stubServer) serveFooBarFileCollections() *reqTracker {
180 s.mux.HandleFunc("/arvados/v1/collections", func(w http.ResponseWriter, r *http.Request) {
183 if strings.Contains(r.Form.Get("filters"), `modified_at`) {
184 io.WriteString(w, `{"items_available":0,"items":[]}`)
186 io.WriteString(w, `{"items_available":3,"items":[
187 {"uuid":"zzzzz-4zz18-aaaaaaaaaaaaaaa","portable_data_hash":"fa7aeb5140e2848d39b416daeef4ffc5+45","manifest_text":". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n","modified_at":"2014-02-03T17:22:54Z"},
188 {"uuid":"zzzzz-4zz18-ehbhgtheo8909or","portable_data_hash":"fa7aeb5140e2848d39b416daeef4ffc5+45","manifest_text":". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n","modified_at":"2014-02-03T17:22:54Z"},
189 {"uuid":"zzzzz-4zz18-znfnqtbbv4spc3w","portable_data_hash":"1f4b0bc7583c2a7f9102c395f4ffc5e3+45","manifest_text":". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n","modified_at":"2014-02-03T17:22:54Z"}]}`)
195 func (s *stubServer) serveCollectionsButSkipOne() *reqTracker {
197 s.mux.HandleFunc("/arvados/v1/collections", func(w http.ResponseWriter, r *http.Request) {
200 if strings.Contains(r.Form.Get("filters"), `"modified_at","\u003c="`) {
201 io.WriteString(w, `{"items_available":3,"items":[]}`)
202 } else if strings.Contains(r.Form.Get("filters"), `"modified_at","\u003e`) {
203 io.WriteString(w, `{"items_available":0,"items":[]}`)
204 } else if strings.Contains(r.Form.Get("filters"), `"modified_at","="`) && strings.Contains(r.Form.Get("filters"), `"uuid","\u003e"`) {
205 io.WriteString(w, `{"items_available":0,"items":[]}`)
207 io.WriteString(w, `{"items_available":2,"items":[
208 {"uuid":"zzzzz-4zz18-ehbhgtheo8909or","portable_data_hash":"fa7aeb5140e2848d39b416daeef4ffc5+45","manifest_text":". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n","modified_at":"2014-02-03T17:22:54Z"},
209 {"uuid":"zzzzz-4zz18-znfnqtbbv4spc3w","portable_data_hash":"1f4b0bc7583c2a7f9102c395f4ffc5e3+45","manifest_text":". acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo\n","modified_at":"2014-02-03T17:22:54Z"}]}`)
215 func (s *stubServer) serveZeroKeepServices() *reqTracker {
216 return s.serveJSON("/arvados/v1/keep_services", arvados.KeepServiceList{})
219 func (s *stubServer) serveKeepServices(svcs []arvados.KeepService) *reqTracker {
220 return s.serveJSON("/arvados/v1/keep_services", arvados.KeepServiceList{
221 ItemsAvailable: len(svcs),
226 func (s *stubServer) serveJSON(path string, resp interface{}) *reqTracker {
228 s.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
230 json.NewEncoder(w).Encode(resp)
235 func (s *stubServer) serveKeepstoreMounts() *reqTracker {
237 s.mux.HandleFunc("/mounts", func(w http.ResponseWriter, r *http.Request) {
239 json.NewEncoder(w).Encode(stubMounts[r.Host])
244 func (s *stubServer) serveKeepstoreIndexFoo4Bar1() *reqTracker {
246 s.mux.HandleFunc("/index/", func(w http.ResponseWriter, r *http.Request) {
248 if r.Host == "keep0.zzzzz.arvadosapi.com:25107" {
249 io.WriteString(w, "37b51d194a7513e45b56f6524f2d51f2+3 12345678\n")
251 fmt.Fprintf(w, "acbd18db4cc2f85cedef654fccc4a4d8+3 %d\n\n", 12345678+count)
253 for _, mounts := range stubMounts {
254 for i, mnt := range mounts {
256 s.mux.HandleFunc(fmt.Sprintf("/mounts/%s/blocks", mnt.UUID), func(w http.ResponseWriter, r *http.Request) {
258 if i == 0 && r.Host == "keep0.zzzzz.arvadosapi.com:25107" {
259 io.WriteString(w, "37b51d194a7513e45b56f6524f2d51f2+3 12345678\n")
262 fmt.Fprintf(w, "acbd18db4cc2f85cedef654fccc4a4d8+3 %d\n", 12345678+count)
271 func (s *stubServer) serveKeepstoreTrash() *reqTracker {
272 return s.serveStatic("/trash", `{}`)
275 func (s *stubServer) serveKeepstorePull() *reqTracker {
276 return s.serveStatic("/pull", `{}`)
279 type runSuite struct {
284 // make a log.Logger that writes to the current test's c.Log().
285 func (s *runSuite) logger(c *check.C) *logrus.Logger {
288 buf := make([]byte, 10000)
290 n, err := r.Read(buf)
292 if buf[n-1] == '\n' {
295 c.Log(string(buf[:n]))
302 logger := logrus.New()
307 func (s *runSuite) SetUpTest(c *check.C) {
309 Client: arvados.Client{
311 APIHost: "zzzzz.arvadosapi.com",
312 Client: s.stub.Start()},
313 KeepServiceTypes: []string{"disk"},
314 RunPeriod: arvados.Duration(time.Second),
316 s.stub.serveDiscoveryDoc()
320 func (s *runSuite) TearDownTest(c *check.C) {
324 func (s *runSuite) TestRefuseZeroCollections(c *check.C) {
330 s.stub.serveCurrentUserAdmin()
331 s.stub.serveZeroCollections()
332 s.stub.serveKeepServices(stubServices)
333 s.stub.serveKeepstoreMounts()
334 s.stub.serveKeepstoreIndexFoo4Bar1()
335 trashReqs := s.stub.serveKeepstoreTrash()
336 pullReqs := s.stub.serveKeepstorePull()
337 srv, err := NewServer(s.config, opts)
338 c.Assert(err, check.IsNil)
340 c.Check(err, check.ErrorMatches, "received zero collections")
341 c.Check(trashReqs.Count(), check.Equals, 4)
342 c.Check(pullReqs.Count(), check.Equals, 0)
345 func (s *runSuite) TestServiceTypes(c *check.C) {
351 s.config.KeepServiceTypes = []string{"unlisted-type"}
352 s.stub.serveCurrentUserAdmin()
353 s.stub.serveFooBarFileCollections()
354 s.stub.serveKeepServices(stubServices)
355 s.stub.serveKeepstoreMounts()
356 indexReqs := s.stub.serveKeepstoreIndexFoo4Bar1()
357 trashReqs := s.stub.serveKeepstoreTrash()
358 srv, err := NewServer(s.config, opts)
359 c.Assert(err, check.IsNil)
361 c.Check(err, check.IsNil)
362 c.Check(indexReqs.Count(), check.Equals, 0)
363 c.Check(trashReqs.Count(), check.Equals, 0)
366 func (s *runSuite) TestRefuseNonAdmin(c *check.C) {
372 s.stub.serveCurrentUserNotAdmin()
373 s.stub.serveZeroCollections()
374 s.stub.serveKeepServices(stubServices)
375 s.stub.serveKeepstoreMounts()
376 trashReqs := s.stub.serveKeepstoreTrash()
377 pullReqs := s.stub.serveKeepstorePull()
378 srv, err := NewServer(s.config, opts)
379 c.Assert(err, check.IsNil)
381 c.Check(err, check.ErrorMatches, "current user .* is not .* admin user")
382 c.Check(trashReqs.Count(), check.Equals, 0)
383 c.Check(pullReqs.Count(), check.Equals, 0)
386 func (s *runSuite) TestDetectSkippedCollections(c *check.C) {
392 s.stub.serveCurrentUserAdmin()
393 s.stub.serveCollectionsButSkipOne()
394 s.stub.serveKeepServices(stubServices)
395 s.stub.serveKeepstoreMounts()
396 s.stub.serveKeepstoreIndexFoo4Bar1()
397 trashReqs := s.stub.serveKeepstoreTrash()
398 pullReqs := s.stub.serveKeepstorePull()
399 srv, err := NewServer(s.config, opts)
400 c.Assert(err, check.IsNil)
402 c.Check(err, check.ErrorMatches, `Retrieved 2 collections with modtime <= .* but server now reports there are 3 collections.*`)
403 c.Check(trashReqs.Count(), check.Equals, 4)
404 c.Check(pullReqs.Count(), check.Equals, 0)
407 func (s *runSuite) TestDryRun(c *check.C) {
413 s.stub.serveCurrentUserAdmin()
414 collReqs := s.stub.serveFooBarFileCollections()
415 s.stub.serveKeepServices(stubServices)
416 s.stub.serveKeepstoreMounts()
417 s.stub.serveKeepstoreIndexFoo4Bar1()
418 trashReqs := s.stub.serveKeepstoreTrash()
419 pullReqs := s.stub.serveKeepstorePull()
420 srv, err := NewServer(s.config, opts)
421 c.Assert(err, check.IsNil)
422 bal, err := srv.Run()
423 c.Check(err, check.IsNil)
424 for _, req := range collReqs.reqs {
425 c.Check(req.Form.Get("include_trash"), check.Equals, "true")
426 c.Check(req.Form.Get("include_old_versions"), check.Equals, "true")
428 c.Check(trashReqs.Count(), check.Equals, 0)
429 c.Check(pullReqs.Count(), check.Equals, 0)
430 c.Check(bal.stats.pulls, check.Not(check.Equals), 0)
431 c.Check(bal.stats.underrep.replicas, check.Not(check.Equals), 0)
432 c.Check(bal.stats.overrep.replicas, check.Not(check.Equals), 0)
435 func (s *runSuite) TestCommit(c *check.C) {
436 s.config.Listen = ":"
437 s.config.ManagementToken = "xyzzy"
444 s.stub.serveCurrentUserAdmin()
445 s.stub.serveFooBarFileCollections()
446 s.stub.serveKeepServices(stubServices)
447 s.stub.serveKeepstoreMounts()
448 s.stub.serveKeepstoreIndexFoo4Bar1()
449 trashReqs := s.stub.serveKeepstoreTrash()
450 pullReqs := s.stub.serveKeepstorePull()
451 srv, err := NewServer(s.config, opts)
452 c.Assert(err, check.IsNil)
453 bal, err := srv.Run()
454 c.Check(err, check.IsNil)
455 c.Check(trashReqs.Count(), check.Equals, 8)
456 c.Check(pullReqs.Count(), check.Equals, 4)
457 // "foo" block is overreplicated by 2
458 c.Check(bal.stats.trashes, check.Equals, 2)
459 // "bar" block is underreplicated by 1, and its only copy is
460 // in a poor rendezvous position
461 c.Check(bal.stats.pulls, check.Equals, 2)
463 metrics := s.getMetrics(c, srv)
464 c.Check(metrics, check.Matches, `(?ms).*\narvados_keep_total_bytes 15\n.*`)
465 c.Check(metrics, check.Matches, `(?ms).*\narvados_keepbalance_changeset_compute_seconds_sum [0-9\.]+\n.*`)
466 c.Check(metrics, check.Matches, `(?ms).*\narvados_keepbalance_changeset_compute_seconds_count 1\n.*`)
467 c.Check(metrics, check.Matches, `(?ms).*\narvados_keep_dedup_byte_ratio 1\.5\n.*`)
468 c.Check(metrics, check.Matches, `(?ms).*\narvados_keep_dedup_block_ratio 1\.5\n.*`)
471 func (s *runSuite) TestRunForever(c *check.C) {
472 s.config.Listen = ":"
473 s.config.ManagementToken = "xyzzy"
480 s.stub.serveCurrentUserAdmin()
481 s.stub.serveFooBarFileCollections()
482 s.stub.serveKeepServices(stubServices)
483 s.stub.serveKeepstoreMounts()
484 s.stub.serveKeepstoreIndexFoo4Bar1()
485 trashReqs := s.stub.serveKeepstoreTrash()
486 pullReqs := s.stub.serveKeepstorePull()
488 stop := make(chan interface{})
489 s.config.RunPeriod = arvados.Duration(time.Millisecond)
490 srv, err := NewServer(s.config, opts)
491 c.Assert(err, check.IsNil)
493 done := make(chan bool)
499 // Each run should send 4 pull lists + 4 trash lists. The
500 // first run should also send 4 empty trash lists at
501 // startup. We should complete all four runs in much less than
503 for t0 := time.Now(); pullReqs.Count() < 16 && time.Since(t0) < 10*time.Second; {
504 time.Sleep(time.Millisecond)
508 c.Check(pullReqs.Count() >= 16, check.Equals, true)
509 c.Check(trashReqs.Count(), check.Equals, pullReqs.Count()+4)
510 c.Check(s.getMetrics(c, srv), check.Matches, `(?ms).*\narvados_keepbalance_changeset_compute_seconds_count `+fmt.Sprintf("%d", pullReqs.Count()/4)+`\n.*`)
513 func (s *runSuite) getMetrics(c *check.C, srv *Server) string {
514 resp, err := http.Get("http://" + srv.listening + "/metrics")
515 c.Assert(err, check.IsNil)
516 c.Check(resp.StatusCode, check.Equals, http.StatusUnauthorized)
518 resp, err = http.Get("http://" + srv.listening + "/metrics?api_token=xyzzy")
519 c.Assert(err, check.IsNil)
520 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
521 buf, err := ioutil.ReadAll(resp.Body)
522 c.Check(err, check.IsNil)