20637: Fix tests
[arvados.git] / lib / dispatchcloud / dispatcher_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package dispatchcloud
6
7 import (
8         "context"
9         "crypto/tls"
10         "encoding/json"
11         "io/ioutil"
12         "math/rand"
13         "net/http"
14         "net/http/httptest"
15         "net/url"
16         "os"
17         "sync"
18         "time"
19
20         "git.arvados.org/arvados.git/lib/config"
21         "git.arvados.org/arvados.git/lib/dispatchcloud/test"
22         "git.arvados.org/arvados.git/sdk/go/arvados"
23         "git.arvados.org/arvados.git/sdk/go/arvadostest"
24         "git.arvados.org/arvados.git/sdk/go/ctxlog"
25         "github.com/prometheus/client_golang/prometheus"
26         "golang.org/x/crypto/ssh"
27         check "gopkg.in/check.v1"
28 )
29
30 var _ = check.Suite(&DispatcherSuite{})
31
32 type DispatcherSuite struct {
33         ctx            context.Context
34         cancel         context.CancelFunc
35         cluster        *arvados.Cluster
36         stubDriver     *test.StubDriver
37         disp           *dispatcher
38         error503Server *httptest.Server
39 }
40
41 func (s *DispatcherSuite) SetUpTest(c *check.C) {
42         s.ctx, s.cancel = context.WithCancel(context.Background())
43         s.ctx = ctxlog.Context(s.ctx, ctxlog.TestLogger(c))
44         dispatchpub, _ := test.LoadTestKey(c, "test/sshkey_dispatch")
45         dispatchprivraw, err := ioutil.ReadFile("test/sshkey_dispatch")
46         c.Assert(err, check.IsNil)
47
48         _, hostpriv := test.LoadTestKey(c, "test/sshkey_vm")
49         s.stubDriver = &test.StubDriver{
50                 HostKey:                   hostpriv,
51                 AuthorizedKeys:            []ssh.PublicKey{dispatchpub},
52                 ErrorRateDestroy:          0.1,
53                 MinTimeBetweenCreateCalls: time.Millisecond,
54         }
55
56         // We need the postgresql connection info from the integration
57         // test config.
58         cfg, err := config.NewLoader(nil, ctxlog.FromContext(s.ctx)).Load()
59         c.Assert(err, check.IsNil)
60         testcluster, err := cfg.GetCluster("")
61         c.Assert(err, check.IsNil)
62
63         s.cluster = &arvados.Cluster{
64                 ManagementToken: "test-management-token",
65                 PostgreSQL:      testcluster.PostgreSQL,
66                 Containers: arvados.ContainersConfig{
67                         CrunchRunCommand:       "crunch-run",
68                         CrunchRunArgumentsList: []string{"--foo", "--extra='args'"},
69                         DispatchPrivateKey:     string(dispatchprivraw),
70                         StaleLockTimeout:       arvados.Duration(5 * time.Millisecond),
71                         RuntimeEngine:          "stub",
72                         CloudVMs: arvados.CloudVMsConfig{
73                                 Driver:               "test",
74                                 SyncInterval:         arvados.Duration(10 * time.Millisecond),
75                                 TimeoutIdle:          arvados.Duration(150 * time.Millisecond),
76                                 TimeoutBooting:       arvados.Duration(150 * time.Millisecond),
77                                 TimeoutProbe:         arvados.Duration(15 * time.Millisecond),
78                                 TimeoutShutdown:      arvados.Duration(5 * time.Millisecond),
79                                 MaxCloudOpsPerSecond: 500,
80                                 PollInterval:         arvados.Duration(5 * time.Millisecond),
81                                 ProbeInterval:        arvados.Duration(5 * time.Millisecond),
82                                 MaxProbesPerSecond:   1000,
83                                 TimeoutSignal:        arvados.Duration(3 * time.Millisecond),
84                                 TimeoutStaleRunLock:  arvados.Duration(3 * time.Millisecond),
85                                 TimeoutTERM:          arvados.Duration(20 * time.Millisecond),
86                                 ResourceTags:         map[string]string{"testtag": "test value"},
87                                 TagKeyPrefix:         "test:",
88                         },
89                 },
90                 InstanceTypes: arvados.InstanceTypeMap{
91                         test.InstanceType(1).Name:  test.InstanceType(1),
92                         test.InstanceType(2).Name:  test.InstanceType(2),
93                         test.InstanceType(3).Name:  test.InstanceType(3),
94                         test.InstanceType(4).Name:  test.InstanceType(4),
95                         test.InstanceType(6).Name:  test.InstanceType(6),
96                         test.InstanceType(8).Name:  test.InstanceType(8),
97                         test.InstanceType(16).Name: test.InstanceType(16),
98                 },
99         }
100         arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
101         arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
102
103         arvClient, err := arvados.NewClientFromConfig(s.cluster)
104         c.Assert(err, check.IsNil)
105         // Disable auto-retry
106         arvClient.Timeout = 0
107
108         s.error503Server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
109                 c.Logf("503 stub: returning 503")
110                 w.WriteHeader(http.StatusServiceUnavailable)
111         }))
112         arvClient.Client = &http.Client{
113                 Transport: &http.Transport{
114                         Proxy: s.arvClientProxy(c),
115                         TLSClientConfig: &tls.Config{
116                                 InsecureSkipVerify: true}}}
117
118         s.disp = &dispatcher{
119                 Cluster:   s.cluster,
120                 Context:   s.ctx,
121                 ArvClient: arvClient,
122                 AuthToken: arvadostest.AdminToken,
123                 Registry:  prometheus.NewRegistry(),
124         }
125         // Test cases can modify s.cluster before calling
126         // initialize(), and then modify private state before calling
127         // go run().
128 }
129
130 func (s *DispatcherSuite) TearDownTest(c *check.C) {
131         s.cancel()
132         s.disp.Close()
133         s.error503Server.Close()
134 }
135
136 // Intercept outgoing API requests for "/503" and respond HTTP
137 // 503. This lets us force (*arvados.Client)Last503() to return
138 // something.
139 func (s *DispatcherSuite) arvClientProxy(c *check.C) func(*http.Request) (*url.URL, error) {
140         return func(req *http.Request) (*url.URL, error) {
141                 if req.URL.Path == "/503" {
142                         c.Logf("arvClientProxy: proxying to 503 stub")
143                         return url.Parse(s.error503Server.URL)
144                 } else {
145                         return nil, nil
146                 }
147         }
148 }
149
150 // DispatchToStubDriver checks that the dispatcher wires everything
151 // together effectively. It uses a real scheduler and worker pool with
152 // a fake queue and cloud driver. The fake cloud driver injects
153 // artificial errors in order to exercise a variety of code paths.
154 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
155         Drivers["test"] = s.stubDriver
156         s.disp.setupOnce.Do(s.disp.initialize)
157         queue := &test.Queue{
158                 MaxDispatchAttempts: 5,
159                 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
160                         return ChooseInstanceType(s.cluster, ctr)
161                 },
162                 Logger: ctxlog.TestLogger(c),
163         }
164         for i := 0; i < 200; i++ {
165                 queue.Containers = append(queue.Containers, arvados.Container{
166                         UUID:     test.ContainerUUID(i + 1),
167                         State:    arvados.ContainerStateQueued,
168                         Priority: int64(i%20 + 1),
169                         RuntimeConstraints: arvados.RuntimeConstraints{
170                                 RAM:   int64(i%3+1) << 30,
171                                 VCPUs: i%8 + 1,
172                         },
173                 })
174         }
175         s.disp.queue = queue
176
177         var mtx sync.Mutex
178         done := make(chan struct{})
179         waiting := map[string]struct{}{}
180         for _, ctr := range queue.Containers {
181                 waiting[ctr.UUID] = struct{}{}
182         }
183         finishContainer := func(ctr arvados.Container) {
184                 mtx.Lock()
185                 defer mtx.Unlock()
186                 if _, ok := waiting[ctr.UUID]; !ok {
187                         c.Errorf("container completed twice: %s", ctr.UUID)
188                         return
189                 }
190                 delete(waiting, ctr.UUID)
191                 if len(waiting) == 100 {
192                         // trigger scheduler maxConcurrency limit
193                         c.Logf("test: requesting 503 in order to trigger maxConcurrency limit")
194                         s.disp.ArvClient.RequestAndDecode(nil, "GET", "503", nil, nil)
195                 }
196                 if len(waiting) == 0 {
197                         close(done)
198                 }
199         }
200         executeContainer := func(ctr arvados.Container) int {
201                 finishContainer(ctr)
202                 return int(rand.Uint32() & 0x3)
203         }
204         n := 0
205         s.stubDriver.Queue = queue
206         s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
207                 n++
208                 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
209                 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
210                 stubvm.ExecuteContainer = executeContainer
211                 stubvm.CrashRunningContainer = finishContainer
212                 stubvm.ExtraCrunchRunArgs = "'--runtime-engine=stub' '--foo' '--extra='\\''args'\\'''"
213                 switch n % 7 {
214                 case 0:
215                         stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
216                 case 1:
217                         stubvm.CrunchRunMissing = true
218                 case 2:
219                         stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
220                 default:
221                         stubvm.CrunchRunCrashRate = 0.1
222                         stubvm.ArvMountDeadlockRate = 0.1
223                 }
224         }
225         s.stubDriver.Bugf = c.Errorf
226
227         start := time.Now()
228         go s.disp.run()
229         err := s.disp.CheckHealth()
230         c.Check(err, check.IsNil)
231
232         for len(waiting) > 0 {
233                 waswaiting := len(waiting)
234                 select {
235                 case <-done:
236                         // loop will end because len(waiting)==0
237                 case <-time.After(3 * time.Second):
238                         if len(waiting) >= waswaiting {
239                                 c.Fatalf("timed out; no progress in 3s while waiting for %d containers: %q", len(waiting), waiting)
240                         }
241                 }
242         }
243         c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
244
245         deadline := time.Now().Add(5 * time.Second)
246         for range time.NewTicker(10 * time.Millisecond).C {
247                 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
248                 c.Check(err, check.IsNil)
249                 queue.Update()
250                 ents, _ := queue.Entries()
251                 if len(ents) == 0 && len(insts) == 0 {
252                         break
253                 }
254                 if time.Now().After(deadline) {
255                         c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
256                 }
257         }
258
259         req := httptest.NewRequest("GET", "/metrics", nil)
260         req.Header.Set("Authorization", "Bearer "+s.cluster.ManagementToken)
261         resp := httptest.NewRecorder()
262         s.disp.ServeHTTP(resp, req)
263         c.Check(resp.Code, check.Equals, http.StatusOK)
264         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Create"} [^0].*`)
265         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="List"} [^0].*`)
266         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Destroy"} [^0].*`)
267         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="Create"} [^0].*`)
268         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="List"} 0\n.*`)
269         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="aborted"} [0-9]+\n.*`)
270         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="disappeared"} [^0].*`)
271         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="failure"} [^0].*`)
272         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="success"} [^0].*`)
273         c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="shutdown"} [^0].*`)
274         c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="unknown"} 0\n.*`)
275         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds{quantile="0.95"} [0-9.]*`)
276         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_count [0-9]*`)
277         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_sum [0-9.]*`)
278         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds{quantile="0.95"} [0-9.]*`)
279         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_count [0-9]*`)
280         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_sum [0-9.]*`)
281         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_count [0-9]*`)
282         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_sum [0-9.]*`)
283         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_count [0-9]*`)
284         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_sum [0-9e+.]*`)
285         c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="success"} [0-9]*`)
286         c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="success"} [0-9e+.]*`)
287         c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="fail"} [0-9]*`)
288         c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="fail"} [0-9e+.]*`)
289         c.Check(resp.Body.String(), check.Matches, `(?ms).*last_503_time [1-9][0-9e+.]*`)
290         c.Check(resp.Body.String(), check.Matches, `(?ms).*max_concurrent_containers [1-9][0-9e+.]*`)
291 }
292
293 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
294         s.cluster.ManagementToken = "abcdefgh"
295         Drivers["test"] = s.stubDriver
296         s.disp.setupOnce.Do(s.disp.initialize)
297         s.disp.queue = &test.Queue{}
298         go s.disp.run()
299
300         for _, token := range []string{"abc", ""} {
301                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
302                 if token != "" {
303                         req.Header.Set("Authorization", "Bearer "+token)
304                 }
305                 resp := httptest.NewRecorder()
306                 s.disp.ServeHTTP(resp, req)
307                 if token == "" {
308                         c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
309                 } else {
310                         c.Check(resp.Code, check.Equals, http.StatusForbidden)
311                 }
312         }
313 }
314
315 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
316         s.cluster.ManagementToken = ""
317         Drivers["test"] = s.stubDriver
318         s.disp.setupOnce.Do(s.disp.initialize)
319         s.disp.queue = &test.Queue{}
320         go s.disp.run()
321
322         for _, token := range []string{"abc", ""} {
323                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
324                 if token != "" {
325                         req.Header.Set("Authorization", "Bearer "+token)
326                 }
327                 resp := httptest.NewRecorder()
328                 s.disp.ServeHTTP(resp, req)
329                 c.Check(resp.Code, check.Equals, http.StatusForbidden)
330         }
331 }
332
333 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
334         s.cluster.ManagementToken = "abcdefgh"
335         s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
336         Drivers["test"] = s.stubDriver
337         s.disp.setupOnce.Do(s.disp.initialize)
338         s.disp.queue = &test.Queue{}
339         go s.disp.run()
340
341         type instance struct {
342                 Instance             string
343                 WorkerState          string `json:"worker_state"`
344                 Price                float64
345                 LastContainerUUID    string `json:"last_container_uuid"`
346                 ArvadosInstanceType  string `json:"arvados_instance_type"`
347                 ProviderInstanceType string `json:"provider_instance_type"`
348         }
349         type instancesResponse struct {
350                 Items []instance
351         }
352         getInstances := func() instancesResponse {
353                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
354                 req.Header.Set("Authorization", "Bearer abcdefgh")
355                 resp := httptest.NewRecorder()
356                 s.disp.ServeHTTP(resp, req)
357                 var sr instancesResponse
358                 c.Check(resp.Code, check.Equals, http.StatusOK)
359                 err := json.Unmarshal(resp.Body.Bytes(), &sr)
360                 c.Check(err, check.IsNil)
361                 return sr
362         }
363
364         sr := getInstances()
365         c.Check(len(sr.Items), check.Equals, 0)
366
367         ch := s.disp.pool.Subscribe()
368         defer s.disp.pool.Unsubscribe(ch)
369         ok := s.disp.pool.Create(test.InstanceType(1))
370         c.Check(ok, check.Equals, true)
371         <-ch
372
373         for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
374                 sr = getInstances()
375                 if len(sr.Items) > 0 {
376                         break
377                 }
378                 time.Sleep(time.Millisecond)
379         }
380         c.Assert(len(sr.Items), check.Equals, 1)
381         c.Check(sr.Items[0].Instance, check.Matches, "inst.*")
382         c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
383         c.Check(sr.Items[0].Price, check.Equals, 0.123)
384         c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
385         c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
386         c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)
387 }