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 DispatchPrivateKey: string(dispatchprivraw),
56 StaleLockTimeout: arvados.Duration(5 * time.Millisecond),
57 CloudVMs: arvados.CloudVMsConfig{
59 SyncInterval: arvados.Duration(10 * time.Millisecond),
60 TimeoutIdle: arvados.Duration(150 * time.Millisecond),
61 TimeoutBooting: arvados.Duration(150 * time.Millisecond),
62 TimeoutProbe: arvados.Duration(15 * time.Millisecond),
63 TimeoutShutdown: arvados.Duration(5 * time.Millisecond),
64 MaxCloudOpsPerSecond: 500,
65 PollInterval: arvados.Duration(5 * time.Millisecond),
66 ProbeInterval: arvados.Duration(5 * time.Millisecond),
67 MaxProbesPerSecond: 1000,
68 TimeoutSignal: arvados.Duration(3 * time.Millisecond),
69 TimeoutTERM: arvados.Duration(20 * time.Millisecond),
70 ResourceTags: map[string]string{"testtag": "test value"},
71 TagKeyPrefix: "test:",
74 InstanceTypes: arvados.InstanceTypeMap{
75 test.InstanceType(1).Name: test.InstanceType(1),
76 test.InstanceType(2).Name: test.InstanceType(2),
77 test.InstanceType(3).Name: test.InstanceType(3),
78 test.InstanceType(4).Name: test.InstanceType(4),
79 test.InstanceType(6).Name: test.InstanceType(6),
80 test.InstanceType(8).Name: test.InstanceType(8),
81 test.InstanceType(16).Name: test.InstanceType(16),
84 arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
85 arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
87 arvClient, err := arvados.NewClientFromConfig(s.cluster)
88 c.Check(err, check.IsNil)
94 AuthToken: arvadostest.AdminToken,
95 Registry: prometheus.NewRegistry(),
97 // Test cases can modify s.cluster before calling
98 // initialize(), and then modify private state before calling
102 func (s *DispatcherSuite) TearDownTest(c *check.C) {
107 // DispatchToStubDriver checks that the dispatcher wires everything
108 // together effectively. It uses a real scheduler and worker pool with
109 // a fake queue and cloud driver. The fake cloud driver injects
110 // artificial errors in order to exercise a variety of code paths.
111 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
112 Drivers["test"] = s.stubDriver
113 s.disp.setupOnce.Do(s.disp.initialize)
114 queue := &test.Queue{
115 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
116 return ChooseInstanceType(s.cluster, ctr)
119 for i := 0; i < 200; i++ {
120 queue.Containers = append(queue.Containers, arvados.Container{
121 UUID: test.ContainerUUID(i + 1),
122 State: arvados.ContainerStateQueued,
123 Priority: int64(i%20 + 1),
124 RuntimeConstraints: arvados.RuntimeConstraints{
125 RAM: int64(i%3+1) << 30,
133 done := make(chan struct{})
134 waiting := map[string]struct{}{}
135 for _, ctr := range queue.Containers {
136 waiting[ctr.UUID] = struct{}{}
138 finishContainer := func(ctr arvados.Container) {
141 if _, ok := waiting[ctr.UUID]; !ok {
142 c.Errorf("container completed twice: %s", ctr.UUID)
145 delete(waiting, ctr.UUID)
146 if len(waiting) == 0 {
150 executeContainer := func(ctr arvados.Container) int {
152 return int(rand.Uint32() & 0x3)
155 s.stubDriver.Queue = queue
156 s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
158 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
159 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
160 stubvm.ExecuteContainer = executeContainer
161 stubvm.CrashRunningContainer = finishContainer
164 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
166 stubvm.CrunchRunMissing = true
168 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
170 stubvm.CrunchRunCrashRate = 0.1
176 err := s.disp.CheckHealth()
177 c.Check(err, check.IsNil)
181 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
182 case <-time.After(10 * time.Second):
183 c.Fatalf("timed out; still waiting for %d containers: %q", len(waiting), waiting)
186 deadline := time.Now().Add(5 * time.Second)
187 for range time.NewTicker(10 * time.Millisecond).C {
188 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
189 c.Check(err, check.IsNil)
191 ents, _ := queue.Entries()
192 if len(ents) == 0 && len(insts) == 0 {
195 if time.Now().After(deadline) {
196 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
200 req := httptest.NewRequest("GET", "/metrics", nil)
201 req.Header.Set("Authorization", "Bearer "+s.cluster.ManagementToken)
202 resp := httptest.NewRecorder()
203 s.disp.ServeHTTP(resp, req)
204 c.Check(resp.Code, check.Equals, http.StatusOK)
205 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Create"} [^0].*`)
206 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="List"} [^0].*`)
207 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="0",operation="Destroy"} [^0].*`)
208 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="Create"} [^0].*`)
209 c.Check(resp.Body.String(), check.Matches, `(?ms).*driver_operations{error="1",operation="List"} 0\n.*`)
210 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="shutdown"} [^0].*`)
211 c.Check(resp.Body.String(), check.Matches, `(?ms).*instances_disappeared{state="unknown"} 0\n.*`)
214 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
215 s.cluster.ManagementToken = "abcdefgh"
216 Drivers["test"] = s.stubDriver
217 s.disp.setupOnce.Do(s.disp.initialize)
218 s.disp.queue = &test.Queue{}
221 for _, token := range []string{"abc", ""} {
222 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
224 req.Header.Set("Authorization", "Bearer "+token)
226 resp := httptest.NewRecorder()
227 s.disp.ServeHTTP(resp, req)
229 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
231 c.Check(resp.Code, check.Equals, http.StatusForbidden)
236 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
237 s.cluster.ManagementToken = ""
238 Drivers["test"] = s.stubDriver
239 s.disp.setupOnce.Do(s.disp.initialize)
240 s.disp.queue = &test.Queue{}
243 for _, token := range []string{"abc", ""} {
244 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
246 req.Header.Set("Authorization", "Bearer "+token)
248 resp := httptest.NewRecorder()
249 s.disp.ServeHTTP(resp, req)
250 c.Check(resp.Code, check.Equals, http.StatusForbidden)
254 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
255 s.cluster.ManagementToken = "abcdefgh"
256 s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
257 Drivers["test"] = s.stubDriver
258 s.disp.setupOnce.Do(s.disp.initialize)
259 s.disp.queue = &test.Queue{}
262 type instance struct {
264 WorkerState string `json:"worker_state"`
266 LastContainerUUID string `json:"last_container_uuid"`
267 ArvadosInstanceType string `json:"arvados_instance_type"`
268 ProviderInstanceType string `json:"provider_instance_type"`
270 type instancesResponse struct {
273 getInstances := func() instancesResponse {
274 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
275 req.Header.Set("Authorization", "Bearer abcdefgh")
276 resp := httptest.NewRecorder()
277 s.disp.ServeHTTP(resp, req)
278 var sr instancesResponse
279 c.Check(resp.Code, check.Equals, http.StatusOK)
280 err := json.Unmarshal(resp.Body.Bytes(), &sr)
281 c.Check(err, check.IsNil)
286 c.Check(len(sr.Items), check.Equals, 0)
288 ch := s.disp.pool.Subscribe()
289 defer s.disp.pool.Unsubscribe(ch)
290 ok := s.disp.pool.Create(test.InstanceType(1))
291 c.Check(ok, check.Equals, true)
294 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
296 if len(sr.Items) > 0 {
299 time.Sleep(time.Millisecond)
301 c.Assert(len(sr.Items), check.Equals, 1)
302 c.Check(sr.Items[0].Instance, check.Matches, "stub.*")
303 c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
304 c.Check(sr.Items[0].Price, check.Equals, 0.123)
305 c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
306 c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
307 c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)