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