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