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