1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/lib/config"
21 "git.arvados.org/arvados.git/lib/dispatchcloud/test"
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "git.arvados.org/arvados.git/sdk/go/arvadostest"
24 "git.arvados.org/arvados.git/sdk/go/ctxlog"
25 "github.com/prometheus/client_golang/prometheus"
26 "golang.org/x/crypto/ssh"
27 check "gopkg.in/check.v1"
30 var _ = check.Suite(&DispatcherSuite{})
32 type DispatcherSuite struct {
34 cancel context.CancelFunc
35 cluster *arvados.Cluster
36 stubDriver *test.StubDriver
38 error503Server *httptest.Server
41 func (s *DispatcherSuite) SetUpTest(c *check.C) {
42 s.ctx, s.cancel = context.WithCancel(context.Background())
43 s.ctx = ctxlog.Context(s.ctx, ctxlog.TestLogger(c))
44 dispatchpub, _ := test.LoadTestKey(c, "test/sshkey_dispatch")
45 dispatchprivraw, err := ioutil.ReadFile("test/sshkey_dispatch")
46 c.Assert(err, check.IsNil)
48 _, hostpriv := test.LoadTestKey(c, "test/sshkey_vm")
49 s.stubDriver = &test.StubDriver{
51 AuthorizedKeys: []ssh.PublicKey{dispatchpub},
52 ErrorRateDestroy: 0.1,
53 MinTimeBetweenCreateCalls: time.Millisecond,
56 // We need the postgresql connection info from the integration
58 cfg, err := config.NewLoader(nil, ctxlog.FromContext(s.ctx)).Load()
59 c.Assert(err, check.IsNil)
60 testcluster, err := cfg.GetCluster("")
61 c.Assert(err, check.IsNil)
63 s.cluster = &arvados.Cluster{
64 ManagementToken: "test-management-token",
65 PostgreSQL: testcluster.PostgreSQL,
66 Containers: arvados.ContainersConfig{
67 CrunchRunCommand: "crunch-run",
68 CrunchRunArgumentsList: []string{"--foo", "--extra='args'"},
69 DispatchPrivateKey: string(dispatchprivraw),
70 StaleLockTimeout: arvados.Duration(5 * time.Millisecond),
71 RuntimeEngine: "stub",
72 CloudVMs: arvados.CloudVMsConfig{
74 SyncInterval: arvados.Duration(10 * time.Millisecond),
75 TimeoutIdle: arvados.Duration(150 * time.Millisecond),
76 TimeoutBooting: arvados.Duration(150 * time.Millisecond),
77 TimeoutProbe: arvados.Duration(15 * time.Millisecond),
78 TimeoutShutdown: arvados.Duration(5 * time.Millisecond),
79 MaxCloudOpsPerSecond: 500,
80 PollInterval: arvados.Duration(5 * time.Millisecond),
81 ProbeInterval: arvados.Duration(5 * time.Millisecond),
82 MaxProbesPerSecond: 1000,
83 TimeoutSignal: arvados.Duration(3 * time.Millisecond),
84 TimeoutStaleRunLock: arvados.Duration(3 * time.Millisecond),
85 TimeoutTERM: arvados.Duration(20 * time.Millisecond),
86 ResourceTags: map[string]string{"testtag": "test value"},
87 TagKeyPrefix: "test:",
90 InstanceTypes: arvados.InstanceTypeMap{
91 test.InstanceType(1).Name: test.InstanceType(1),
92 test.InstanceType(2).Name: test.InstanceType(2),
93 test.InstanceType(3).Name: test.InstanceType(3),
94 test.InstanceType(4).Name: test.InstanceType(4),
95 test.InstanceType(6).Name: test.InstanceType(6),
96 test.InstanceType(8).Name: test.InstanceType(8),
97 test.InstanceType(16).Name: test.InstanceType(16),
100 arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
101 arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
103 arvClient, err := arvados.NewClientFromConfig(s.cluster)
104 c.Assert(err, check.IsNil)
105 // Disable auto-retry
106 arvClient.Timeout = 0
108 s.error503Server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusServiceUnavailable) }))
109 arvClient.Client = &http.Client{
110 Transport: &http.Transport{
111 Proxy: s.arvClientProxy(c),
112 TLSClientConfig: &tls.Config{
113 InsecureSkipVerify: true}}}
115 s.disp = &dispatcher{
118 ArvClient: arvClient,
119 AuthToken: arvadostest.AdminToken,
120 Registry: prometheus.NewRegistry(),
122 // Test cases can modify s.cluster before calling
123 // initialize(), and then modify private state before calling
127 func (s *DispatcherSuite) TearDownTest(c *check.C) {
130 s.error503Server.Close()
133 // Intercept outgoing API requests for "/503" and respond HTTP
134 // 503. This lets us force (*arvados.Client)Last503() to return
136 func (s *DispatcherSuite) arvClientProxy(c *check.C) func(*http.Request) (*url.URL, error) {
137 return func(req *http.Request) (*url.URL, error) {
138 if req.URL.Path == "/503" {
139 return url.Parse(s.error503Server.URL)
146 // DispatchToStubDriver checks that the dispatcher wires everything
147 // together effectively. It uses a real scheduler and worker pool with
148 // a fake queue and cloud driver. The fake cloud driver injects
149 // artificial errors in order to exercise a variety of code paths.
150 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
151 Drivers["test"] = s.stubDriver
152 s.disp.setupOnce.Do(s.disp.initialize)
153 queue := &test.Queue{
154 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
155 return ChooseInstanceType(s.cluster, ctr)
157 Logger: ctxlog.TestLogger(c),
159 for i := 0; i < 200; i++ {
160 queue.Containers = append(queue.Containers, arvados.Container{
161 UUID: test.ContainerUUID(i + 1),
162 State: arvados.ContainerStateQueued,
163 Priority: int64(i%20 + 1),
164 RuntimeConstraints: arvados.RuntimeConstraints{
165 RAM: int64(i%3+1) << 30,
173 done := make(chan struct{})
174 waiting := map[string]struct{}{}
175 for _, ctr := range queue.Containers {
176 waiting[ctr.UUID] = struct{}{}
178 finishContainer := func(ctr arvados.Container) {
181 if _, ok := waiting[ctr.UUID]; !ok {
182 c.Errorf("container completed twice: %s", ctr.UUID)
185 delete(waiting, ctr.UUID)
186 if len(waiting) == 100 {
187 // trigger scheduler maxConcurrency limit
188 s.disp.ArvClient.RequestAndDecode(nil, "GET", "503", nil, nil)
190 if len(waiting) == 0 {
194 executeContainer := func(ctr arvados.Container) int {
196 return int(rand.Uint32() & 0x3)
199 s.stubDriver.Queue = queue
200 s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
202 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
203 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
204 stubvm.ExecuteContainer = executeContainer
205 stubvm.CrashRunningContainer = finishContainer
206 stubvm.ExtraCrunchRunArgs = "'--runtime-engine=stub' '--foo' '--extra='\\''args'\\'''"
209 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
211 stubvm.CrunchRunMissing = true
213 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
215 stubvm.CrunchRunCrashRate = 0.1
216 stubvm.ArvMountDeadlockRate = 0.1
219 s.stubDriver.Bugf = c.Errorf
223 err := s.disp.CheckHealth()
224 c.Check(err, check.IsNil)
226 for len(waiting) > 0 {
227 waswaiting := len(waiting)
230 // loop will end because len(waiting)==0
231 case <-time.After(3 * time.Second):
232 if len(waiting) >= waswaiting {
233 c.Fatalf("timed out; no progress in 3s while waiting for %d containers: %q", len(waiting), waiting)
237 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
239 deadline := time.Now().Add(5 * time.Second)
240 for range time.NewTicker(10 * time.Millisecond).C {
241 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
242 c.Check(err, check.IsNil)
244 ents, _ := queue.Entries()
245 if len(ents) == 0 && len(insts) == 0 {
248 if time.Now().After(deadline) {
249 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
253 req := httptest.NewRequest("GET", "/metrics", nil)
254 req.Header.Set("Authorization", "Bearer "+s.cluster.ManagementToken)
255 resp := httptest.NewRecorder()
256 s.disp.ServeHTTP(resp, req)
257 c.Check(resp.Code, check.Equals, http.StatusOK)
258 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Create"} [^0].*`)
259 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="List"} [^0].*`)
260 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Destroy"} [^0].*`)
261 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="Create"} [^0].*`)
262 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="List"} 0\n.*`)
263 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="aborted"} [0-9]+\n.*`)
264 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="disappeared"} [^0].*`)
265 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="failure"} [^0].*`)
266 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="success"} [^0].*`)
267 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="shutdown"} [^0].*`)
268 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="unknown"} 0\n.*`)
269 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds{quantile="0.95"} [0-9.]*`)
270 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_count [0-9]*`)
271 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_sum [0-9.]*`)
272 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds{quantile="0.95"} [0-9.]*`)
273 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_count [0-9]*`)
274 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_sum [0-9.]*`)
275 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_count [0-9]*`)
276 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_sum [0-9.]*`)
277 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_count [0-9]*`)
278 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_sum [0-9e+.]*`)
279 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="success"} [0-9]*`)
280 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="success"} [0-9e+.]*`)
281 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="fail"} [0-9]*`)
282 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="fail"} [0-9e+.]*`)
283 c.Check(resp.Body.String(), check.Matches, `(?ms).*last_503_time [1-9][0-9e+.]*`)
284 c.Check(resp.Body.String(), check.Matches, `(?ms).*max_concurrent_containers [1-9][0-9e+.]*`)
287 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
288 s.cluster.ManagementToken = "abcdefgh"
289 Drivers["test"] = s.stubDriver
290 s.disp.setupOnce.Do(s.disp.initialize)
291 s.disp.queue = &test.Queue{}
294 for _, token := range []string{"abc", ""} {
295 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
297 req.Header.Set("Authorization", "Bearer "+token)
299 resp := httptest.NewRecorder()
300 s.disp.ServeHTTP(resp, req)
302 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
304 c.Check(resp.Code, check.Equals, http.StatusForbidden)
309 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
310 s.cluster.ManagementToken = ""
311 Drivers["test"] = s.stubDriver
312 s.disp.setupOnce.Do(s.disp.initialize)
313 s.disp.queue = &test.Queue{}
316 for _, token := range []string{"abc", ""} {
317 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
319 req.Header.Set("Authorization", "Bearer "+token)
321 resp := httptest.NewRecorder()
322 s.disp.ServeHTTP(resp, req)
323 c.Check(resp.Code, check.Equals, http.StatusForbidden)
327 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
328 s.cluster.ManagementToken = "abcdefgh"
329 s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
330 Drivers["test"] = s.stubDriver
331 s.disp.setupOnce.Do(s.disp.initialize)
332 s.disp.queue = &test.Queue{}
335 type instance struct {
337 WorkerState string `json:"worker_state"`
339 LastContainerUUID string `json:"last_container_uuid"`
340 ArvadosInstanceType string `json:"arvados_instance_type"`
341 ProviderInstanceType string `json:"provider_instance_type"`
343 type instancesResponse struct {
346 getInstances := func() instancesResponse {
347 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
348 req.Header.Set("Authorization", "Bearer abcdefgh")
349 resp := httptest.NewRecorder()
350 s.disp.ServeHTTP(resp, req)
351 var sr instancesResponse
352 c.Check(resp.Code, check.Equals, http.StatusOK)
353 err := json.Unmarshal(resp.Body.Bytes(), &sr)
354 c.Check(err, check.IsNil)
359 c.Check(len(sr.Items), check.Equals, 0)
361 ch := s.disp.pool.Subscribe()
362 defer s.disp.pool.Unsubscribe(ch)
363 ok := s.disp.pool.Create(test.InstanceType(1))
364 c.Check(ok, check.Equals, true)
367 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
369 if len(sr.Items) > 0 {
372 time.Sleep(time.Millisecond)
374 c.Assert(len(sr.Items), check.Equals, 1)
375 c.Check(sr.Items[0].Instance, check.Matches, "inst.*")
376 c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
377 c.Check(sr.Items[0].Price, check.Equals, 0.123)
378 c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
379 c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
380 c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)