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"},
71 InstanceTypes: arvados.InstanceTypeMap{
72 test.InstanceType(1).Name: test.InstanceType(1),
73 test.InstanceType(2).Name: test.InstanceType(2),
74 test.InstanceType(3).Name: test.InstanceType(3),
75 test.InstanceType(4).Name: test.InstanceType(4),
76 test.InstanceType(6).Name: test.InstanceType(6),
77 test.InstanceType(8).Name: test.InstanceType(8),
78 test.InstanceType(16).Name: test.InstanceType(16),
81 arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
82 arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
84 arvClient, err := arvados.NewClientFromConfig(s.cluster)
85 c.Check(err, check.IsNil)
91 AuthToken: arvadostest.AdminToken,
93 // Test cases can modify s.cluster before calling
94 // initialize(), and then modify private state before calling
98 func (s *DispatcherSuite) TearDownTest(c *check.C) {
103 // DispatchToStubDriver checks that the dispatcher wires everything
104 // together effectively. It uses a real scheduler and worker pool with
105 // a fake queue and cloud driver. The fake cloud driver injects
106 // artificial errors in order to exercise a variety of code paths.
107 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
108 drivers["test"] = s.stubDriver
109 s.disp.setupOnce.Do(s.disp.initialize)
110 queue := &test.Queue{
111 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
112 return ChooseInstanceType(s.cluster, ctr)
115 for i := 0; i < 200; i++ {
116 queue.Containers = append(queue.Containers, arvados.Container{
117 UUID: test.ContainerUUID(i + 1),
118 State: arvados.ContainerStateQueued,
119 Priority: int64(i%20 + 1),
120 RuntimeConstraints: arvados.RuntimeConstraints{
121 RAM: int64(i%3+1) << 30,
129 done := make(chan struct{})
130 waiting := map[string]struct{}{}
131 for _, ctr := range queue.Containers {
132 waiting[ctr.UUID] = struct{}{}
134 finishContainer := func(ctr arvados.Container) {
137 if _, ok := waiting[ctr.UUID]; !ok {
138 c.Errorf("container completed twice: %s", ctr.UUID)
141 delete(waiting, ctr.UUID)
142 if len(waiting) == 0 {
146 executeContainer := func(ctr arvados.Container) int {
148 return int(rand.Uint32() & 0x3)
151 s.stubDriver.Queue = queue
152 s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
154 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
155 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
156 stubvm.ExecuteContainer = executeContainer
157 stubvm.CrashRunningContainer = finishContainer
160 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
162 stubvm.CrunchRunMissing = true
164 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
166 stubvm.CrunchRunCrashRate = 0.1
172 err := s.disp.CheckHealth()
173 c.Check(err, check.IsNil)
177 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
178 case <-time.After(10 * time.Second):
179 c.Fatalf("timed out; still waiting for %d containers: %q", len(waiting), waiting)
182 deadline := time.Now().Add(5 * time.Second)
183 for range time.NewTicker(10 * time.Millisecond).C {
184 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
185 c.Check(err, check.IsNil)
187 ents, _ := queue.Entries()
188 if len(ents) == 0 && len(insts) == 0 {
191 if time.Now().After(deadline) {
192 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
197 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
198 s.cluster.ManagementToken = "abcdefgh"
199 drivers["test"] = s.stubDriver
200 s.disp.setupOnce.Do(s.disp.initialize)
201 s.disp.queue = &test.Queue{}
204 for _, token := range []string{"abc", ""} {
205 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
207 req.Header.Set("Authorization", "Bearer "+token)
209 resp := httptest.NewRecorder()
210 s.disp.ServeHTTP(resp, req)
212 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
214 c.Check(resp.Code, check.Equals, http.StatusForbidden)
219 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
220 s.cluster.ManagementToken = ""
221 drivers["test"] = s.stubDriver
222 s.disp.setupOnce.Do(s.disp.initialize)
223 s.disp.queue = &test.Queue{}
226 for _, token := range []string{"abc", ""} {
227 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
229 req.Header.Set("Authorization", "Bearer "+token)
231 resp := httptest.NewRecorder()
232 s.disp.ServeHTTP(resp, req)
233 c.Check(resp.Code, check.Equals, http.StatusForbidden)
237 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
238 s.cluster.ManagementToken = "abcdefgh"
239 s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
240 drivers["test"] = s.stubDriver
241 s.disp.setupOnce.Do(s.disp.initialize)
242 s.disp.queue = &test.Queue{}
245 type instance struct {
247 WorkerState string `json:"worker_state"`
249 LastContainerUUID string `json:"last_container_uuid"`
250 ArvadosInstanceType string `json:"arvados_instance_type"`
251 ProviderInstanceType string `json:"provider_instance_type"`
253 type instancesResponse struct {
256 getInstances := func() instancesResponse {
257 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
258 req.Header.Set("Authorization", "Bearer abcdefgh")
259 resp := httptest.NewRecorder()
260 s.disp.ServeHTTP(resp, req)
261 var sr instancesResponse
262 c.Check(resp.Code, check.Equals, http.StatusOK)
263 err := json.Unmarshal(resp.Body.Bytes(), &sr)
264 c.Check(err, check.IsNil)
269 c.Check(len(sr.Items), check.Equals, 0)
271 ch := s.disp.pool.Subscribe()
272 defer s.disp.pool.Unsubscribe(ch)
273 ok := s.disp.pool.Create(test.InstanceType(1))
274 c.Check(ok, check.Equals, true)
277 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
279 if len(sr.Items) > 0 {
282 time.Sleep(time.Millisecond)
284 c.Assert(len(sr.Items), check.Equals, 1)
285 c.Check(sr.Items[0].Instance, check.Matches, "stub.*")
286 c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
287 c.Check(sr.Items[0].Price, check.Equals, 0.123)
288 c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
289 c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
290 c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)