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