14807: Fix unreliable test.
[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/ctxlog"
21         "golang.org/x/crypto/ssh"
22         check "gopkg.in/check.v1"
23 )
24
25 var _ = check.Suite(&DispatcherSuite{})
26
27 type DispatcherSuite struct {
28         ctx        context.Context
29         cancel     context.CancelFunc
30         cluster    *arvados.Cluster
31         stubDriver *test.StubDriver
32         disp       *dispatcher
33 }
34
35 func (s *DispatcherSuite) SetUpTest(c *check.C) {
36         s.ctx, s.cancel = context.WithCancel(context.Background())
37         s.ctx = ctxlog.Context(s.ctx, ctxlog.TestLogger(c))
38         dispatchpub, _ := test.LoadTestKey(c, "test/sshkey_dispatch")
39         dispatchprivraw, err := ioutil.ReadFile("test/sshkey_dispatch")
40         c.Assert(err, check.IsNil)
41
42         _, hostpriv := test.LoadTestKey(c, "test/sshkey_vm")
43         s.stubDriver = &test.StubDriver{
44                 HostKey:                   hostpriv,
45                 AuthorizedKeys:            []ssh.PublicKey{dispatchpub},
46                 ErrorRateDestroy:          0.1,
47                 MinTimeBetweenCreateCalls: time.Millisecond,
48         }
49
50         s.cluster = &arvados.Cluster{
51                 CloudVMs: arvados.CloudVMs{
52                         Driver:          "test",
53                         SyncInterval:    arvados.Duration(10 * time.Millisecond),
54                         TimeoutIdle:     arvados.Duration(150 * time.Millisecond),
55                         TimeoutBooting:  arvados.Duration(150 * time.Millisecond),
56                         TimeoutProbe:    arvados.Duration(15 * time.Millisecond),
57                         TimeoutShutdown: arvados.Duration(5 * time.Millisecond),
58                 },
59                 Dispatch: arvados.Dispatch{
60                         PrivateKey:         string(dispatchprivraw),
61                         PollInterval:       arvados.Duration(5 * time.Millisecond),
62                         ProbeInterval:      arvados.Duration(5 * time.Millisecond),
63                         StaleLockTimeout:   arvados.Duration(5 * time.Millisecond),
64                         MaxProbesPerSecond: 1000,
65                 },
66                 InstanceTypes: arvados.InstanceTypeMap{
67                         test.InstanceType(1).Name:  test.InstanceType(1),
68                         test.InstanceType(2).Name:  test.InstanceType(2),
69                         test.InstanceType(3).Name:  test.InstanceType(3),
70                         test.InstanceType(4).Name:  test.InstanceType(4),
71                         test.InstanceType(6).Name:  test.InstanceType(6),
72                         test.InstanceType(8).Name:  test.InstanceType(8),
73                         test.InstanceType(16).Name: test.InstanceType(16),
74                 },
75                 NodeProfiles: map[string]arvados.NodeProfile{
76                         "*": {
77                                 Controller:    arvados.SystemServiceInstance{Listen: os.Getenv("ARVADOS_API_HOST")},
78                                 DispatchCloud: arvados.SystemServiceInstance{Listen: ":"},
79                         },
80                 },
81         }
82         s.disp = &dispatcher{
83                 Cluster: s.cluster,
84                 Context: s.ctx,
85         }
86         // Test cases can modify s.cluster before calling
87         // initialize(), and then modify private state before calling
88         // go run().
89 }
90
91 func (s *DispatcherSuite) TearDownTest(c *check.C) {
92         s.cancel()
93         s.disp.Close()
94 }
95
96 // DispatchToStubDriver checks that the dispatcher wires everything
97 // together effectively. It uses a real scheduler and worker pool with
98 // a fake queue and cloud driver. The fake cloud driver injects
99 // artificial errors in order to exercise a variety of code paths.
100 func (s *DispatcherSuite) TestDispatchToStubDriver(c *check.C) {
101         drivers["test"] = s.stubDriver
102         s.disp.setupOnce.Do(s.disp.initialize)
103         queue := &test.Queue{
104                 ChooseType: func(ctr *arvados.Container) (arvados.InstanceType, error) {
105                         return ChooseInstanceType(s.cluster, ctr)
106                 },
107         }
108         for i := 0; i < 200; i++ {
109                 queue.Containers = append(queue.Containers, arvados.Container{
110                         UUID:     test.ContainerUUID(i + 1),
111                         State:    arvados.ContainerStateQueued,
112                         Priority: int64(i%20 + 1),
113                         RuntimeConstraints: arvados.RuntimeConstraints{
114                                 RAM:   int64(i%3+1) << 30,
115                                 VCPUs: i%8 + 1,
116                         },
117                 })
118         }
119         s.disp.queue = queue
120
121         var mtx sync.Mutex
122         done := make(chan struct{})
123         waiting := map[string]struct{}{}
124         for _, ctr := range queue.Containers {
125                 waiting[ctr.UUID] = struct{}{}
126         }
127         executeContainer := func(ctr arvados.Container) int {
128                 mtx.Lock()
129                 defer mtx.Unlock()
130                 if _, ok := waiting[ctr.UUID]; !ok {
131                         c.Logf("container completed twice: %s -- perhaps completed after stub instance was killed?", ctr.UUID)
132                         return 1
133                 }
134                 delete(waiting, ctr.UUID)
135                 if len(waiting) == 0 {
136                         close(done)
137                 }
138                 return int(rand.Uint32() & 0x3)
139         }
140         n := 0
141         s.stubDriver.Queue = queue
142         s.stubDriver.SetupVM = func(stubvm *test.StubVM) {
143                 n++
144                 stubvm.Boot = time.Now().Add(time.Duration(rand.Int63n(int64(5 * time.Millisecond))))
145                 stubvm.CrunchRunDetachDelay = time.Duration(rand.Int63n(int64(10 * time.Millisecond)))
146                 stubvm.ExecuteContainer = executeContainer
147                 switch n % 7 {
148                 case 0:
149                         stubvm.Broken = time.Now().Add(time.Duration(rand.Int63n(90)) * time.Millisecond)
150                 case 1:
151                         stubvm.CrunchRunMissing = true
152                 default:
153                         stubvm.CrunchRunCrashRate = 0.1
154                 }
155         }
156
157         start := time.Now()
158         go s.disp.run()
159         err := s.disp.CheckHealth()
160         c.Check(err, check.IsNil)
161
162         select {
163         case <-done:
164                 c.Logf("containers finished (%s), waiting for instances to shutdown and queue to clear", time.Since(start))
165         case <-time.After(10 * time.Second):
166                 c.Fatalf("timed out; still waiting for %d containers: %q", len(waiting), waiting)
167         }
168
169         deadline := time.Now().Add(5 * time.Second)
170         for range time.NewTicker(10 * time.Millisecond).C {
171                 insts, err := s.stubDriver.InstanceSets()[0].Instances(nil)
172                 c.Check(err, check.IsNil)
173                 queue.Update()
174                 ents, _ := queue.Entries()
175                 if len(ents) == 0 && len(insts) == 0 {
176                         break
177                 }
178                 if time.Now().After(deadline) {
179                         c.Fatalf("timed out with %d containers (%v), %d instances (%+v)", len(ents), ents, len(insts), insts)
180                 }
181         }
182 }
183
184 func (s *DispatcherSuite) TestAPIPermissions(c *check.C) {
185         s.cluster.ManagementToken = "abcdefgh"
186         drivers["test"] = s.stubDriver
187         s.disp.setupOnce.Do(s.disp.initialize)
188         s.disp.queue = &test.Queue{}
189         go s.disp.run()
190
191         for _, token := range []string{"abc", ""} {
192                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
193                 if token != "" {
194                         req.Header.Set("Authorization", "Bearer "+token)
195                 }
196                 resp := httptest.NewRecorder()
197                 s.disp.ServeHTTP(resp, req)
198                 if token == "" {
199                         c.Check(resp.Code, check.Equals, http.StatusUnauthorized)
200                 } else {
201                         c.Check(resp.Code, check.Equals, http.StatusForbidden)
202                 }
203         }
204 }
205
206 func (s *DispatcherSuite) TestAPIDisabled(c *check.C) {
207         s.cluster.ManagementToken = ""
208         drivers["test"] = s.stubDriver
209         s.disp.setupOnce.Do(s.disp.initialize)
210         s.disp.queue = &test.Queue{}
211         go s.disp.run()
212
213         for _, token := range []string{"abc", ""} {
214                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
215                 if token != "" {
216                         req.Header.Set("Authorization", "Bearer "+token)
217                 }
218                 resp := httptest.NewRecorder()
219                 s.disp.ServeHTTP(resp, req)
220                 c.Check(resp.Code, check.Equals, http.StatusForbidden)
221         }
222 }
223
224 func (s *DispatcherSuite) TestInstancesAPI(c *check.C) {
225         s.cluster.ManagementToken = "abcdefgh"
226         s.cluster.CloudVMs.TimeoutBooting = arvados.Duration(time.Second)
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         type instance struct {
233                 Instance             string
234                 WorkerState          string `json:"worker_state"`
235                 Price                float64
236                 LastContainerUUID    string `json:"last_container_uuid"`
237                 ArvadosInstanceType  string `json:"arvados_instance_type"`
238                 ProviderInstanceType string `json:"provider_instance_type"`
239         }
240         type instancesResponse struct {
241                 Items []instance
242         }
243         getInstances := func() instancesResponse {
244                 req := httptest.NewRequest("GET", "/arvados/v1/dispatch/instances", nil)
245                 req.Header.Set("Authorization", "Bearer abcdefgh")
246                 resp := httptest.NewRecorder()
247                 s.disp.ServeHTTP(resp, req)
248                 var sr instancesResponse
249                 c.Check(resp.Code, check.Equals, http.StatusOK)
250                 err := json.Unmarshal(resp.Body.Bytes(), &sr)
251                 c.Check(err, check.IsNil)
252                 return sr
253         }
254
255         sr := getInstances()
256         c.Check(len(sr.Items), check.Equals, 0)
257
258         ch := s.disp.pool.Subscribe()
259         defer s.disp.pool.Unsubscribe(ch)
260         ok := s.disp.pool.Create(test.InstanceType(1))
261         c.Check(ok, check.Equals, true)
262         <-ch
263
264         for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
265                 sr = getInstances()
266                 if len(sr.Items) > 0 {
267                         break
268                 }
269                 time.Sleep(time.Millisecond)
270         }
271         c.Assert(len(sr.Items), check.Equals, 1)
272         c.Check(sr.Items[0].Instance, check.Matches, "stub.*")
273         c.Check(sr.Items[0].WorkerState, check.Equals, "booting")
274         c.Check(sr.Items[0].Price, check.Equals, 0.123)
275         c.Check(sr.Items[0].LastContainerUUID, check.Equals, "")
276         c.Check(sr.Items[0].ProviderInstanceType, check.Equals, test.InstanceType(1).ProviderType)
277         c.Check(sr.Items[0].ArvadosInstanceType, check.Equals, test.InstanceType(1).Name)
278 }