Merge branch 'master' into 14873-api-rails5-upgrade
[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                 CloudVMs: arvados.CloudVMs{
53                         Driver:               "test",
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,
60                 },
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),
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                 NodeProfiles: map[string]arvados.NodeProfile{
80                         "*": {
81                                 Controller:    arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_API_HOST")},
82                                 DispatchCloud: arvados.SystemServiceInstance{Listen: ":"},
83                         },
84                 },
85                 Services: arvados.Services{
86                         Controller: arvados.Service{ExternalURL: arvados.URL{Scheme: "https", Host: os.Getenv("ARVADOS_API_HOST")}},
87                 },
88         }
89
90         arvClient, err := arvados.NewClientFromConfig(s.cluster)
91         c.Check(err, check.IsNil)
92
93         s.disp = &dispatcher{
94                 Cluster:   s.cluster,
95                 Context:   s.ctx,
96                 ArvClient: arvClient,
97                 AuthToken: arvadostest.AdminToken,
98         }
99         // Test cases can modify s.cluster before calling
100         // initialize(), and then modify private state before calling
101         // go run().
102 }
103
104 func (s *DispatcherSuite) TearDownTest(c *check.C) {
105         s.cancel()
106         s.disp.Close()
107 }
108
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)
119                 },
120         }
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,
128                                 VCPUs: i%8 + 1,
129                         },
130                 })
131         }
132         s.disp.queue = queue
133
134         var mtx sync.Mutex
135         done := make(chan struct{})
136         waiting := map[string]struct{}{}
137         for _, ctr := range queue.Containers {
138                 waiting[ctr.UUID] = struct{}{}
139         }
140         finishContainer := func(ctr arvados.Container) {
141                 mtx.Lock()
142                 defer mtx.Unlock()
143                 if _, ok := waiting[ctr.UUID]; !ok {
144                         c.Errorf("container completed twice: %s", ctr.UUID)
145                         return
146                 }
147                 delete(waiting, ctr.UUID)
148                 if len(waiting) == 0 {
149                         close(done)
150                 }
151         }
152         executeContainer := func(ctr arvados.Container) int {
153                 finishContainer(ctr)
154                 return int(rand.Uint32() & 0x3)
155         }
156         n := 0
157         s.stubDriver.Queue = queue
158         s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
159                 n++
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
164                 switch n % 7 {
165                 case 0:
166                         stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
167                 case 1:
168                         stubvm.CrunchRunMissing = true
169                 case 2:
170                         stubvm.ReportBroken = time.Now().Add(time.Duration(rand.Int63n(200)) * time.Millisecond)
171                 default:
172                         stubvm.CrunchRunCrashRate = 0.1
173                 }
174         }
175
176         start := time.Now()
177         go s.disp.run()
178         err := s.disp.CheckHealth()
179         c.Check(err, check.IsNil)
180
181         select {
182         case <-done:
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)
186         }
187
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)
192                 queue.Update()
193                 ents, _ := queue.Entries()
194                 if len(ents) == 0 && len(insts) == 0 {
195                         break
196                 }
197                 if time.Now().After(deadline) {
198                         c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
199                 }
200         }
201 }
202
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{}
208         go s.disp.run()
209
210         for _, token := range []string{"abc", ""} {
211                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
212                 if token != "" {
213                         req.Header.Set("Authorization", "Bearer "+token)
214                 }
215                 resp := httptest.NewRecorder()
216                 s.disp.ServeHTTP(resp, req)
217                 if token == "" {
218                         c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
219                 } else {
220                         c.Check(resp.Code, check.Equals, http.StatusForbidden)
221                 }
222         }
223 }
224
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{}
230         go s.disp.run()
231
232         for _, token := range []string{"abc", ""} {
233                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
234                 if token != "" {
235                         req.Header.Set("Authorization", "Bearer "+token)
236                 }
237                 resp := httptest.NewRecorder()
238                 s.disp.ServeHTTP(resp, req)
239                 c.Check(resp.Code, check.Equals, http.StatusForbidden)
240         }
241 }
242
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{}
249         go s.disp.run()
250
251         type instance struct {
252                 Instance             string
253                 WorkerState          string `json:"worker_state"`
254                 Price                float64
255                 LastContainerUUID    string `json:"last_container_uuid"`
256                 ArvadosInstanceType  string `json:"arvados_instance_type"`
257                 ProviderInstanceType string `json:"provider_instance_type"`
258         }
259         type instancesResponse struct {
260                 Items []instance
261         }
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)
271                 return sr
272         }
273
274         sr := getInstances()
275         c.Check(len(sr.Items), check.Equals, 0)
276
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)
281         <-ch
282
283         for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
284                 sr = getInstances()
285                 if len(sr.Items) > 0 {
286                         break
287                 }
288                 time.Sleep(time.Millisecond)
289         }
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)
297 }