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