1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.curoverse.com/arvados.git/lib/dispatchcloud/test"
19 "git.curoverse.com/arvados.git/sdk/go/arvados"
20 "git.curoverse.com/arvados.git/sdk/go/arvadostest"
21 "git.curoverse.com/arvados.git/sdk/go/ctxlog"
22 "golang.org/x/crypto/ssh"
23 check "gopkg.in/check.v1"
26 var _ = check.Suite(&DispatcherSuite{})
28 type DispatcherSuite struct {
30 cancel context.CancelFunc
31 cluster *arvados.Cluster
32 stubDriver *test.StubDriver
36 func (s *DispatcherSuite) SetUpTest(c *check.C) {
37 s.ctx, s.cancel = context.WithCancel(context.Background())
38 s.ctx = ctxlog.Context(s.ctx, ctxlog.TestLogger(c))
39 dispatchpub, _ := test.LoadTestKey(c, "test/sshkey_dispatch")
40 dispatchprivraw, err := ioutil.ReadFile("test/sshkey_dispatch")
41 c.Assert(err, check.IsNil)
43 _, hostpriv := test.LoadTestKey(c, "test/sshkey_vm")
44 s.stubDriver = &test.StubDriver{
46 AuthorizedKeys: []ssh.PublicKey{dispatchpub},
47 ErrorRateDestroy: 0.1,
48 MinTimeBetweenCreateCalls: time.Millisecond,
51 s.cluster = &arvados.Cluster{
52 Containers: arvados.ContainersConfig{
53 DispatchPrivateKey: string(dispatchprivraw),
54 StaleLockTimeout: arvados.Duration(5 * time.Millisecond),
55 CloudVMs: arvados.CloudVMsConfig{
57 SyncInterval: arvados.Duration(10 * time.Millisecond),
58 TimeoutIdle: arvados.Duration(150 * time.Millisecond),
59 TimeoutBooting: arvados.Duration(150 * time.Millisecond),
60 TimeoutProbe: arvados.Duration(15 * time.Millisecond),
61 TimeoutShutdown: arvados.Duration(5 * time.Millisecond),
62 MaxCloudOpsPerSecond: 500,
63 PollInterval: arvados.Duration(5 * time.Millisecond),
64 ProbeInterval: arvados.Duration(5 * time.Millisecond),
65 MaxProbesPerSecond: 1000,
66 TimeoutSignal: arvados.Duration(3 * time.Millisecond),
67 TimeoutTERM: arvados.Duration(20 * time.Millisecond),
68 ResourceTags: map[string]string{"testtag": "test value"},
69 TagKeyPrefix: "test:",
72 InstanceTypes: arvados.InstanceTypeMap{
73 test.InstanceType(1).Name: test.InstanceType(1),
74 test.InstanceType(2).Name: test.InstanceType(2),
75 test.InstanceType(3).Name: test.InstanceType(3),
76 test.InstanceType(4).Name: test.InstanceType(4),
77 test.InstanceType(6).Name: test.InstanceType(6),
78 test.InstanceType(8).Name: test.InstanceType(8),
79 test.InstanceType(16).Name: test.InstanceType(16),
82 arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
83 arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
85 arvClient, err := arvados.NewClientFromConfig(s.cluster)
86 c.Check(err, check.IsNil)
92 AuthToken: arvadostest.AdminToken,
94 // Test cases can modify s.cluster before calling
95 // initialize(), and then modify private state before calling
99 func (s *DispatcherSuite) TearDownTest(c *check.C) {
104 // DispatchToStubDriver checks that the dispatcher wires everything
105 // together effectively. It uses a real scheduler and worker pool with
106 // a fake queue and cloud driver. The fake cloud driver injects
107 // artificial errors in order to exercise a variety of code paths.
108 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
109 drivers["test"] = s.stubDriver
110 s.disp.setupOnce.Do(s.disp.initialize)
111 queue := &test.Queue{
112 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
113 return ChooseInstanceType(s.cluster, ctr)
116 for i := 0; i < 200; i++ {
117 queue.Containers = append(queue.Containers, arvados.Container{
118 UUID: test.ContainerUUID(i + 1),
119 State: arvados.ContainerStateQueued,
120 Priority: int64(i%20 + 1),
121 RuntimeConstraints: arvados.RuntimeConstraints{
122 RAM: int64(i%3+1) << 30,
130 done := make(chan struct{})
131 waiting := map[string]struct{}{}
132 for _, ctr := range queue.Containers {
133 waiting[ctr.UUID] = struct{}{}
135 finishContainer := func(ctr arvados.Container) {
138 if _, ok := waiting[ctr.UUID]; !ok {
139 c.Errorf("container completed twice: %s", ctr.UUID)
142 delete(waiting, ctr.UUID)
143 if len(waiting) == 0 {
147 executeContainer := func(ctr arvados.Container) int {
149 return int(rand.Uint32() & 0x3)
152 s.stubDriver.Queue = queue
153 s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
155 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
156 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
157 stubvm.ExecuteContainer = executeContainer
158 stubvm.CrashRunningContainer = finishContainer
161 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
163 stubvm.CrunchRunMissing = true
165 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
167 stubvm.CrunchRunCrashRate = 0.1
173 err := s.disp.CheckHealth()
174 c.Check(err, check.IsNil)
178 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
179 case <-time.After(10 * time.Second):
180 c.Fatalf("timed out; still waiting for %d containers: %q", len(waiting), waiting)
183 deadline := time.Now().Add(5 * time.Second)
184 for range time.NewTicker(10 * time.Millisecond).C {
185 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
186 c.Check(err, check.IsNil)
188 ents, _ := queue.Entries()
189 if len(ents) == 0 && len(insts) == 0 {
192 if time.Now().After(deadline) {
193 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
198 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
199 s.cluster.ManagementToken = "abcdefgh"
200 drivers["test"] = s.stubDriver
201 s.disp.setupOnce.Do(s.disp.initialize)
202 s.disp.queue = &test.Queue{}
205 for _, token := range []string{"abc", ""} {
206 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
208 req.Header.Set("Authorization", "Bearer "+token)
210 resp := httptest.NewRecorder()
211 s.disp.ServeHTTP(resp, req)
213 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
215 c.Check(resp.Code, check.Equals, http.StatusForbidden)
220 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
221 s.cluster.ManagementToken = ""
222 drivers["test"] = s.stubDriver
223 s.disp.setupOnce.Do(s.disp.initialize)
224 s.disp.queue = &test.Queue{}
227 for _, token := range []string{"abc", ""} {
228 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
230 req.Header.Set("Authorization", "Bearer "+token)
232 resp := httptest.NewRecorder()
233 s.disp.ServeHTTP(resp, req)
234 c.Check(resp.Code, check.Equals, http.StatusForbidden)
238 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
239 s.cluster.ManagementToken = "abcdefgh"
240 s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
241 drivers["test"] = s.stubDriver
242 s.disp.setupOnce.Do(s.disp.initialize)
243 s.disp.queue = &test.Queue{}
246 type instance struct {
248 WorkerState string `json:"worker_state"`
250 LastContainerUUID string `json:"last_container_uuid"`
251 ArvadosInstanceType string `json:"arvados_instance_type"`
252 ProviderInstanceType string `json:"provider_instance_type"`
254 type instancesResponse struct {
257 getInstances := func() instancesResponse {
258 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
259 req.Header.Set("Authorization", "Bearer abcdefgh")
260 resp := httptest.NewRecorder()
261 s.disp.ServeHTTP(resp, req)
262 var sr instancesResponse
263 c.Check(resp.Code, check.Equals, http.StatusOK)
264 err := json.Unmarshal(resp.Body.Bytes(), &sr)
265 c.Check(err, check.IsNil)
270 c.Check(len(sr.Items), check.Equals, 0)
272 ch := s.disp.pool.Subscribe()
273 defer s.disp.pool.Unsubscribe(ch)
274 ok := s.disp.pool.Create(test.InstanceType(1))
275 c.Check(ok, check.Equals, true)
278 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
280 if len(sr.Items) > 0 {
283 time.Sleep(time.Millisecond)
285 c.Assert(len(sr.Items), check.Equals, 1)
286 c.Check(sr.Items[0].Instance, check.Matches, "stub.*")
287 c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
288 c.Check(sr.Items[0].Price, check.Equals, 0.123)
289 c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
290 c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
291 c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)