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