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}
220 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
221 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
222 stubvm.ExecuteContainer = executeContainer
223 stubvm.CrashRunningContainer = finishContainer
224 stubvm.ExtraCrunchRunArgs = "'--runtime-engine=stub' '--foo' '--extra='\\''args'\\'''"
227 // some instances start out OK but then stop
228 // running any commands
229 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
231 // some instances never pass a run-probe
232 stubvm.CrunchRunMissing = true
234 // some instances start out OK but then start
235 // reporting themselves as broken
236 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
238 // 1 instance is completely broken, ensuring
239 // the boot_outcomes{outcome="failure"} metric
241 stubvm.CrunchRunCrashRate = 1
243 stubvm.CrunchRunCrashRate = 0.1
244 stubvm.ArvMountDeadlockRate = 0.1
248 s.stubDriver.Bugf = c.Errorf
252 err := s.disp.CheckHealth()
253 c.Check(err, check.IsNil)
255 for len(waiting) > 0 {
256 waswaiting := len(waiting)
259 // loop will end because len(waiting)==0
260 case <-time.After(5 * time.Second):
261 if len(waiting) >= waswaiting {
262 c.Fatalf("timed out; no progress in 5 s while waiting for %d containers: %q", len(waiting), waiting)
266 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
268 deadline := time.Now().Add(5 * time.Second)
269 for range time.NewTicker(10 * time.Millisecond).C {
270 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
271 c.Check(err, check.IsNil)
273 ents, _ := queue.Entries()
274 if len(ents) == 0 && len(insts) == 0 {
277 if time.Now().After(deadline) {
278 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
282 c.Check(countCapacityErrors, check.Not(check.Equals), int64(0))
284 req := httptest.NewRequest("GET", "/metrics", nil)
285 req.Header.Set("Authorization", "Bearer "+s.cluster.ManagementToken)
286 resp := httptest.NewRecorder()
287 s.disp.ServeHTTP(resp, req)
288 c.Check(resp.Code, check.Equals, http.StatusOK)
289 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Create"} [^0].*`)
290 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="List"} [^0].*`)
291 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Destroy"} [^0].*`)
292 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="Create"} [^0].*`)
293 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="List"} 0\n.*`)
294 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="aborted"} [0-9]+\n.*`)
295 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="disappeared"} [^0].*`)
296 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="failure"} [^0].*`)
297 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="success"} [^0].*`)
298 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="shutdown"} [^0].*`)
299 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="unknown"} 0\n.*`)
300 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds{quantile="0.95"} [0-9.]*`)
301 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_count [0-9]*`)
302 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_sum [0-9.]*`)
303 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds{quantile="0.95"} [0-9.]*`)
304 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_count [0-9]*`)
305 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_sum [0-9.]*`)
306 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_count [0-9]*`)
307 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_sum [0-9.]*`)
308 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_count [0-9]*`)
309 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_sum [0-9e+.]*`)
310 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="success"} [0-9]*`)
311 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="success"} [0-9e+.]*`)
312 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="fail"} [0-9]*`)
313 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="fail"} [0-9e+.]*`)
314 c.Check(resp.Body.String(), check.Matches, `(?ms).*last_503_time [1-9][0-9e+.]*`)
315 c.Check(resp.Body.String(), check.Matches, `(?ms).*max_concurrent_containers [1-9][0-9e+.]*`)
318 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
319 s.cluster.ManagementToken = "abcdefgh"
320 Drivers["test"] = s.stubDriver
321 s.disp.setupOnce.Do(s.disp.initialize)
322 s.disp.queue = &test.Queue{}
325 for _, token := range []string{"abc", ""} {
326 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
328 req.Header.Set("Authorization", "Bearer "+token)
330 resp := httptest.NewRecorder()
331 s.disp.ServeHTTP(resp, req)
333 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
335 c.Check(resp.Code, check.Equals, http.StatusForbidden)
340 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
341 s.cluster.ManagementToken = ""
342 Drivers["test"] = s.stubDriver
343 s.disp.setupOnce.Do(s.disp.initialize)
344 s.disp.queue = &test.Queue{}
347 for _, token := range []string{"abc", ""} {
348 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
350 req.Header.Set("Authorization", "Bearer "+token)
352 resp := httptest.NewRecorder()
353 s.disp.ServeHTTP(resp, req)
354 c.Check(resp.Code, check.Equals, http.StatusForbidden)
358 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
359 s.cluster.ManagementToken = "abcdefgh"
360 s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
361 Drivers["test"] = s.stubDriver
362 s.disp.setupOnce.Do(s.disp.initialize)
363 s.disp.queue = &test.Queue{}
366 type instance struct {
368 WorkerState string `json:"worker_state"`
370 LastContainerUUID string `json:"last_container_uuid"`
371 ArvadosInstanceType string `json:"arvados_instance_type"`
372 ProviderInstanceType string `json:"provider_instance_type"`
374 type instancesResponse struct {
377 getInstances := func() instancesResponse {
378 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
379 req.Header.Set("Authorization", "Bearer abcdefgh")
380 resp := httptest.NewRecorder()
381 s.disp.ServeHTTP(resp, req)
382 var sr instancesResponse
383 c.Check(resp.Code, check.Equals, http.StatusOK)
384 err := json.Unmarshal(resp.Body.Bytes(), &sr)
385 c.Check(err, check.IsNil)
390 c.Check(len(sr.Items), check.Equals, 0)
392 s.stubDriver.ErrorRateCreate = 0
393 ch := s.disp.pool.Subscribe()
394 defer s.disp.pool.Unsubscribe(ch)
395 ok := s.disp.pool.Create(test.InstanceType(1))
396 c.Check(ok, check.Equals, true)
399 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
401 if len(sr.Items) > 0 {
404 time.Sleep(time.Millisecond)
406 c.Assert(len(sr.Items), check.Equals, 1)
407 c.Check(sr.Items[0].Instance, check.Matches, "inst.*")
408 c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
409 c.Check(sr.Items[0].Price, check.Equals, 0.123)
410 c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
411 c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
412 c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)