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