15003: Update dispatchcloud to new config struct.
[arvados.git] / lib / dispatchcloud / dispatcher_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package dispatchcloud
6
7 import (
8         "context"
9         "encoding/json"
10         "io/ioutil"
11         "math/rand"
12         "net/http"
13         "net/http/httptest"
14         "os"
15         "sync"
16         "time"
17
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"
24 )
25
26 var _ = check.Suite(&DispatcherSuite{})
27
28 type DispatcherSuite struct {
29         ctx        context.Context
30         cancel     context.CancelFunc
31         cluster    *arvados.Cluster
32         stubDriver *test.StubDriver
33         disp       *dispatcher
34 }
35
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)
42
43         _, hostpriv := test.LoadTestKey(c, "test/sshkey_vm")
44         s.stubDriver = &test.StubDriver{
45                 HostKey:                   hostpriv,
46                 AuthorizedKeys:            []ssh.PublicKey{dispatchpub},
47                 ErrorRateDestroy:          0.1,
48                 MinTimeBetweenCreateCalls: time.Millisecond,
49         }
50
51         s.cluster = &arvados.Cluster{
52                 Containers: arvados.ContainersConfig{
53                         DispatchPrivateKey: string(dispatchprivraw),
54                         StaleLockTimeout:   arvados.Duration(5 * time.Millisecond),
55                         CloudVMs: arvados.CloudVMsConfig{
56                                 Driver:               "test",
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                         },
69                 },
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),
78                 },
79         }
80         arvadostest.SetServiceURL(&s.cluster.Services.DispatchCloud, "http://localhost:/")
81         arvadostest.SetServiceURL(&s.cluster.Services.Controller, "https://"+os.Getenv("ARVADOS_API_HOST")+"/")
82
83         arvClient, err := arvados.NewClientFromConfig(s.cluster)
84         c.Check(err, check.IsNil)
85
86         s.disp = &dispatcher{
87                 Cluster:   s.cluster,
88                 Context:   s.ctx,
89                 ArvClient: arvClient,
90                 AuthToken: arvadostest.AdminToken,
91         }
92         // Test cases can modify s.cluster before calling
93         // initialize(), and then modify private state before calling
94         // go run().
95 }
96
97 func (s *DispatcherSuite) TearDownTest(c *check.C) {
98         s.cancel()
99         s.disp.Close()
100 }
101
102 // DispatchToStubDriver checks that the dispatcher wires everything
103 // together effectively. It uses a real scheduler and worker pool with
104 // a fake queue and cloud driver. The fake cloud driver injects
105 // artificial errors in order to exercise a variety of code paths.
106 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
107         drivers["test"] = s.stubDriver
108         s.disp.setupOnce.Do(s.disp.initialize)
109         queue := &test.Queue{
110                 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
111                         return ChooseInstanceType(s.cluster, ctr)
112                 },
113         }
114         for i := 0; i < 200; i++ {
115                 queue.Containers = append(queue.Containers, arvados.Container{
116                         UUID:     test.ContainerUUID(i + 1),
117                         State:    arvados.ContainerStateQueued,
118                         Priority: int64(i%20 + 1),
119                         RuntimeConstraints: arvados.RuntimeConstraints{
120                                 RAM:   int64(i%3+1) << 30,
121                                 VCPUs: i%8 + 1,
122                         },
123                 })
124         }
125         s.disp.queue = queue
126
127         var mtx sync.Mutex
128         done := make(chan struct{})
129         waiting := map[string]struct{}{}
130         for _, ctr := range queue.Containers {
131                 waiting[ctr.UUID] = struct{}{}
132         }
133         finishContainer := func(ctr arvados.Container) {
134                 mtx.Lock()
135                 defer mtx.Unlock()
136                 if _, ok := waiting[ctr.UUID]; !ok {
137                         c.Errorf("container completed twice: %s", ctr.UUID)
138                         return
139                 }
140                 delete(waiting, ctr.UUID)
141                 if len(waiting) == 0 {
142                         close(done)
143                 }
144         }
145         executeContainer := func(ctr arvados.Container) int {
146                 finishContainer(ctr)
147                 return int(rand.Uint32() & 0x3)
148         }
149         n := 0
150         s.stubDriver.Queue = queue
151         s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
152                 n++
153                 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
154                 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
155                 stubvm.ExecuteContainer = executeContainer
156                 stubvm.CrashRunningContainer = finishContainer
157                 switch n % 7 {
158                 case 0:
159                         stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
160                 case 1:
161                         stubvm.CrunchRunMissing = true
162                 case 2:
163                         stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
164                 default:
165                         stubvm.CrunchRunCrashRate = 0.1
166                 }
167         }
168
169         start := time.Now()
170         go s.disp.run()
171         err := s.disp.CheckHealth()
172         c.Check(err, check.IsNil)
173
174         select {
175         case <-done:
176                 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
177         case <-time.After(10 * time.Second):
178                 c.Fatalf("timed out; still waiting for %d containers: %q", len(waiting), waiting)
179         }
180
181         deadline := time.Now().Add(5 * time.Second)
182         for range time.NewTicker(10 * time.Millisecond).C {
183                 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
184                 c.Check(err, check.IsNil)
185                 queue.Update()
186                 ents, _ := queue.Entries()
187                 if len(ents) == 0 && len(insts) == 0 {
188                         break
189                 }
190                 if time.Now().After(deadline) {
191                         c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
192                 }
193         }
194 }
195
196 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
197         s.cluster.ManagementToken = "abcdefgh"
198         drivers["test"] = s.stubDriver
199         s.disp.setupOnce.Do(s.disp.initialize)
200         s.disp.queue = &test.Queue{}
201         go s.disp.run()
202
203         for _, token := range []string{"abc", ""} {
204                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
205                 if token != "" {
206                         req.Header.Set("Authorization", "Bearer "+token)
207                 }
208                 resp := httptest.NewRecorder()
209                 s.disp.ServeHTTP(resp, req)
210                 if token == "" {
211                         c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
212                 } else {
213                         c.Check(resp.Code, check.Equals, http.StatusForbidden)
214                 }
215         }
216 }
217
218 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
219         s.cluster.ManagementToken = ""
220         drivers["test"] = s.stubDriver
221         s.disp.setupOnce.Do(s.disp.initialize)
222         s.disp.queue = &test.Queue{}
223         go s.disp.run()
224
225         for _, token := range []string{"abc", ""} {
226                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
227                 if token != "" {
228                         req.Header.Set("Authorization", "Bearer "+token)
229                 }
230                 resp := httptest.NewRecorder()
231                 s.disp.ServeHTTP(resp, req)
232                 c.Check(resp.Code, check.Equals, http.StatusForbidden)
233         }
234 }
235
236 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
237         s.cluster.ManagementToken = "abcdefgh"
238         s.cluster.Containers.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
239         drivers["test"] = s.stubDriver
240         s.disp.setupOnce.Do(s.disp.initialize)
241         s.disp.queue = &test.Queue{}
242         go s.disp.run()
243
244         type instance struct {
245                 Instance             string
246                 WorkerState          string `json:"worker_state"`
247                 Price                float64
248                 LastContainerUUID    string `json:"last_container_uuid"`
249                 ArvadosInstanceType  string `json:"arvados_instance_type"`
250                 ProviderInstanceType string `json:"provider_instance_type"`
251         }
252         type instancesResponse struct {
253                 Items []instance
254         }
255         getInstances := func() instancesResponse {
256                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
257                 req.Header.Set("Authorization", "Bearer abcdefgh")
258                 resp := httptest.NewRecorder()
259                 s.disp.ServeHTTP(resp, req)
260                 var sr instancesResponse
261                 c.Check(resp.Code, check.Equals, http.StatusOK)
262                 err := json.Unmarshal(resp.Body.Bytes(), &sr)
263                 c.Check(err, check.IsNil)
264                 return sr
265         }
266
267         sr := getInstances()
268         c.Check(len(sr.Items), check.Equals, 0)
269
270         ch := s.disp.pool.Subscribe()
271         defer s.disp.pool.Unsubscribe(ch)
272         ok := s.disp.pool.Create(test.InstanceType(1))
273         c.Check(ok, check.Equals, true)
274         <-ch
275
276         for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
277                 sr = getInstances()
278                 if len(sr.Items) > 0 {
279                         break
280                 }
281                 time.Sleep(time.Millisecond)
282         }
283         c.Assert(len(sr.Items), check.Equals, 1)
284         c.Check(sr.Items[0].Instance, check.Matches, "stub.*")
285         c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
286         c.Check(sr.Items[0].Price, check.Equals, 0.123)
287         c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
288         c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
289         c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)
290 }