1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
21 "git.arvados.org/arvados.git/lib/config"
22 "git.arvados.org/arvados.git/lib/dispatchcloud/test"
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "git.arvados.org/arvados.git/sdk/go/arvadostest"
25 "git.arvados.org/arvados.git/sdk/go/ctxlog"
26 "github.com/prometheus/client_golang/prometheus"
27 "golang.org/x/crypto/ssh"
28 check "gopkg.in/check.v1"
31 var _ = check.Suite(&DispatcherSuite{})
33 type DispatcherSuite struct {
35 cancel context.CancelFunc
36 cluster *arvados.Cluster
37 stubDriver *test.StubDriver
39 error503Server *httptest.Server
42 func (s *DispatcherSuite) SetUpTest(c *check.C) {
43 s.ctx, s.cancel = context.WithCancel(context.Background())
44 s.ctx = ctxlog.Context(s.ctx, ctxlog.TestLogger(c))
45 dispatchpub, _ := test.LoadTestKey(c, "test/sshkey_dispatch")
46 dispatchprivraw, err := ioutil.ReadFile("test/sshkey_dispatch")
47 c.Assert(err, check.IsNil)
49 _, hostpriv := test.LoadTestKey(c, "test/sshkey_vm")
50 s.stubDriver = &test.StubDriver{
52 AuthorizedKeys: []ssh.PublicKey{dispatchpub},
54 ErrorRateDestroy: 0.1,
55 MinTimeBetweenCreateCalls: time.Millisecond,
56 QuotaMaxInstances: 10,
59 // We need the postgresql connection info from the integration
61 cfg, err := config.NewLoader(nil, ctxlog.FromContext(s.ctx)).Load()
62 c.Assert(err, check.IsNil)
63 testcluster, err := cfg.GetCluster("")
64 c.Assert(err, check.IsNil)
66 s.cluster = &arvados.Cluster{
67 ManagementToken: "test-management-token",
68 PostgreSQL: testcluster.PostgreSQL,
69 Containers: arvados.ContainersConfig{
70 CrunchRunCommand: "crunch-run",
71 CrunchRunArgumentsList: []string{"--foo", "--extra='args'"},
72 DispatchPrivateKey: string(dispatchprivraw),
73 StaleLockTimeout: arvados.Duration(5 * time.Millisecond),
74 RuntimeEngine: "stub",
75 MaxDispatchAttempts: 10,
76 MaximumPriceFactor: 1.5,
77 CloudVMs: arvados.CloudVMsConfig{
79 SyncInterval: arvados.Duration(10 * time.Millisecond),
80 TimeoutIdle: arvados.Duration(150 * time.Millisecond),
81 TimeoutBooting: arvados.Duration(150 * time.Millisecond),
82 TimeoutProbe: arvados.Duration(15 * time.Millisecond),
83 TimeoutShutdown: arvados.Duration(5 * time.Millisecond),
84 MaxCloudOpsPerSecond: 500,
85 InitialQuotaEstimate: 8,
86 PollInterval: arvados.Duration(5 * time.Millisecond),
87 ProbeInterval: arvados.Duration(5 * time.Millisecond),
88 MaxProbesPerSecond: 1000,
89 TimeoutSignal: arvados.Duration(3 * time.Millisecond),
90 TimeoutStaleRunLock: arvados.Duration(3 * time.Millisecond),
91 TimeoutTERM: arvados.Duration(20 * time.Millisecond),
92 ResourceTags: map[string]string{"testtag": "test value"},
93 TagKeyPrefix: "test:",
96 InstanceTypes: arvados.InstanceTypeMap{
97 test.InstanceType(1).Name: test.InstanceType(1),
98 test.InstanceType(2).Name: test.InstanceType(2),
99 test.InstanceType(3).Name: test.InstanceType(3),
100 test.InstanceType(4).Name: test.InstanceType(4),
101 test.InstanceType(6).Name: test.InstanceType(6),
102 test.InstanceType(8).Name: test.InstanceType(8),
103 test.InstanceType(16).Name: test.InstanceType(16),
106 arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
107 arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
109 arvClient, err := arvados.NewClientFromConfig(s.cluster)
110 c.Assert(err, check.IsNil)
111 // Disable auto-retry
112 arvClient.Timeout = 0
114 s.error503Server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
115 c.Logf("503 stub: returning 503")
116 w.WriteHeader(http.StatusServiceUnavailable)
118 arvClient.Client = &http.Client{
119 Transport: &http.Transport{
120 Proxy: s.arvClientProxy(c),
121 TLSClientConfig: &tls.Config{
122 InsecureSkipVerify: true}}}
124 s.disp = &dispatcher{
127 ArvClient: arvClient,
128 AuthToken: arvadostest.AdminToken,
129 Registry: prometheus.NewRegistry(),
131 // Test cases can modify s.cluster before calling
132 // initialize(), and then modify private state before calling
136 func (s *DispatcherSuite) TearDownTest(c *check.C) {
139 s.error503Server.Close()
142 // Intercept outgoing API requests for "/503" and respond HTTP
143 // 503. This lets us force (*arvados.Client)Last503() to return
145 func (s *DispatcherSuite) arvClientProxy(c *check.C) func(*http.Request) (*url.URL, error) {
146 return func(req *http.Request) (*url.URL, error) {
147 if req.URL.Path == "/503" {
148 c.Logf("arvClientProxy: proxying to 503 stub")
149 return url.Parse(s.error503Server.URL)
156 // DispatchToStubDriver checks that the dispatcher wires everything
157 // together effectively. It uses a real scheduler and worker pool with
158 // a fake queue and cloud driver. The fake cloud driver injects
159 // artificial errors in order to exercise a variety of code paths.
160 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
161 Drivers["test"] = s.stubDriver
162 s.disp.setupOnce.Do(s.disp.initialize)
163 queue := &test.Queue{
164 MaxDispatchAttempts: 5,
165 ChooseType: func(ctr *arvados.Container) ([]arvados.InstanceType, error) {
166 return ChooseInstanceType(s.cluster, ctr)
168 Logger: ctxlog.TestLogger(c),
170 for i := 0; i < 200; i++ {
171 queue.Containers = append(queue.Containers, arvados.Container{
172 UUID: test.ContainerUUID(i + 1),
173 State: arvados.ContainerStateQueued,
174 Priority: int64(i%20 + 1),
175 RuntimeConstraints: arvados.RuntimeConstraints{
176 RAM: int64(i%3+1) << 30,
184 done := make(chan struct{})
185 waiting := map[string]struct{}{}
186 for _, ctr := range queue.Containers {
187 waiting[ctr.UUID] = struct{}{}
189 finishContainer := func(ctr arvados.Container) {
192 if _, ok := waiting[ctr.UUID]; !ok {
193 c.Errorf("container completed twice: %s", ctr.UUID)
196 delete(waiting, ctr.UUID)
197 if len(waiting) == 100 {
198 // trigger scheduler maxConcurrency limit
199 c.Logf("test: requesting 503 in order to trigger maxConcurrency limit")
200 s.disp.ArvClient.RequestAndDecode(nil, "GET", "503", nil, nil)
202 if len(waiting) == 0 {
206 executeContainer := func(ctr arvados.Container) int {
208 return int(rand.Uint32() & 0x3)
210 var countCapacityErrors int64
212 s.stubDriver.Queue = queue
213 s.stubDriver.SetupVM = func(stubvm *test.StubVM) error {
214 if pt := stubvm.Instance().ProviderType(); pt == test.InstanceType(6).ProviderType {
215 c.Logf("test: returning capacity error for instance type %s", pt)
216 atomic.AddInt64(&countCapacityErrors, 1)
217 return test.CapacityError{InstanceTypeSpecific: true}
219 n := atomic.AddInt32(&vmCount, 1)
220 c.Logf("SetupVM: instance %s n=%d", stubvm.Instance(), n)
221 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
222 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
223 stubvm.ExecuteContainer = executeContainer
224 stubvm.CrashRunningContainer = finishContainer
225 stubvm.ExtraCrunchRunArgs = "'--runtime-engine=stub' '--foo' '--extra='\\''args'\\'''"
228 // some instances start out OK but then stop
229 // running any commands
230 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
232 // some instances never pass a run-probe
233 stubvm.CrunchRunMissing = true
235 // some instances start out OK but then start
236 // reporting themselves as broken
237 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
239 // 1 instance is completely broken, ensuring
240 // the boot_outcomes{outcome="failure"} metric
242 stubvm.Broken = time.Now()
244 stubvm.CrunchRunCrashRate = 0.1
245 stubvm.ArvMountDeadlockRate = 0.1
249 s.stubDriver.Bugf = c.Errorf
253 err := s.disp.CheckHealth()
254 c.Check(err, check.IsNil)
256 for len(waiting) > 0 {
257 waswaiting := len(waiting)
260 // loop will end because len(waiting)==0
261 case <-time.After(5 * time.Second):
262 if len(waiting) >= waswaiting {
263 c.Fatalf("timed out; no progress in 5 s while waiting for %d containers: %q", len(waiting), waiting)
267 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
269 deadline := time.Now().Add(5 * time.Second)
270 for range time.NewTicker(10 * time.Millisecond).C {
271 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
272 c.Check(err, check.IsNil)
274 ents, _ := queue.Entries()
275 if len(ents) == 0 && len(insts) == 0 {
278 if time.Now().After(deadline) {
279 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
283 c.Check(countCapacityErrors, check.Not(check.Equals), int64(0))
285 req := httptest.NewRequest("GET", "/metrics", nil)
286 req.Header.Set("Authorization", "Bearer "+s.cluster.ManagementToken)
287 resp := httptest.NewRecorder()
288 s.disp.ServeHTTP(resp, req)
289 c.Check(resp.Code, check.Equals, http.StatusOK)
290 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Create"} [^0].*`)
291 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="List"} [^0].*`)
292 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Destroy"} [^0].*`)
293 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="Create"} [^0].*`)
294 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="List"} 0\n.*`)
295 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="aborted"} [0-9]+\n.*`)
296 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="disappeared"} [^0].*`)
297 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="failure"} [^0].*`)
298 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="success"} [^0].*`)
299 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="shutdown"} [^0].*`)
300 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="unknown"} 0\n.*`)
301 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds{quantile="0.95"} [0-9.]*`)
302 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_count [0-9]*`)
303 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_sum [0-9.]*`)
304 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds{quantile="0.95"} [0-9.]*`)
305 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_count [0-9]*`)
306 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_sum [0-9.]*`)
307 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_count [0-9]*`)
308 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_sum [0-9.]*`)
309 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_count [0-9]*`)
310 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_sum [0-9e+.]*`)
311 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="success"} [0-9]*`)
312 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="success"} [0-9e+.]*`)
313 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="fail"} [0-9]*`)
314 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="fail"} [0-9e+.]*`)
315 c.Check(resp.Body.String(), check.Matches, `(?ms).*last_503_time [1-9][0-9e+.]*`)
316 c.Check(resp.Body.String(), check.Matches, `(?ms).*max_concurrent_containers [1-9][0-9e+.]*`)
319 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
320 s.cluster.ManagementToken = "abcdefgh"
321 Drivers["test"] = s.stubDriver
322 s.disp.setupOnce.Do(s.disp.initialize)
323 s.disp.queue = &test.Queue{}
326 for _, token := range []string{"abc", ""} {
327 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
329 req.Header.Set("Authorization", "Bearer "+token)
331 resp := httptest.NewRecorder()
332 s.disp.ServeHTTP(resp, req)
334 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
336 c.Check(resp.Code, check.Equals, http.StatusForbidden)
341 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
342 s.cluster.ManagementToken = ""
343 Drivers["test"] = s.stubDriver
344 s.disp.setupOnce.Do(s.disp.initialize)
345 s.disp.queue = &test.Queue{}
348 for _, token := range []string{"abc", ""} {
349 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
351 req.Header.Set("Authorization", "Bearer "+token)
353 resp := httptest.NewRecorder()
354 s.disp.ServeHTTP(resp, req)
355 c.Check(resp.Code, check.Equals, http.StatusForbidden)
359 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
360 s.cluster.ManagementToken = "abcdefgh"
361 s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
362 Drivers["test"] = s.stubDriver
363 s.disp.setupOnce.Do(s.disp.initialize)
364 s.disp.queue = &test.Queue{}
367 type instance struct {
369 WorkerState string `json:"worker_state"`
371 LastContainerUUID string `json:"last_container_uuid"`
372 ArvadosInstanceType string `json:"arvados_instance_type"`
373 ProviderInstanceType string `json:"provider_instance_type"`
375 type instancesResponse struct {
378 getInstances := func() instancesResponse {
379 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
380 req.Header.Set("Authorization", "Bearer abcdefgh")
381 resp := httptest.NewRecorder()
382 s.disp.ServeHTTP(resp, req)
383 var sr instancesResponse
384 c.Check(resp.Code, check.Equals, http.StatusOK)
385 err := json.Unmarshal(resp.Body.Bytes(), &sr)
386 c.Check(err, check.IsNil)
391 c.Check(len(sr.Items), check.Equals, 0)
393 s.stubDriver.ErrorRateCreate = 0
394 ch := s.disp.pool.Subscribe()
395 defer s.disp.pool.Unsubscribe(ch)
396 ok := s.disp.pool.Create(test.InstanceType(1))
397 c.Check(ok, check.Equals, true)
400 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
402 if len(sr.Items) > 0 {
405 time.Sleep(time.Millisecond)
407 c.Assert(len(sr.Items), check.Equals, 1)
408 c.Check(sr.Items[0].Instance, check.Matches, "inst.*")
409 c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
410 c.Check(sr.Items[0].Price, check.Equals, 0.123)
411 c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
412 c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
413 c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)