Bump loofah from 2.2.3 to 2.3.1 in /apps/workbench
[arvados.git] / lib / dispatchcloud / worker / pool_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package worker
6
7 import (
8         "sort"
9         "strings"
10         "time"
11
12         "git.curoverse.com/arvados.git/lib/cloud"
13         "git.curoverse.com/arvados.git/lib/dispatchcloud/test"
14         "git.curoverse.com/arvados.git/sdk/go/arvados"
15         "git.curoverse.com/arvados.git/sdk/go/ctxlog"
16         "github.com/prometheus/client_golang/prometheus"
17         check "gopkg.in/check.v1"
18 )
19
20 const GiB arvados.ByteSize = 1 << 30
21
22 var _ = check.Suite(&PoolSuite{})
23
24 type lessChecker struct {
25         *check.CheckerInfo
26 }
27
28 func (*lessChecker) Check(params []interface{}, names []string) (result bool, error string) {
29         return params[0].(int) < params[1].(int), ""
30 }
31
32 var less = &lessChecker{&check.CheckerInfo{Name: "less", Params: []string{"obtained", "expected"}}}
33
34 type PoolSuite struct{}
35
36 func (suite *PoolSuite) TestResumeAfterRestart(c *check.C) {
37         type1 := test.InstanceType(1)
38         type2 := test.InstanceType(2)
39         type3 := test.InstanceType(3)
40         waitForIdle := func(pool *Pool, notify <-chan struct{}) {
41                 timeout := time.NewTimer(time.Second)
42                 for {
43                         instances := pool.Instances()
44                         sort.Slice(instances, func(i, j int) bool {
45                                 return strings.Compare(instances[i].ArvadosInstanceType, instances[j].ArvadosInstanceType) < 0
46                         })
47                         if len(instances) == 3 &&
48                                 instances[0].ArvadosInstanceType == type1.Name &&
49                                 instances[0].WorkerState == StateIdle.String() &&
50                                 instances[1].ArvadosInstanceType == type1.Name &&
51                                 instances[1].WorkerState == StateIdle.String() &&
52                                 instances[2].ArvadosInstanceType == type2.Name &&
53                                 instances[2].WorkerState == StateIdle.String() {
54                                 return
55                         }
56                         select {
57                         case <-timeout.C:
58                                 c.Logf("pool.Instances() == %#v", instances)
59                                 c.Error("timed out")
60                                 return
61                         case <-notify:
62                         }
63                 }
64         }
65
66         logger := ctxlog.TestLogger(c)
67         driver := &test.StubDriver{}
68         instanceSetID := cloud.InstanceSetID("test-instance-set-id")
69         is, err := driver.InstanceSet(nil, instanceSetID, nil, logger)
70         c.Assert(err, check.IsNil)
71
72         newExecutor := func(cloud.Instance) Executor {
73                 return stubExecutor{
74                         "crunch-run --list": stubResp{},
75                         "true":              stubResp{},
76                 }
77         }
78
79         cluster := &arvados.Cluster{
80                 Containers: arvados.ContainersConfig{
81                         CloudVMs: arvados.CloudVMsConfig{
82                                 BootProbeCommand:   "true",
83                                 MaxProbesPerSecond: 1000,
84                                 ProbeInterval:      arvados.Duration(time.Millisecond * 10),
85                                 SyncInterval:       arvados.Duration(time.Millisecond * 10),
86                                 TagKeyPrefix:       "testprefix:",
87                         },
88                 },
89                 InstanceTypes: arvados.InstanceTypeMap{
90                         type1.Name: type1,
91                         type2.Name: type2,
92                         type3.Name: type3,
93                 },
94         }
95
96         pool := NewPool(logger, arvados.NewClientFromEnv(), prometheus.NewRegistry(), instanceSetID, is, newExecutor, nil, cluster)
97         notify := pool.Subscribe()
98         defer pool.Unsubscribe(notify)
99         pool.Create(type1)
100         pool.Create(type1)
101         pool.Create(type2)
102         waitForIdle(pool, notify)
103         var heldInstanceID cloud.InstanceID
104         for _, inst := range pool.Instances() {
105                 if inst.ArvadosInstanceType == type2.Name {
106                         heldInstanceID = cloud.InstanceID(inst.Instance)
107                         pool.SetIdleBehavior(heldInstanceID, IdleBehaviorHold)
108                 }
109         }
110         // Wait for the tags to save to the cloud provider
111         tagKey := cluster.Containers.CloudVMs.TagKeyPrefix + tagKeyIdleBehavior
112         deadline := time.Now().Add(time.Second)
113         for !func() bool {
114                 pool.mtx.RLock()
115                 defer pool.mtx.RUnlock()
116                 for _, wkr := range pool.workers {
117                         if wkr.instType == type2 {
118                                 return wkr.instance.Tags()[tagKey] == string(IdleBehaviorHold)
119                         }
120                 }
121                 return false
122         }() {
123                 if time.Now().After(deadline) {
124                         c.Fatal("timeout")
125                 }
126                 time.Sleep(time.Millisecond * 10)
127         }
128         pool.Stop()
129
130         c.Log("------- starting new pool, waiting to recover state")
131
132         pool2 := NewPool(logger, arvados.NewClientFromEnv(), prometheus.NewRegistry(), instanceSetID, is, newExecutor, nil, cluster)
133         notify2 := pool2.Subscribe()
134         defer pool2.Unsubscribe(notify2)
135         waitForIdle(pool2, notify2)
136         for _, inst := range pool2.Instances() {
137                 if inst.ArvadosInstanceType == type2.Name {
138                         c.Check(inst.Instance, check.Equals, heldInstanceID)
139                         c.Check(inst.IdleBehavior, check.Equals, IdleBehaviorHold)
140                 } else {
141                         c.Check(inst.IdleBehavior, check.Equals, IdleBehaviorRun)
142                 }
143         }
144         pool2.Stop()
145 }
146
147 func (suite *PoolSuite) TestCreateUnallocShutdown(c *check.C) {
148         logger := ctxlog.TestLogger(c)
149         driver := test.StubDriver{HoldCloudOps: true}
150         instanceSet, err := driver.InstanceSet(nil, "test-instance-set-id", nil, logger)
151         c.Assert(err, check.IsNil)
152
153         type1 := arvados.InstanceType{Name: "a1s", ProviderType: "a1.small", VCPUs: 1, RAM: 1 * GiB, Price: .01}
154         type2 := arvados.InstanceType{Name: "a2m", ProviderType: "a2.medium", VCPUs: 2, RAM: 2 * GiB, Price: .02}
155         type3 := arvados.InstanceType{Name: "a2l", ProviderType: "a2.large", VCPUs: 4, RAM: 4 * GiB, Price: .04}
156         pool := &Pool{
157                 logger:      logger,
158                 newExecutor: func(cloud.Instance) Executor { return stubExecutor{} },
159                 instanceSet: &throttledInstanceSet{InstanceSet: instanceSet},
160                 instanceTypes: arvados.InstanceTypeMap{
161                         type1.Name: type1,
162                         type2.Name: type2,
163                         type3.Name: type3,
164                 },
165         }
166         notify := pool.Subscribe()
167         defer pool.Unsubscribe(notify)
168         notify2 := pool.Subscribe()
169         defer pool.Unsubscribe(notify2)
170
171         c.Check(pool.Unallocated()[type1], check.Equals, 0)
172         c.Check(pool.Unallocated()[type2], check.Equals, 0)
173         c.Check(pool.Unallocated()[type3], check.Equals, 0)
174         pool.Create(type2)
175         pool.Create(type1)
176         pool.Create(type2)
177         pool.Create(type3)
178         c.Check(pool.Unallocated()[type1], check.Equals, 1)
179         c.Check(pool.Unallocated()[type2], check.Equals, 2)
180         c.Check(pool.Unallocated()[type3], check.Equals, 1)
181
182         // Unblock the pending Create calls.
183         go driver.ReleaseCloudOps(4)
184
185         // Wait for each instance to either return from its Create
186         // call, or show up in a poll.
187         suite.wait(c, pool, notify, func() bool {
188                 pool.mtx.RLock()
189                 defer pool.mtx.RUnlock()
190                 return len(pool.workers) == 4
191         })
192
193         // Place type3 node on admin-hold
194         ivs := suite.instancesByType(pool, type3)
195         c.Assert(ivs, check.HasLen, 1)
196         type3instanceID := ivs[0].Instance
197         err = pool.SetIdleBehavior(type3instanceID, IdleBehaviorHold)
198         c.Check(err, check.IsNil)
199
200         // Check admin-hold behavior: refuse to shutdown, and don't
201         // report as Unallocated ("available now or soon").
202         c.Check(pool.Shutdown(type3), check.Equals, false)
203         suite.wait(c, pool, notify, func() bool {
204                 return pool.Unallocated()[type3] == 0
205         })
206         c.Check(suite.instancesByType(pool, type3), check.HasLen, 1)
207
208         // Shutdown both type2 nodes
209         c.Check(pool.Shutdown(type2), check.Equals, true)
210         suite.wait(c, pool, notify, func() bool {
211                 return pool.Unallocated()[type1] == 1 && pool.Unallocated()[type2] == 1
212         })
213         c.Check(pool.Shutdown(type2), check.Equals, true)
214         suite.wait(c, pool, notify, func() bool {
215                 return pool.Unallocated()[type1] == 1 && pool.Unallocated()[type2] == 0
216         })
217         c.Check(pool.Shutdown(type2), check.Equals, false)
218         for {
219                 // Consume any waiting notifications to ensure the
220                 // next one we get is from Shutdown.
221                 select {
222                 case <-notify:
223                         continue
224                 default:
225                 }
226                 break
227         }
228
229         // Shutdown type1 node
230         c.Check(pool.Shutdown(type1), check.Equals, true)
231         suite.wait(c, pool, notify, func() bool {
232                 return pool.Unallocated()[type1] == 0 && pool.Unallocated()[type2] == 0 && pool.Unallocated()[type3] == 0
233         })
234         select {
235         case <-notify2:
236         case <-time.After(time.Second):
237                 c.Error("notify did not receive")
238         }
239
240         // Put type3 node back in service.
241         err = pool.SetIdleBehavior(type3instanceID, IdleBehaviorRun)
242         c.Check(err, check.IsNil)
243         suite.wait(c, pool, notify, func() bool {
244                 return pool.Unallocated()[type3] == 1
245         })
246
247         // Check admin-drain behavior: shut down right away, and don't
248         // report as Unallocated.
249         err = pool.SetIdleBehavior(type3instanceID, IdleBehaviorDrain)
250         c.Check(err, check.IsNil)
251         suite.wait(c, pool, notify, func() bool {
252                 return pool.Unallocated()[type3] == 0
253         })
254         suite.wait(c, pool, notify, func() bool {
255                 ivs := suite.instancesByType(pool, type3)
256                 return len(ivs) == 1 && ivs[0].WorkerState == StateShutdown.String()
257         })
258
259         // Unblock all pending Destroy calls. Pool calls Destroy again
260         // if a node still appears in the provider list after a
261         // previous attempt, so there might be more than 4 Destroy
262         // calls to unblock.
263         go driver.ReleaseCloudOps(4444)
264
265         // Sync until all instances disappear from the provider list.
266         suite.wait(c, pool, notify, func() bool {
267                 pool.getInstancesAndSync()
268                 return len(pool.Instances()) == 0
269         })
270 }
271
272 func (suite *PoolSuite) instancesByType(pool *Pool, it arvados.InstanceType) []InstanceView {
273         var ivs []InstanceView
274         for _, iv := range pool.Instances() {
275                 if iv.ArvadosInstanceType == it.Name {
276                         ivs = append(ivs, iv)
277                 }
278         }
279         return ivs
280 }
281
282 func (suite *PoolSuite) wait(c *check.C, pool *Pool, notify <-chan struct{}, ready func() bool) {
283         timeout := time.NewTimer(time.Second).C
284         for !ready() {
285                 select {
286                 case <-notify:
287                         continue
288                 case <-timeout:
289                 }
290                 break
291         }
292         c.Check(ready(), check.Equals, true)
293 }