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 CloudVMs: arvados.CloudVMsConfig{
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:",
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),
87 arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
88 arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
90 arvClient, err := arvados.NewClientFromConfig(s.cluster)
91 c.Check(err, check.IsNil)
97 AuthToken: arvadostest.AdminToken,
98 Registry: prometheus.NewRegistry(),
100 // Test cases can modify s.cluster before calling
101 // initialize(), and then modify private state before calling
105 func (s *DispatcherSuite) TearDownTest(c *check.C) {
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)
121 Logger: ctxlog.TestLogger(c),
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,
137 done := make(chan struct{})
138 waiting := map[string]struct{}{}
139 for _, ctr := range queue.Containers {
140 waiting[ctr.UUID] = struct{}{}
142 finishContainer := func(ctr arvados.Container) {
145 if _, ok := waiting[ctr.UUID]; !ok {
146 c.Errorf("container completed twice: %s", ctr.UUID)
149 delete(waiting, ctr.UUID)
150 if len(waiting) == 0 {
154 executeContainer := func(ctr arvados.Container) int {
156 return int(rand.Uint32() & 0x3)
159 s.stubDriver.Queue = queue
160 s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
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'\\'''"
169 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
171 stubvm.CrunchRunMissing = true
173 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
175 stubvm.CrunchRunCrashRate = 0.1
176 stubvm.ArvMountDeadlockRate = 0.1
179 s.stubDriver.Bugf = c.Errorf
183 err := s.disp.CheckHealth()
184 c.Check(err, check.IsNil)
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)
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)
198 ents, _ := queue.Entries()
199 if len(ents) == 0 && len(insts) == 0 {
202 if time.Now().After(deadline) {
203 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
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+.]*`)
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{}
246 for _, token := range []string{"abc", ""} {
247 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
249 req.Header.Set("Authorization", "Bearer "+token)
251 resp := httptest.NewRecorder()
252 s.disp.ServeHTTP(resp, req)
254 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
256 c.Check(resp.Code, check.Equals, http.StatusForbidden)
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{}
268 for _, token := range []string{"abc", ""} {
269 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
271 req.Header.Set("Authorization", "Bearer "+token)
273 resp := httptest.NewRecorder()
274 s.disp.ServeHTTP(resp, req)
275 c.Check(resp.Code, check.Equals, http.StatusForbidden)
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{}
287 type instance struct {
289 WorkerState string `json:"worker_state"`
291 LastContainerUUID string `json:"last_container_uuid"`
292 ArvadosInstanceType string `json:"arvados_instance_type"`
293 ProviderInstanceType string `json:"provider_instance_type"`
295 type instancesResponse struct {
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)
311 c.Check(len(sr.Items), check.Equals, 0)
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)
319 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
321 if len(sr.Items) > 0 {
324 time.Sleep(time.Millisecond)
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)