21126: Merge branch 'main' into 21126-trash-when-ro
[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         n := 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++
220                 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
221                 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
222                 stubvm.ExecuteContainer = executeContainer
223                 stubvm.CrashRunningContainer = finishContainer
224                 stubvm.ExtraCrunchRunArgs = "'--runtime-engine=stub' '--foo' '--extra='\\''args'\\'''"
225                 switch {
226                 case n%7 == 0:
227                         // some instances start out OK but then stop
228                         // running any commands
229                         stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
230                 case n%7 == 1:
231                         // some instances never pass a run-probe
232                         stubvm.CrunchRunMissing = true
233                 case n%7 == 2:
234                         // some instances start out OK but then start
235                         // reporting themselves as broken
236                         stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
237                 case n == 3:
238                         // 1 instance is completely broken, ensuring
239                         // the boot_outcomes{outcome="failure"} metric
240                         // is not zero
241                         stubvm.CrunchRunCrashRate = 1
242                 default:
243                         stubvm.CrunchRunCrashRate = 0.1
244                         stubvm.ArvMountDeadlockRate = 0.1
245                 }
246                 return nil
247         }
248         s.stubDriver.Bugf = c.Errorf
249
250         start := time.Now()
251         go s.disp.run()
252         err := s.disp.CheckHealth()
253         c.Check(err, check.IsNil)
254
255         for len(waiting) > 0 {
256                 waswaiting := len(waiting)
257                 select {
258                 case <-done:
259                         // loop will end because len(waiting)==0
260                 case <-time.After(5 * time.Second):
261                         if len(waiting) >= waswaiting {
262                                 c.Fatalf("timed out; no progress in 5 s while waiting for %d containers: %q", len(waiting), waiting)
263                         }
264                 }
265         }
266         c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
267
268         deadline := time.Now().Add(5 * time.Second)
269         for range time.NewTicker(10 * time.Millisecond).C {
270                 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
271                 c.Check(err, check.IsNil)
272                 queue.Update()
273                 ents, _ := queue.Entries()
274                 if len(ents) == 0 && len(insts) == 0 {
275                         break
276                 }
277                 if time.Now().After(deadline) {
278                         c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
279                 }
280         }
281
282         c.Check(countCapacityErrors, check.Not(check.Equals), int64(0))
283
284         req := httptest.NewRequest("GET", "/metrics", nil)
285         req.Header.Set("Authorization", "Bearer "+s.cluster.ManagementToken)
286         resp := httptest.NewRecorder()
287         s.disp.ServeHTTP(resp, req)
288         c.Check(resp.Code, check.Equals, http.StatusOK)
289         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Create"} [^0].*`)
290         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="List"} [^0].*`)
291         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Destroy"} [^0].*`)
292         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="Create"} [^0].*`)
293         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="List"} 0\n.*`)
294         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="aborted"} [0-9]+\n.*`)
295         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="disappeared"} [^0].*`)
296         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="failure"} [^0].*`)
297         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="success"} [^0].*`)
298         c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="shutdown"} [^0].*`)
299         c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="unknown"} 0\n.*`)
300         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds{quantile="0.95"} [0-9.]*`)
301         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_count [0-9]*`)
302         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_sum [0-9.]*`)
303         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds{quantile="0.95"} [0-9.]*`)
304         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_count [0-9]*`)
305         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_sum [0-9.]*`)
306         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_count [0-9]*`)
307         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_sum [0-9.]*`)
308         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_count [0-9]*`)
309         c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_sum [0-9e+.]*`)
310         c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="success"} [0-9]*`)
311         c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="success"} [0-9e+.]*`)
312         c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="fail"} [0-9]*`)
313         c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="fail"} [0-9e+.]*`)
314         c.Check(resp.Body.String(), check.Matches, `(?ms).*last_503_time [1-9][0-9e+.]*`)
315         c.Check(resp.Body.String(), check.Matches, `(?ms).*max_concurrent_containers [1-9][0-9e+.]*`)
316 }
317
318 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
319         s.cluster.ManagementToken = "abcdefgh"
320         Drivers["test"] = s.stubDriver
321         s.disp.setupOnce.Do(s.disp.initialize)
322         s.disp.queue = &test.Queue{}
323         go s.disp.run()
324
325         for _, token := range []string{"abc", ""} {
326                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
327                 if token != "" {
328                         req.Header.Set("Authorization", "Bearer "+token)
329                 }
330                 resp := httptest.NewRecorder()
331                 s.disp.ServeHTTP(resp, req)
332                 if token == "" {
333                         c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
334                 } else {
335                         c.Check(resp.Code, check.Equals, http.StatusForbidden)
336                 }
337         }
338 }
339
340 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
341         s.cluster.ManagementToken = ""
342         Drivers["test"] = s.stubDriver
343         s.disp.setupOnce.Do(s.disp.initialize)
344         s.disp.queue = &test.Queue{}
345         go s.disp.run()
346
347         for _, token := range []string{"abc", ""} {
348                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
349                 if token != "" {
350                         req.Header.Set("Authorization", "Bearer "+token)
351                 }
352                 resp := httptest.NewRecorder()
353                 s.disp.ServeHTTP(resp, req)
354                 c.Check(resp.Code, check.Equals, http.StatusForbidden)
355         }
356 }
357
358 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
359         s.cluster.ManagementToken = "abcdefgh"
360         s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
361         Drivers["test"] = s.stubDriver
362         s.disp.setupOnce.Do(s.disp.initialize)
363         s.disp.queue = &test.Queue{}
364         go s.disp.run()
365
366         type instance struct {
367                 Instance             string
368                 WorkerState          string `json:"worker_state"`
369                 Price                float64
370                 LastContainerUUID    string `json:"last_container_uuid"`
371                 ArvadosInstanceType  string `json:"arvados_instance_type"`
372                 ProviderInstanceType string `json:"provider_instance_type"`
373         }
374         type instancesResponse struct {
375                 Items []instance
376         }
377         getInstances := func() instancesResponse {
378                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
379                 req.Header.Set("Authorization", "Bearer abcdefgh")
380                 resp := httptest.NewRecorder()
381                 s.disp.ServeHTTP(resp, req)
382                 var sr instancesResponse
383                 c.Check(resp.Code, check.Equals, http.StatusOK)
384                 err := json.Unmarshal(resp.Body.Bytes(), &sr)
385                 c.Check(err, check.IsNil)
386                 return sr
387         }
388
389         sr := getInstances()
390         c.Check(len(sr.Items), check.Equals, 0)
391
392         s.stubDriver.ErrorRateCreate = 0
393         ch := s.disp.pool.Subscribe()
394         defer s.disp.pool.Unsubscribe(ch)
395         ok := s.disp.pool.Create(test.InstanceType(1))
396         c.Check(ok, check.Equals, true)
397         <-ch
398
399         for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
400                 sr = getInstances()
401                 if len(sr.Items) > 0 {
402                         break
403                 }
404                 time.Sleep(time.Millisecond)
405         }
406         c.Assert(len(sr.Items), check.Equals, 1)
407         c.Check(sr.Items[0].Instance, check.Matches, "inst.*")
408         c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
409         c.Check(sr.Items[0].Price, check.Equals, 0.123)
410         c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
411         c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
412         c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)
413 }