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