1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
27 var _ = check.Suite(&DispatcherSuite{})
29 type DispatcherSuite struct {
31 cancel context.CancelFunc
32 cluster *arvados.Cluster
33 stubDriver *test.StubDriver
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)
44 _, hostpriv := test.LoadTestKey(c, "test/sshkey_vm")
45 s.stubDriver = &test.StubDriver{
47 AuthorizedKeys: []ssh.PublicKey{dispatchpub},
48 ErrorRateDestroy: 0.1,
49 MinTimeBetweenCreateCalls: time.Millisecond,
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{
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:",
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),
88 arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
89 arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
91 arvClient, err := arvados.NewClientFromConfig(s.cluster)
92 c.Check(err, check.IsNil)
98 AuthToken: arvadostest.AdminToken,
99 Registry: prometheus.NewRegistry(),
101 // Test cases can modify s.cluster before calling
102 // initialize(), and then modify private state before calling
106 func (s *DispatcherSuite) TearDownTest(c *check.C) {
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)
122 Logger: ctxlog.TestLogger(c),
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,
138 done := make(chan struct{})
139 waiting := map[string]struct{}{}
140 for _, ctr := range queue.Containers {
141 waiting[ctr.UUID] = struct{}{}
143 finishContainer := func(ctr arvados.Container) {
146 if _, ok := waiting[ctr.UUID]; !ok {
147 c.Errorf("container completed twice: %s", ctr.UUID)
150 delete(waiting, ctr.UUID)
151 if len(waiting) == 0 {
155 executeContainer := func(ctr arvados.Container) int {
157 return int(rand.Uint32() & 0x3)
160 s.stubDriver.Queue = queue
161 s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
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'\\'''"
170 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
172 stubvm.CrunchRunMissing = true
174 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
176 stubvm.CrunchRunCrashRate = 0.1
177 stubvm.ArvMountDeadlockRate = 0.1
180 s.stubDriver.Bugf = c.Errorf
184 err := s.disp.CheckHealth()
185 c.Check(err, check.IsNil)
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)
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)
199 ents, _ := queue.Entries()
200 if len(ents) == 0 && len(insts) == 0 {
203 if time.Now().After(deadline) {
204 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
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+.]*`)
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{}
247 for _, token := range []string{"abc", ""} {
248 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
250 req.Header.Set("Authorization", "Bearer "+token)
252 resp := httptest.NewRecorder()
253 s.disp.ServeHTTP(resp, req)
255 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
257 c.Check(resp.Code, check.Equals, http.StatusForbidden)
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{}
269 for _, token := range []string{"abc", ""} {
270 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
272 req.Header.Set("Authorization", "Bearer "+token)
274 resp := httptest.NewRecorder()
275 s.disp.ServeHTTP(resp, req)
276 c.Check(resp.Code, check.Equals, http.StatusForbidden)
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{}
288 type instance struct {
290 WorkerState string `json:"worker_state"`
292 LastContainerUUID string `json:"last_container_uuid"`
293 ArvadosInstanceType string `json:"arvados_instance_type"`
294 ProviderInstanceType string `json:"provider_instance_type"`
296 type instancesResponse struct {
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)
312 c.Check(len(sr.Items), check.Equals, 0)
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)
320 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
322 if len(sr.Items) > 0 {
325 time.Sleep(time.Millisecond)
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)