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 CloudVMs: arvados.CloudVMs{
54 SyncInterval: arvados.Duration(10 * time.Millisecond),
55 TimeoutIdle: arvados.Duration(150 * time.Millisecond),
56 TimeoutBooting: arvados.Duration(150 * time.Millisecond),
57 TimeoutProbe: arvados.Duration(15 * time.Millisecond),
58 TimeoutShutdown: arvados.Duration(5 * time.Millisecond),
59 MaxCloudOpsPerSecond: 500,
61 Dispatch: arvados.Dispatch{
62 PrivateKey: string(dispatchprivraw),
63 PollInterval: arvados.Duration(5 * time.Millisecond),
64 ProbeInterval: arvados.Duration(5 * time.Millisecond),
65 StaleLockTimeout: arvados.Duration(5 * time.Millisecond),
66 MaxProbesPerSecond: 1000,
67 TimeoutSignal: arvados.Duration(3 * time.Millisecond),
68 TimeoutTERM: arvados.Duration(20 * time.Millisecond),
70 InstanceTypes: arvados.InstanceTypeMap{
71 test.InstanceType(1).Name: test.InstanceType(1),
72 test.InstanceType(2).Name: test.InstanceType(2),
73 test.InstanceType(3).Name: test.InstanceType(3),
74 test.InstanceType(4).Name: test.InstanceType(4),
75 test.InstanceType(6).Name: test.InstanceType(6),
76 test.InstanceType(8).Name: test.InstanceType(8),
77 test.InstanceType(16).Name: test.InstanceType(16),
79 NodeProfiles: map[string]arvados.NodeProfile{
81 Controller: arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_API_HOST")},
82 DispatchCloud: arvados.SystemServiceInstance{Listen: ":"},
85 Services: arvados.Services{
86 Controller: arvados.Service{ExternalURL: arvados.URL{Scheme: "https", Host: os.Getenv("ARVADOS_API_HOST")}},
90 arvClient, err := arvados.NewClientFromConfig(s.cluster)
91 c.Check(err, check.IsNil)
97 AuthToken: arvadostest.AdminToken,
99 // Test cases can modify s.cluster before calling
100 // initialize(), and then modify private state before calling
104 func (s *DispatcherSuite) TearDownTest(c *check.C) {
109 // DispatchToStubDriver checks that the dispatcher wires everything
110 // together effectively. It uses a real scheduler and worker pool with
111 // a fake queue and cloud driver. The fake cloud driver injects
112 // artificial errors in order to exercise a variety of code paths.
113 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
114 drivers["test"] = s.stubDriver
115 s.disp.setupOnce.Do(s.disp.initialize)
116 queue := &test.Queue{
117 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
118 return ChooseInstanceType(s.cluster, ctr)
121 for i := 0; i < 200; i++ {
122 queue.Containers = append(queue.Containers, arvados.Container{
123 UUID: test.ContainerUUID(i + 1),
124 State: arvados.ContainerStateQueued,
125 Priority: int64(i%20 + 1),
126 RuntimeConstraints: arvados.RuntimeConstraints{
127 RAM: int64(i%3+1) << 30,
135 done := make(chan struct{})
136 waiting := map[string]struct{}{}
137 for _, ctr := range queue.Containers {
138 waiting[ctr.UUID] = struct{}{}
140 finishContainer := func(ctr arvados.Container) {
143 if _, ok := waiting[ctr.UUID]; !ok {
144 c.Errorf("container completed twice: %s", ctr.UUID)
147 delete(waiting, ctr.UUID)
148 if len(waiting) == 0 {
152 executeContainer := func(ctr arvados.Container) int {
154 return int(rand.Uint32() & 0x3)
157 s.stubDriver.Queue = queue
158 s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
160 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
161 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
162 stubvm.ExecuteContainer = executeContainer
163 stubvm.CrashRunningContainer = finishContainer
166 stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
168 stubvm.CrunchRunMissing = true
170 stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
172 stubvm.CrunchRunCrashRate = 0.1
178 err := s.disp.CheckHealth()
179 c.Check(err, check.IsNil)
183 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
184 case <-time.After(10 * time.Second):
185 c.Fatalf("timed out; still waiting for %d containers: %q", len(waiting), waiting)
188 deadline := time.Now().Add(5 * time.Second)
189 for range time.NewTicker(10 * time.Millisecond).C {
190 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
191 c.Check(err, check.IsNil)
193 ents, _ := queue.Entries()
194 if len(ents) == 0 && len(insts) == 0 {
197 if time.Now().After(deadline) {
198 c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
203 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
204 s.cluster.ManagementToken = "abcdefgh"
205 drivers["test"] = s.stubDriver
206 s.disp.setupOnce.Do(s.disp.initialize)
207 s.disp.queue = &test.Queue{}
210 for _, token := range []string{"abc", ""} {
211 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
213 req.Header.Set("Authorization", "Bearer "+token)
215 resp := httptest.NewRecorder()
216 s.disp.ServeHTTP(resp, req)
218 c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
220 c.Check(resp.Code, check.Equals, http.StatusForbidden)
225 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
226 s.cluster.ManagementToken = ""
227 drivers["test"] = s.stubDriver
228 s.disp.setupOnce.Do(s.disp.initialize)
229 s.disp.queue = &test.Queue{}
232 for _, token := range []string{"abc", ""} {
233 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
235 req.Header.Set("Authorization", "Bearer "+token)
237 resp := httptest.NewRecorder()
238 s.disp.ServeHTTP(resp, req)
239 c.Check(resp.Code, check.Equals, http.StatusForbidden)
243 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
244 s.cluster.ManagementToken = "abcdefgh"
245 s.cluster.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
246 drivers["test"] = s.stubDriver
247 s.disp.setupOnce.Do(s.disp.initialize)
248 s.disp.queue = &test.Queue{}
251 type instance struct {
253 WorkerState string `json:"worker_state"`
255 LastContainerUUID string `json:"last_container_uuid"`
256 ArvadosInstanceType string `json:"arvados_instance_type"`
257 ProviderInstanceType string `json:"provider_instance_type"`
259 type instancesResponse struct {
262 getInstances := func() instancesResponse {
263 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
264 req.Header.Set("Authorization", "Bearer abcdefgh")
265 resp := httptest.NewRecorder()
266 s.disp.ServeHTTP(resp, req)
267 var sr instancesResponse
268 c.Check(resp.Code, check.Equals, http.StatusOK)
269 err := json.Unmarshal(resp.Body.Bytes(), &sr)
270 c.Check(err, check.IsNil)
275 c.Check(len(sr.Items), check.Equals, 0)
277 ch := s.disp.pool.Subscribe()
278 defer s.disp.pool.Unsubscribe(ch)
279 ok := s.disp.pool.Create(test.InstanceType(1))
280 c.Check(ok, check.Equals, true)
283 for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
285 if len(sr.Items) > 0 {
288 time.Sleep(time.Millisecond)
290 c.Assert(len(sr.Items), check.Equals, 1)
291 c.Check(sr.Items[0].Instance, check.Matches, "stub.*")
292 c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
293 c.Check(sr.Items[0].Price, check.Equals, 0.123)
294 c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
295 c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
296 c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)