1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.curoverse.com/arvados.git/sdk/go/arvados"
21 check "gopkg.in/check.v1"
24 var _ = check.Suite(&runSuite{})
26 type reqTracker struct {
31 func (rt *reqTracker) Count() int {
37 func (rt *reqTracker) Add(req *http.Request) int {
40 rt.reqs = append(rt.reqs, *req)
44 var stubServices = []arvados.KeepService{
46 UUID: "zzzzz-bi6l4-000000000000000",
47 ServiceHost: "keep0.zzzzz.arvadosapi.com",
49 ServiceSSLFlag: false,
53 UUID: "zzzzz-bi6l4-000000000000001",
54 ServiceHost: "keep1.zzzzz.arvadosapi.com",
56 ServiceSSLFlag: false,
60 UUID: "zzzzz-bi6l4-000000000000002",
61 ServiceHost: "keep2.zzzzz.arvadosapi.com",
63 ServiceSSLFlag: false,
67 UUID: "zzzzz-bi6l4-000000000000003",
68 ServiceHost: "keep3.zzzzz.arvadosapi.com",
70 ServiceSSLFlag: false,
74 UUID: "zzzzz-bi6l4-h0a0xwut9qa6g3a",
75 ServiceHost: "keep.zzzzz.arvadosapi.com",
82 var stubMounts = map[string][]arvados.KeepMount{
83 "keep0.zzzzz.arvadosapi.com:25107": {{
84 UUID: "zzzzz-ivpuk-000000000000000",
85 DeviceID: "keep0-vol0",
87 "keep1.zzzzz.arvadosapi.com:25107": {{
88 UUID: "zzzzz-ivpuk-100000000000000",
89 DeviceID: "keep1-vol0",
91 "keep2.zzzzz.arvadosapi.com:25107": {{
92 UUID: "zzzzz-ivpuk-200000000000000",
93 DeviceID: "keep2-vol0",
95 "keep3.zzzzz.arvadosapi.com:25107": {{
96 UUID: "zzzzz-ivpuk-300000000000000",
97 DeviceID: "keep3-vol0",
101 // stubServer is an HTTP transport that intercepts and processes all
102 // requests using its own handlers.
103 type stubServer struct {
108 logf func(string, ...interface{})
111 // Start initializes the stub server and returns an *http.Client that
112 // uses the stub server to handle all requests.
114 // A stubServer that has been started should eventually be shut down
116 func (s *stubServer) Start() *http.Client {
117 // Set up a config.Client that forwards all requests to s.mux
118 // via s.srv. Test cases will attach handlers to s.mux to get
119 // the desired responses.
120 s.mux = http.NewServeMux()
121 s.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
125 w.Header().Set("Content-Type", "application/json")
126 s.mux.ServeHTTP(w, r)
128 return &http.Client{Transport: s}
131 func (s *stubServer) RoundTrip(req *http.Request) (*http.Response, error) {
132 w := httptest.NewRecorder()
133 s.mux.ServeHTTP(w, req)
134 return &http.Response{
136 Status: fmt.Sprintf("%d %s", w.Code, http.StatusText(w.Code)),
138 Body: ioutil.NopCloser(w.Body)}, nil
141 // Close releases resources used by the server.
142 func (s *stubServer) Close() {
146 func (s *stubServer) serveStatic(path, data string) *reqTracker {
148 s.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
151 ioutil.ReadAll(r.Body)
154 io.WriteString(w, data)
159 func (s *stubServer) serveCurrentUserAdmin() *reqTracker {
160 return s.serveStatic("/arvados/v1/users/current",
161 `{"uuid":"zzzzz-tpzed-000000000000000","is_admin":true,"is_active":true}`)
164 func (s *stubServer) serveCurrentUserNotAdmin() *reqTracker {
165 return s.serveStatic("/arvados/v1/users/current",
166 `{"uuid":"zzzzz-tpzed-000000000000000","is_admin":false,"is_active":true}`)
169 func (s *stubServer) serveDiscoveryDoc() *reqTracker {
170 return s.serveStatic("/discovery/v1/apis/arvados/v1/rest",
171 `{"defaultCollectionReplication":2}`)
174 func (s *stubServer) serveZeroCollections() *reqTracker {
175 return s.serveStatic("/arvados/v1/collections",
176 `{"items":[],"items_available":0}`)
179 func (s *stubServer) serveFooBarFileCollections() *reqTracker {
181 s.mux.HandleFunc("/arvados/v1/collections", func(w http.ResponseWriter, r *http.Request) {
184 if strings.Contains(r.Form.Get("filters"), `modified_at`) {
185 io.WriteString(w, `{"items_available":0,"items":[]}`)
187 io.WriteString(w, `{"items_available":2,"items":[
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) *log.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 return log.New(w, "", log.LstdFlags)
305 func (s *runSuite) SetUpTest(c *check.C) {
307 Client: arvados.Client{
309 APIHost: "zzzzz.arvadosapi.com",
310 Client: s.stub.Start()},
311 KeepServiceTypes: []string{"disk"}}
312 s.stub.serveDiscoveryDoc()
316 func (s *runSuite) TearDownTest(c *check.C) {
320 func (s *runSuite) TestRefuseZeroCollections(c *check.C) {
326 s.stub.serveCurrentUserAdmin()
327 s.stub.serveZeroCollections()
328 s.stub.serveKeepServices(stubServices)
329 s.stub.serveKeepstoreMounts()
330 s.stub.serveKeepstoreIndexFoo4Bar1()
331 trashReqs := s.stub.serveKeepstoreTrash()
332 pullReqs := s.stub.serveKeepstorePull()
333 _, err := (&Balancer{}).Run(s.config, opts)
334 c.Check(err, check.ErrorMatches, "received zero collections")
335 c.Check(trashReqs.Count(), check.Equals, 4)
336 c.Check(pullReqs.Count(), check.Equals, 0)
339 func (s *runSuite) TestServiceTypes(c *check.C) {
345 s.config.KeepServiceTypes = []string{"unlisted-type"}
346 s.stub.serveCurrentUserAdmin()
347 s.stub.serveFooBarFileCollections()
348 s.stub.serveKeepServices(stubServices)
349 s.stub.serveKeepstoreMounts()
350 indexReqs := s.stub.serveKeepstoreIndexFoo4Bar1()
351 trashReqs := s.stub.serveKeepstoreTrash()
352 _, err := (&Balancer{}).Run(s.config, opts)
353 c.Check(err, check.IsNil)
354 c.Check(indexReqs.Count(), check.Equals, 0)
355 c.Check(trashReqs.Count(), check.Equals, 0)
358 func (s *runSuite) TestRefuseNonAdmin(c *check.C) {
364 s.stub.serveCurrentUserNotAdmin()
365 s.stub.serveZeroCollections()
366 s.stub.serveKeepServices(stubServices)
367 s.stub.serveKeepstoreMounts()
368 trashReqs := s.stub.serveKeepstoreTrash()
369 pullReqs := s.stub.serveKeepstorePull()
370 _, err := (&Balancer{}).Run(s.config, opts)
371 c.Check(err, check.ErrorMatches, "current user .* is not .* admin user")
372 c.Check(trashReqs.Count(), check.Equals, 0)
373 c.Check(pullReqs.Count(), check.Equals, 0)
376 func (s *runSuite) TestDetectSkippedCollections(c *check.C) {
382 s.stub.serveCurrentUserAdmin()
383 s.stub.serveCollectionsButSkipOne()
384 s.stub.serveKeepServices(stubServices)
385 s.stub.serveKeepstoreMounts()
386 s.stub.serveKeepstoreIndexFoo4Bar1()
387 trashReqs := s.stub.serveKeepstoreTrash()
388 pullReqs := s.stub.serveKeepstorePull()
389 _, err := (&Balancer{}).Run(s.config, opts)
390 c.Check(err, check.ErrorMatches, `Retrieved 2 collections with modtime <= .* but server now reports there are 3 collections.*`)
391 c.Check(trashReqs.Count(), check.Equals, 4)
392 c.Check(pullReqs.Count(), check.Equals, 0)
395 func (s *runSuite) TestDryRun(c *check.C) {
401 s.stub.serveCurrentUserAdmin()
402 collReqs := s.stub.serveFooBarFileCollections()
403 s.stub.serveKeepServices(stubServices)
404 s.stub.serveKeepstoreMounts()
405 s.stub.serveKeepstoreIndexFoo4Bar1()
406 trashReqs := s.stub.serveKeepstoreTrash()
407 pullReqs := s.stub.serveKeepstorePull()
409 _, err := bal.Run(s.config, opts)
410 c.Check(err, check.IsNil)
411 for _, req := range collReqs.reqs {
412 c.Check(req.Form.Get("include_trash"), check.Equals, "true")
414 c.Check(trashReqs.Count(), check.Equals, 0)
415 c.Check(pullReqs.Count(), check.Equals, 0)
416 c.Check(bal.stats.pulls, check.Not(check.Equals), 0)
417 c.Check(bal.stats.underrep.replicas, check.Not(check.Equals), 0)
418 c.Check(bal.stats.overrep.replicas, check.Not(check.Equals), 0)
421 func (s *runSuite) TestCommit(c *check.C) {
428 s.stub.serveCurrentUserAdmin()
429 s.stub.serveFooBarFileCollections()
430 s.stub.serveKeepServices(stubServices)
431 s.stub.serveKeepstoreMounts()
432 s.stub.serveKeepstoreIndexFoo4Bar1()
433 trashReqs := s.stub.serveKeepstoreTrash()
434 pullReqs := s.stub.serveKeepstorePull()
436 _, err := bal.Run(s.config, opts)
437 c.Check(err, check.IsNil)
438 c.Check(trashReqs.Count(), check.Equals, 8)
439 c.Check(pullReqs.Count(), check.Equals, 4)
440 // "foo" block is overreplicated by 2
441 c.Check(bal.stats.trashes, check.Equals, 2)
442 // "bar" block is underreplicated by 1, and its only copy is
443 // in a poor rendezvous position
444 c.Check(bal.stats.pulls, check.Equals, 2)
447 func (s *runSuite) TestRunForever(c *check.C) {
454 s.stub.serveCurrentUserAdmin()
455 s.stub.serveFooBarFileCollections()
456 s.stub.serveKeepServices(stubServices)
457 s.stub.serveKeepstoreMounts()
458 s.stub.serveKeepstoreIndexFoo4Bar1()
459 trashReqs := s.stub.serveKeepstoreTrash()
460 pullReqs := s.stub.serveKeepstorePull()
462 stop := make(chan interface{})
463 s.config.RunPeriod = arvados.Duration(time.Millisecond)
464 go RunForever(s.config, opts, stop)
466 // Each run should send 4 pull lists + 4 trash lists. The
467 // first run should also send 4 empty trash lists at
468 // startup. We should complete all four runs in much less than
470 for t0 := time.Now(); pullReqs.Count() < 16 && time.Since(t0) < 10*time.Second; {
471 time.Sleep(time.Millisecond)
474 c.Check(pullReqs.Count() >= 16, check.Equals, true)
475 c.Check(trashReqs.Count(), check.Equals, pullReqs.Count()+4)