Merge branch '15964-fix-docs' refs #15964
[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         "encoding/json"
10         "io/ioutil"
11         "math/rand"
12         "net/http"
13         "net/http/httptest"
14         "os"
15         "sync"
16         "time"
17
18         "git.arvados.org/arvados.git/lib/dispatchcloud/test"
19         "git.arvados.org/arvados.git/sdk/go/arvados"
20         "git.arvados.org/arvados.git/sdk/go/arvadostest"
21         "git.arvados.org/arvados.git/sdk/go/ctxlog"
22         "github.com/prometheus/client_golang/prometheus"
23         "golang.org/x/crypto/ssh"
24         check "gopkg.in/check.v1"
25 )
26
27 var _ = check.Suite(&DispatcherSuite{})
28
29 type DispatcherSuite struct {
30         ctx        context.Context
31         cancel     context.CancelFunc
32         cluster    *arvados.Cluster
33         stubDriver *test.StubDriver
34         disp       *dispatcher
35 }
36
37 func (s *DispatcherSuite) SetUpTest(c *check.C) {
38         s.ctx, s.cancel = context.WithCancel(context.Background())
39         s.ctx = ctxlog.Context(s.ctx, ctxlog.TestLogger(c))
40         dispatchpub, _ := test.LoadTestKey(c, "test/sshkey_dispatch")
41         dispatchprivraw, err := ioutil.ReadFile("test/sshkey_dispatch")
42         c.Assert(err, check.IsNil)
43
44         _, hostpriv := test.LoadTestKey(c, "test/sshkey_vm")
45         s.stubDriver = &test.StubDriver{
46                 HostKey:                   hostpriv,
47                 AuthorizedKeys:            []ssh.PublicKey{dispatchpub},
48                 ErrorRateDestroy:          0.1,
49                 MinTimeBetweenCreateCalls: time.Millisecond,
50         }
51
52         s.cluster = &arvados.Cluster{
53                 ManagementToken: "test-management-token",
54                 Containers: arvados.ContainersConfig{
55                         DispatchPrivateKey: string(dispatchprivraw),
56                         StaleLockTimeout:   arvados.Duration(5 * time.Millisecond),
57                         CloudVMs: arvados.CloudVMsConfig{
58                                 Driver:               "test",
59                                 SyncInterval:         arvados.Duration(10 * time.Millisecond),
60                                 TimeoutIdle:          arvados.Duration(150 * time.Millisecond),
61                                 TimeoutBooting:       arvados.Duration(150 * time.Millisecond),
62                                 TimeoutProbe:         arvados.Duration(15 * time.Millisecond),
63                                 TimeoutShutdown:      arvados.Duration(5 * time.Millisecond),
64                                 MaxCloudOpsPerSecond: 500,
65                                 PollInterval:         arvados.Duration(5 * time.Millisecond),
66                                 ProbeInterval:        arvados.Duration(5 * time.Millisecond),
67                                 MaxProbesPerSecond:   1000,
68                                 TimeoutSignal:        arvados.Duration(3 * time.Millisecond),
69                                 TimeoutTERM:          arvados.Duration(20 * time.Millisecond),
70                                 ResourceTags:         map[string]string{"testtag": "test value"},
71                                 TagKeyPrefix:         "test:",
72                         },
73                 },
74                 InstanceTypes: arvados.InstanceTypeMap{
75                         test.InstanceType(1).Name:  test.InstanceType(1),
76                         test.InstanceType(2).Name:  test.InstanceType(2),
77                         test.InstanceType(3).Name:  test.InstanceType(3),
78                         test.InstanceType(4).Name:  test.InstanceType(4),
79                         test.InstanceType(6).Name:  test.InstanceType(6),
80                         test.InstanceType(8).Name:  test.InstanceType(8),
81                         test.InstanceType(16).Name: test.InstanceType(16),
82                 },
83         }
84         arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
85         arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
86
87         arvClient, err := arvados.NewClientFromConfig(s.cluster)
88         c.Check(err, check.IsNil)
89
90         s.disp = &dispatcher{
91                 Cluster:   s.cluster,
92                 Context:   s.ctx,
93                 ArvClient: arvClient,
94                 AuthToken: arvadostest.AdminToken,
95                 Registry:  prometheus.NewRegistry(),
96         }
97         // Test cases can modify s.cluster before calling
98         // initialize(), and then modify private state before calling
99         // go run().
100 }
101
102 func (s *DispatcherSuite) TearDownTest(c *check.C) {
103         s.cancel()
104         s.disp.Close()
105 }
106
107 // DispatchToStubDriver checks that the dispatcher wires everything
108 // together effectively. It uses a real scheduler and worker pool with
109 // a fake queue and cloud driver. The fake cloud driver injects
110 // artificial errors in order to exercise a variety of code paths.
111 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
112         Drivers["test"] = s.stubDriver
113         s.disp.setupOnce.Do(s.disp.initialize)
114         queue := &test.Queue{
115                 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
116                         return ChooseInstanceType(s.cluster, ctr)
117                 },
118                 Logger: ctxlog.TestLogger(c),
119         }
120         for i := 0; i < 200; i++ {
121                 queue.Containers = append(queue.Containers, arvados.Container{
122                         UUID:     test.ContainerUUID(i + 1),
123                         State:    arvados.ContainerStateQueued,
124                         Priority: int64(i%20 + 1),
125                         RuntimeConstraints: arvados.RuntimeConstraints{
126                                 RAM:   int64(i%3+1) << 30,
127                                 VCPUs: i%8 + 1,
128                         },
129                 })
130         }
131         s.disp.queue = queue
132
133         var mtx sync.Mutex
134         done := make(chan struct{})
135         waiting := map[string]struct{}{}
136         for _, ctr := range queue.Containers {
137                 waiting[ctr.UUID] = struct{}{}
138         }
139         finishContainer := func(ctr arvados.Container) {
140                 mtx.Lock()
141                 defer mtx.Unlock()
142                 if _, ok := waiting[ctr.UUID]; !ok {
143                         c.Errorf("container completed twice: %s", ctr.UUID)
144                         return
145                 }
146                 delete(waiting, ctr.UUID)
147                 if len(waiting) == 0 {
148                         close(done)
149                 }
150         }
151         executeContainer := func(ctr arvados.Container) int {
152                 finishContainer(ctr)
153                 return int(rand.Uint32() & 0x3)
154         }
155         n := 0
156         s.stubDriver.Queue = queue
157         s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
158                 n++
159                 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
160                 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
161                 stubvm.ExecuteContainer = executeContainer
162                 stubvm.CrashRunningContainer = finishContainer
163                 switch n % 7 {
164                 case 0:
165                         stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
166                 case 1:
167                         stubvm.CrunchRunMissing = true
168                 case 2:
169                         stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
170                 default:
171                         stubvm.CrunchRunCrashRate = 0.1
172                 }
173         }
174         s.stubDriver.Bugf = c.Errorf
175
176         start := time.Now()
177         go s.disp.run()
178         err := s.disp.CheckHealth()
179         c.Check(err, check.IsNil)
180
181         select {
182         case <-done:
183                 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
184         case <-time.After(10 * time.Second):
185                 c.Fatalf("timed out; still waiting for %d containers: %q", len(waiting), waiting)
186         }
187
188         deadline := time.Now().Add(5 * time.Second)
189         for range time.NewTicker(10 * time.Millisecond).C {
190                 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
191                 c.Check(err, check.IsNil)
192                 queue.Update()
193                 ents, _ := queue.Entries()
194                 if len(ents) == 0 && len(insts) == 0 {
195                         break
196                 }
197                 if time.Now().After(deadline) {
198                         c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
199                 }
200         }
201
202         req := httptest.NewRequest("GET", "/metrics", nil)
203         req.Header.Set("Authorization", "Bearer "+s.cluster.ManagementToken)
204         resp := httptest.NewRecorder()
205         s.disp.ServeHTTP(resp, req)
206         c.Check(resp.Code, check.Equals, http.StatusOK)
207         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Create"} [^0].*`)
208         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="List"} [^0].*`)
209         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Destroy"} [^0].*`)
210         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="Create"} [^0].*`)
211         c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="List"} 0\n.*`)
212         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="aborted"} 0.*`)
213         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="disappeared"} [^0].*`)
214         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="failure"} [^0].*`)
215         c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="success"} [^0].*`)
216         c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="shutdown"} [^0].*`)
217         c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="unknown"} 0\n.*`)
218 }
219
220 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
221         s.cluster.ManagementToken = "abcdefgh"
222         Drivers["test"] = s.stubDriver
223         s.disp.setupOnce.Do(s.disp.initialize)
224         s.disp.queue = &test.Queue{}
225         go s.disp.run()
226
227         for _, token := range []string{"abc", ""} {
228                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
229                 if token != "" {
230                         req.Header.Set("Authorization", "Bearer "+token)
231                 }
232                 resp := httptest.NewRecorder()
233                 s.disp.ServeHTTP(resp, req)
234                 if token == "" {
235                         c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
236                 } else {
237                         c.Check(resp.Code, check.Equals, http.StatusForbidden)
238                 }
239         }
240 }
241
242 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
243         s.cluster.ManagementToken = ""
244         Drivers["test"] = s.stubDriver
245         s.disp.setupOnce.Do(s.disp.initialize)
246         s.disp.queue = &test.Queue{}
247         go s.disp.run()
248
249         for _, token := range []string{"abc", ""} {
250                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
251                 if token != "" {
252                         req.Header.Set("Authorization", "Bearer "+token)
253                 }
254                 resp := httptest.NewRecorder()
255                 s.disp.ServeHTTP(resp, req)
256                 c.Check(resp.Code, check.Equals, http.StatusForbidden)
257         }
258 }
259
260 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
261         s.cluster.ManagementToken = "abcdefgh"
262         s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
263         Drivers["test"] = s.stubDriver
264         s.disp.setupOnce.Do(s.disp.initialize)
265         s.disp.queue = &test.Queue{}
266         go s.disp.run()
267
268         type instance struct {
269                 Instance             string
270                 WorkerState          string `json:"worker_state"`
271                 Price                float64
272                 LastContainerUUID    string `json:"last_container_uuid"`
273                 ArvadosInstanceType  string `json:"arvados_instance_type"`
274                 ProviderInstanceType string `json:"provider_instance_type"`
275         }
276         type instancesResponse struct {
277                 Items []instance
278         }
279         getInstances := func() instancesResponse {
280                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
281                 req.Header.Set("Authorization", "Bearer abcdefgh")
282                 resp := httptest.NewRecorder()
283                 s.disp.ServeHTTP(resp, req)
284                 var sr instancesResponse
285                 c.Check(resp.Code, check.Equals, http.StatusOK)
286                 err := json.Unmarshal(resp.Body.Bytes(), &sr)
287                 c.Check(err, check.IsNil)
288                 return sr
289         }
290
291         sr := getInstances()
292         c.Check(len(sr.Items), check.Equals, 0)
293
294         ch := s.disp.pool.Subscribe()
295         defer s.disp.pool.Unsubscribe(ch)
296         ok := s.disp.pool.Create(test.InstanceType(1))
297         c.Check(ok, check.Equals, true)
298         <-ch
299
300         for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
301                 sr = getInstances()
302                 if len(sr.Items) > 0 {
303                         break
304                 }
305                 time.Sleep(time.Millisecond)
306         }
307         c.Assert(len(sr.Items), check.Equals, 1)
308         c.Check(sr.Items[0].Instance, check.Matches, "inst.*")
309         c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
310         c.Check(sr.Items[0].Price, check.Equals, 0.123)
311         c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
312         c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
313         c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)
314 }