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 MaxDispatchAttempts: 10,
73 CloudVMs: arvados.CloudVMsConfig{
75 SyncInterval: arvados.Duration(10 * time.Millisecond),
76 TimeoutIdle: arvados.Duration(150 * time.Millisecond),
77 TimeoutBooting: arvados.Duration(150 * time.Millisecond),
78 TimeoutProbe: arvados.Duration(15 * time.Millisecond),
79 TimeoutShutdown: arvados.Duration(5 * time.Millisecond),
80 MaxCloudOpsPerSecond: 500,
81 PollInterval: arvados.Duration(5 * time.Millisecond),
82 ProbeInterval: arvados.Duration(5 * time.Millisecond),
83 MaxProbesPerSecond: 1000,
84 TimeoutSignal: arvados.Duration(3 * time.Millisecond),
85 TimeoutStaleRunLock: arvados.Duration(3 * time.Millisecond),
86 TimeoutTERM: arvados.Duration(20 * time.Millisecond),
87 ResourceTags: map[string]string{"testtag": "test value"},
88 TagKeyPrefix: "test:",
91 InstanceTypes: arvados.InstanceTypeMap{
92 test.InstanceType(1).Name: test.InstanceType(1),
93 test.InstanceType(2).Name: test.InstanceType(2),
94 test.InstanceType(3).Name: test.InstanceType(3),
95 test.InstanceType(4).Name: test.InstanceType(4),
96 test.InstanceType(6).Name: test.InstanceType(6),
97 test.InstanceType(8).Name: test.InstanceType(8),
98 test.InstanceType(16).Name: test.InstanceType(16),
101 arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
102 arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
104 arvClient, err := arvados.NewClientFromConfig(s.cluster)
105 c.Assert(err, check.IsNil)
106 // Disable auto-retry
107 arvClient.Timeout = 0
109 s.error503Server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
110 c.Logf("503 stub: returning 503")
111 w.WriteHeader(http.StatusServiceUnavailable)
113 arvClient.Client = &http.Client{
114 Transport: &http.Transport{
115 Proxy: s.arvClientProxy(c),
116 TLSClientConfig: &tls.Config{
117 InsecureSkipVerify: true}}}
119 s.disp = &dispatcher{
122 ArvClient: arvClient,
123 AuthToken: arvadostest.AdminToken,
124 Registry: prometheus.NewRegistry(),
126 // Test cases can modify s.cluster before calling
127 // initialize(), and then modify private state before calling
131 func (s *DispatcherSuite) TearDownTest(c *check.C) {
134 s.error503Server.Close()
137 // Intercept outgoing API requests for "/503" and respond HTTP
138 // 503. This lets us force (*arvados.Client)Last503() to return
140 func (s *DispatcherSuite) arvClientProxy(c *check.C) func(*http.Request) (*url.URL, error) {
141 return func(req *http.Request) (*url.URL, error) {
142 if req.URL.Path == "/503" {
143 c.Logf("arvClientProxy: proxying to 503 stub")
144 return url.Parse(s.error503Server.URL)
151 // DispatchToStubDriver checks that the dispatcher wires everything
152 // together effectively. It uses a real scheduler and worker pool with
153 // a fake queue and cloud driver. The fake cloud driver injects
154 // artificial errors in order to exercise a variety of code paths.
155 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
156 Drivers["test"] = s.stubDriver
157 s.disp.setupOnce.Do(s.disp.initialize)
158 queue := &test.Queue{
159 MaxDispatchAttempts: 5,
160 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
161 return ChooseInstanceType(s.cluster, ctr)
163 Logger: ctxlog.TestLogger(c),
165 for i := 0; i < 200; i++ {
166 queue.Containers = append(queue.Containers, arvados.Container{
167 UUID: test.ContainerUUID(i + 1),
168 State: arvados.ContainerStateQueued,
169 Priority: int64(i%20 + 1),
170 RuntimeConstraints: arvados.RuntimeConstraints{
171 RAM: int64(i%3+1) << 30,
179 done := make(chan struct{})
180 waiting := map[string]struct{}{}
181 for _, ctr := range queue.Containers {
182 waiting[ctr.UUID] = struct{}{}
184 finishContainer := func(ctr arvados.Container) {
187 if _, ok := waiting[ctr.UUID]; !ok {
188 c.Errorf("container completed twice: %s", ctr.UUID)
191 delete(waiting, ctr.UUID)
192 if len(waiting) == 100 {
193 // trigger scheduler maxConcurrency limit
194 c.Logf("test: requesting 503 in order to trigger maxConcurrency limit")
195 s.disp.ArvClient.RequestAndDecode(nil, "GET", "503", nil, nil)
197 if len(waiting) == 0 {
201 executeContainer := func(ctr arvados.Container) int {
203 return int(rand.Uint32() & 0x3)
206 s.stubDriver.Queue = queue
207 s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
209 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
210 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
211 stubvm.ExecuteContainer = executeContainer
212 stubvm.CrashRunningContainer = finishContainer
213 stubvm.ExtraCrunchRunArgs = "'--runtime-engine=stub' '--foo' '--extra='\\''args'\\'''"
216 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
218 stubvm.CrunchRunMissing = true
220 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
222 stubvm.CrunchRunCrashRate = 0.1
223 stubvm.ArvMountDeadlockRate = 0.1
226 s.stubDriver.Bugf = c.Errorf
230 err := s.disp.CheckHealth()
231 c.Check(err, check.IsNil)
233 for len(waiting) > 0 {
234 waswaiting := len(waiting)
237 // loop will end because len(waiting)==0
238 case <-time.After(5 * time.Second):
239 if len(waiting) >= waswaiting {
240 c.Fatalf("timed out; no progress in 5 s while waiting for %d containers: %q", len(waiting), waiting)
244 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
246 deadline := time.Now().Add(5 * time.Second)
247 for range time.NewTicker(10 * time.Millisecond).C {
248 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
249 c.Check(err, check.IsNil)
251 ents, _ := queue.Entries()
252 if len(ents) == 0 && len(insts) == 0 {
255 if time.Now().After(deadline) {
256 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
260 req := httptest.NewRequest("GET", "/metrics", nil)
261 req.Header.Set("Authorization", "Bearer "+s.cluster.ManagementToken)
262 resp := httptest.NewRecorder()
263 s.disp.ServeHTTP(resp, req)
264 c.Check(resp.Code, check.Equals, http.StatusOK)
265 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Create"} [^0].*`)
266 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="List"} [^0].*`)
267 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Destroy"} [^0].*`)
268 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="Create"} [^0].*`)
269 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="List"} 0\n.*`)
270 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="aborted"} [0-9]+\n.*`)
271 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="disappeared"} [^0].*`)
272 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="failure"} [^0].*`)
273 c.Check(resp.Body.String(), check.Matches, `(?ms).*boot_outcomes{outcome="success"} [^0].*`)
274 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="shutdown"} [^0].*`)
275 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="unknown"} 0\n.*`)
276 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds{quantile="0.95"} [0-9.]*`)
277 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_count [0-9]*`)
278 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ssh_seconds_sum [0-9.]*`)
279 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds{quantile="0.95"} [0-9.]*`)
280 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_count [0-9]*`)
281 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_to_ready_for_container_seconds_sum [0-9.]*`)
282 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_count [0-9]*`)
283 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_shutdown_request_to_disappearance_seconds_sum [0-9.]*`)
284 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_count [0-9]*`)
285 c.Check(resp.Body.String(), check.Matches, `(?ms).*time_from_queue_to_crunch_run_seconds_sum [0-9e+.]*`)
286 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="success"} [0-9]*`)
287 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="success"} [0-9e+.]*`)
288 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_count{outcome="fail"} [0-9]*`)
289 c.Check(resp.Body.String(), check.Matches, `(?ms).*run_probe_duration_seconds_sum{outcome="fail"} [0-9e+.]*`)
290 c.Check(resp.Body.String(), check.Matches, `(?ms).*last_503_time [1-9][0-9e+.]*`)
291 c.Check(resp.Body.String(), check.Matches, `(?ms).*max_concurrent_containers [1-9][0-9e+.]*`)
294 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
295 s.cluster.ManagementToken = "abcdefgh"
296 Drivers["test"] = s.stubDriver
297 s.disp.setupOnce.Do(s.disp.initialize)
298 s.disp.queue = &test.Queue{}
301 for _, token := range []string{"abc", ""} {
302 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
304 req.Header.Set("Authorization", "Bearer "+token)
306 resp := httptest.NewRecorder()
307 s.disp.ServeHTTP(resp, req)
309 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
311 c.Check(resp.Code, check.Equals, http.StatusForbidden)
316 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
317 s.cluster.ManagementToken = ""
318 Drivers["test"] = s.stubDriver
319 s.disp.setupOnce.Do(s.disp.initialize)
320 s.disp.queue = &test.Queue{}
323 for _, token := range []string{"abc", ""} {
324 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
326 req.Header.Set("Authorization", "Bearer "+token)
328 resp := httptest.NewRecorder()
329 s.disp.ServeHTTP(resp, req)
330 c.Check(resp.Code, check.Equals, http.StatusForbidden)
334 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
335 s.cluster.ManagementToken = "abcdefgh"
336 s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
337 Drivers["test"] = s.stubDriver
338 s.disp.setupOnce.Do(s.disp.initialize)
339 s.disp.queue = &test.Queue{}
342 type instance struct {
344 WorkerState string `json:"worker_state"`
346 LastContainerUUID string `json:"last_container_uuid"`
347 ArvadosInstanceType string `json:"arvados_instance_type"`
348 ProviderInstanceType string `json:"provider_instance_type"`
350 type instancesResponse struct {
353 getInstances := func() instancesResponse {
354 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
355 req.Header.Set("Authorization", "Bearer abcdefgh")
356 resp := httptest.NewRecorder()
357 s.disp.ServeHTTP(resp, req)
358 var sr instancesResponse
359 c.Check(resp.Code, check.Equals, http.StatusOK)
360 err := json.Unmarshal(resp.Body.Bytes(), &sr)
361 c.Check(err, check.IsNil)
366 c.Check(len(sr.Items), check.Equals, 0)
368 ch := s.disp.pool.Subscribe()
369 defer s.disp.pool.Unsubscribe(ch)
370 ok := s.disp.pool.Create(test.InstanceType(1))
371 c.Check(ok, check.Equals, true)
374 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
376 if len(sr.Items) > 0 {
379 time.Sleep(time.Millisecond)
381 c.Assert(len(sr.Items), check.Equals, 1)
382 c.Check(sr.Items[0].Instance, check.Matches, "inst.*")
383 c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
384 c.Check(sr.Items[0].Price, check.Equals, 0.123)
385 c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
386 c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
387 c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)