Merge branch '13933-dispatch-batch-size'
[arvados.git] / services / crunch-dispatch-slurm / crunch-dispatch-slurm_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "bytes"
9         "context"
10         "errors"
11         "fmt"
12         "io"
13         "io/ioutil"
14         "log"
15         "net/http"
16         "net/http/httptest"
17         "os"
18         "os/exec"
19         "strings"
20         "testing"
21         "time"
22
23         "git.curoverse.com/arvados.git/lib/dispatchcloud"
24         "git.curoverse.com/arvados.git/sdk/go/arvados"
25         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
26         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
27         "git.curoverse.com/arvados.git/sdk/go/dispatch"
28         . "gopkg.in/check.v1"
29 )
30
31 // Gocheck boilerplate
32 func Test(t *testing.T) {
33         TestingT(t)
34 }
35
36 var _ = Suite(&IntegrationSuite{})
37 var _ = Suite(&StubbedSuite{})
38
39 type IntegrationSuite struct {
40         disp  Dispatcher
41         slurm slurmFake
42 }
43
44 func (s *IntegrationSuite) SetUpTest(c *C) {
45         arvadostest.StartAPI()
46         os.Setenv("ARVADOS_API_TOKEN", arvadostest.Dispatch1Token)
47         s.disp = Dispatcher{}
48         s.disp.setup()
49         s.slurm = slurmFake{}
50 }
51
52 func (s *IntegrationSuite) TearDownTest(c *C) {
53         arvadostest.ResetEnv()
54         arvadostest.StopAPI()
55 }
56
57 type slurmFake struct {
58         didBatch      [][]string
59         didCancel     []string
60         didRelease    []string
61         didRenice     [][]string
62         queue         string
63         rejectNice10K bool
64         // If non-nil, run this func during the 2nd+ call to Cancel()
65         onCancel func()
66         // Error returned by Batch()
67         errBatch error
68 }
69
70 func (sf *slurmFake) Batch(script io.Reader, args []string) error {
71         sf.didBatch = append(sf.didBatch, args)
72         return sf.errBatch
73 }
74
75 func (sf *slurmFake) QueueCommand(args []string) *exec.Cmd {
76         return exec.Command("echo", sf.queue)
77 }
78
79 func (sf *slurmFake) Release(name string) error {
80         sf.didRelease = append(sf.didRelease, name)
81         return nil
82 }
83
84 func (sf *slurmFake) Renice(name string, nice int64) error {
85         sf.didRenice = append(sf.didRenice, []string{name, fmt.Sprintf("%d", nice)})
86         if sf.rejectNice10K && nice > 10000 {
87                 return errors.New("scontrol: error: Invalid nice value, must be between -10000 and 10000")
88         }
89         return nil
90 }
91
92 func (sf *slurmFake) Cancel(name string) error {
93         sf.didCancel = append(sf.didCancel, name)
94         if len(sf.didCancel) == 1 {
95                 // simulate error on first attempt
96                 return errors.New("something terrible happened")
97         }
98         if sf.onCancel != nil {
99                 sf.onCancel()
100         }
101         return nil
102 }
103
104 func (s *IntegrationSuite) integrationTest(c *C,
105         expectBatch [][]string,
106         runContainer func(*dispatch.Dispatcher, arvados.Container)) arvados.Container {
107         arvadostest.ResetEnv()
108
109         arv, err := arvadosclient.MakeArvadosClient()
110         c.Assert(err, IsNil)
111
112         // There should be one queued container
113         params := arvadosclient.Dict{
114                 "filters": [][]string{{"state", "=", "Queued"}},
115         }
116         var containers arvados.ContainerList
117         err = arv.List("containers", params, &containers)
118         c.Check(err, IsNil)
119         c.Assert(len(containers.Items), Equals, 1)
120
121         s.disp.CrunchRunCommand = []string{"echo"}
122
123         ctx, cancel := context.WithCancel(context.Background())
124         doneRun := make(chan struct{})
125
126         s.disp.Dispatcher = &dispatch.Dispatcher{
127                 Arv:        arv,
128                 PollPeriod: time.Second,
129                 RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
130                         go func() {
131                                 runContainer(disp, ctr)
132                                 s.slurm.queue = ""
133                                 doneRun <- struct{}{}
134                         }()
135                         s.disp.runContainer(disp, ctr, status)
136                         cancel()
137                 },
138         }
139
140         s.disp.slurm = &s.slurm
141         s.disp.sqCheck = &SqueueChecker{Period: 500 * time.Millisecond, Slurm: s.disp.slurm}
142
143         err = s.disp.Dispatcher.Run(ctx)
144         <-doneRun
145         c.Assert(err, Equals, context.Canceled)
146
147         s.disp.sqCheck.Stop()
148
149         c.Check(s.slurm.didBatch, DeepEquals, expectBatch)
150
151         // There should be no queued containers now
152         err = arv.List("containers", params, &containers)
153         c.Check(err, IsNil)
154         c.Check(len(containers.Items), Equals, 0)
155
156         // Previously "Queued" container should now be in "Complete" state
157         var container arvados.Container
158         err = arv.Get("containers", "zzzzz-dz642-queuedcontainer", nil, &container)
159         c.Check(err, IsNil)
160         return container
161 }
162
163 func (s *IntegrationSuite) TestNormal(c *C) {
164         s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
165         container := s.integrationTest(c,
166                 nil,
167                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
168                         dispatcher.UpdateState(container.UUID, dispatch.Running)
169                         time.Sleep(3 * time.Second)
170                         dispatcher.UpdateState(container.UUID, dispatch.Complete)
171                 })
172         c.Check(container.State, Equals, arvados.ContainerStateComplete)
173 }
174
175 func (s *IntegrationSuite) TestCancel(c *C) {
176         s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
177         readyToCancel := make(chan bool)
178         s.slurm.onCancel = func() { <-readyToCancel }
179         container := s.integrationTest(c,
180                 nil,
181                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
182                         dispatcher.UpdateState(container.UUID, dispatch.Running)
183                         time.Sleep(time.Second)
184                         dispatcher.Arv.Update("containers", container.UUID,
185                                 arvadosclient.Dict{
186                                         "container": arvadosclient.Dict{"priority": 0}},
187                                 nil)
188                         readyToCancel <- true
189                         close(readyToCancel)
190                 })
191         c.Check(container.State, Equals, arvados.ContainerStateCancelled)
192         c.Check(len(s.slurm.didCancel) > 1, Equals, true)
193         c.Check(s.slurm.didCancel[:2], DeepEquals, []string{"zzzzz-dz642-queuedcontainer", "zzzzz-dz642-queuedcontainer"})
194 }
195
196 func (s *IntegrationSuite) TestMissingFromSqueue(c *C) {
197         container := s.integrationTest(c,
198                 [][]string{{
199                         fmt.Sprintf("--job-name=%s", "zzzzz-dz642-queuedcontainer"),
200                         fmt.Sprintf("--nice=%d", 10000),
201                         fmt.Sprintf("--mem=%d", 11445),
202                         fmt.Sprintf("--cpus-per-task=%d", 4),
203                         fmt.Sprintf("--tmp=%d", 45777),
204                 }},
205                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
206                         dispatcher.UpdateState(container.UUID, dispatch.Running)
207                         time.Sleep(3 * time.Second)
208                         dispatcher.UpdateState(container.UUID, dispatch.Complete)
209                 })
210         c.Check(container.State, Equals, arvados.ContainerStateCancelled)
211 }
212
213 func (s *IntegrationSuite) TestSbatchFail(c *C) {
214         s.slurm = slurmFake{errBatch: errors.New("something terrible happened")}
215         container := s.integrationTest(c,
216                 [][]string{{"--job-name=zzzzz-dz642-queuedcontainer", "--nice=10000", "--mem=11445", "--cpus-per-task=4", "--tmp=45777"}},
217                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
218                         dispatcher.UpdateState(container.UUID, dispatch.Running)
219                         dispatcher.UpdateState(container.UUID, dispatch.Complete)
220                 })
221         c.Check(container.State, Equals, arvados.ContainerStateComplete)
222
223         arv, err := arvadosclient.MakeArvadosClient()
224         c.Assert(err, IsNil)
225
226         var ll arvados.LogList
227         err = arv.List("logs", arvadosclient.Dict{"filters": [][]string{
228                 {"object_uuid", "=", container.UUID},
229                 {"event_type", "=", "dispatch"},
230         }}, &ll)
231         c.Assert(err, IsNil)
232         c.Assert(len(ll.Items), Equals, 1)
233 }
234
235 type StubbedSuite struct {
236         disp Dispatcher
237 }
238
239 func (s *StubbedSuite) SetUpTest(c *C) {
240         s.disp = Dispatcher{}
241         s.disp.setup()
242 }
243
244 func (s *StubbedSuite) TestAPIErrorGettingContainers(c *C) {
245         apiStubResponses := make(map[string]arvadostest.StubResponse)
246         apiStubResponses["/arvados/v1/api_client_authorizations/current"] = arvadostest.StubResponse{200, `{"uuid":"` + arvadostest.Dispatch1AuthUUID + `"}`}
247         apiStubResponses["/arvados/v1/containers"] = arvadostest.StubResponse{500, string(`{}`)}
248
249         s.testWithServerStub(c, apiStubResponses, "echo", "error getting count of containers")
250 }
251
252 func (s *StubbedSuite) testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubResponse, crunchCmd string, expected string) {
253         apiStub := arvadostest.ServerStub{apiStubResponses}
254
255         api := httptest.NewServer(&apiStub)
256         defer api.Close()
257
258         arv := &arvadosclient.ArvadosClient{
259                 Scheme:    "http",
260                 ApiServer: api.URL[7:],
261                 ApiToken:  "abc123",
262                 Client:    &http.Client{Transport: &http.Transport{}},
263                 Retries:   0,
264         }
265
266         buf := bytes.NewBuffer(nil)
267         log.SetOutput(io.MultiWriter(buf, os.Stderr))
268         defer log.SetOutput(os.Stderr)
269
270         s.disp.CrunchRunCommand = []string{crunchCmd}
271
272         ctx, cancel := context.WithCancel(context.Background())
273         dispatcher := dispatch.Dispatcher{
274                 Arv:        arv,
275                 PollPeriod: time.Second,
276                 RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
277                         go func() {
278                                 time.Sleep(time.Second)
279                                 disp.UpdateState(ctr.UUID, dispatch.Running)
280                                 disp.UpdateState(ctr.UUID, dispatch.Complete)
281                         }()
282                         s.disp.runContainer(disp, ctr, status)
283                         cancel()
284                 },
285         }
286
287         go func() {
288                 for i := 0; i < 80 && !strings.Contains(buf.String(), expected); i++ {
289                         time.Sleep(100 * time.Millisecond)
290                 }
291                 cancel()
292         }()
293
294         err := dispatcher.Run(ctx)
295         c.Assert(err, Equals, context.Canceled)
296
297         c.Check(buf.String(), Matches, `(?ms).*`+expected+`.*`)
298 }
299
300 func (s *StubbedSuite) TestNoSuchConfigFile(c *C) {
301         err := s.disp.readConfig("/nosuchdir89j7879/8hjwr7ojgyy7")
302         c.Assert(err, NotNil)
303 }
304
305 func (s *StubbedSuite) TestBadSbatchArgsConfig(c *C) {
306         tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
307         c.Check(err, IsNil)
308         defer os.Remove(tmpfile.Name())
309
310         _, err = tmpfile.Write([]byte(`{"SbatchArguments": "oops this is not a string array"}`))
311         c.Check(err, IsNil)
312
313         err = s.disp.readConfig(tmpfile.Name())
314         c.Assert(err, NotNil)
315 }
316
317 func (s *StubbedSuite) TestNoSuchArgInConfigIgnored(c *C) {
318         tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
319         c.Check(err, IsNil)
320         defer os.Remove(tmpfile.Name())
321
322         _, err = tmpfile.Write([]byte(`{"NoSuchArg": "Nobody loves me, not one tiny hunk."}`))
323         c.Check(err, IsNil)
324
325         err = s.disp.readConfig(tmpfile.Name())
326         c.Assert(err, IsNil)
327         c.Check(0, Equals, len(s.disp.SbatchArguments))
328 }
329
330 func (s *StubbedSuite) TestReadConfig(c *C) {
331         tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
332         c.Check(err, IsNil)
333         defer os.Remove(tmpfile.Name())
334
335         args := []string{"--arg1=v1", "--arg2", "--arg3=v3"}
336         argsS := `{"SbatchArguments": ["--arg1=v1",  "--arg2", "--arg3=v3"]}`
337         _, err = tmpfile.Write([]byte(argsS))
338         c.Check(err, IsNil)
339
340         err = s.disp.readConfig(tmpfile.Name())
341         c.Assert(err, IsNil)
342         c.Check(args, DeepEquals, s.disp.SbatchArguments)
343 }
344
345 func (s *StubbedSuite) TestSbatchArgs(c *C) {
346         container := arvados.Container{
347                 UUID:               "123",
348                 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
349                 Priority:           1,
350         }
351
352         for _, defaults := range [][]string{
353                 nil,
354                 {},
355                 {"--arg1=v1", "--arg2"},
356         } {
357                 c.Logf("%#v", defaults)
358                 s.disp.SbatchArguments = defaults
359
360                 args, err := s.disp.sbatchArgs(container)
361                 c.Check(args, DeepEquals, append(defaults, "--job-name=123", "--nice=10000", "--mem=239", "--cpus-per-task=2", "--tmp=0"))
362                 c.Check(err, IsNil)
363         }
364 }
365
366 func (s *StubbedSuite) TestSbatchInstanceTypeConstraint(c *C) {
367         container := arvados.Container{
368                 UUID:               "123",
369                 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
370                 Priority:           1,
371         }
372
373         for _, trial := range []struct {
374                 types      map[string]arvados.InstanceType
375                 sbatchArgs []string
376                 err        error
377         }{
378                 // Choose node type => use --constraint arg
379                 {
380                         types: map[string]arvados.InstanceType{
381                                 "a1.tiny":   {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
382                                 "a1.small":  {Name: "a1.small", Price: 0.04, RAM: 256000000, VCPUs: 2},
383                                 "a1.medium": {Name: "a1.medium", Price: 0.08, RAM: 512000000, VCPUs: 4},
384                                 "a1.large":  {Name: "a1.large", Price: 0.16, RAM: 1024000000, VCPUs: 8},
385                         },
386                         sbatchArgs: []string{"--constraint=instancetype=a1.medium"},
387                 },
388                 // No node types configured => no slurm constraint
389                 {
390                         types:      nil,
391                         sbatchArgs: []string{"--mem=239", "--cpus-per-task=2", "--tmp=0"},
392                 },
393                 // No node type is big enough => error
394                 {
395                         types: map[string]arvados.InstanceType{
396                                 "a1.tiny": {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
397                         },
398                         err: dispatchcloud.ConstraintsNotSatisfiableError{},
399                 },
400         } {
401                 c.Logf("%#v", trial)
402                 s.disp.cluster = &arvados.Cluster{InstanceTypes: trial.types}
403
404                 args, err := s.disp.sbatchArgs(container)
405                 c.Check(err == nil, Equals, trial.err == nil)
406                 if trial.err == nil {
407                         c.Check(args, DeepEquals, append([]string{"--job-name=123", "--nice=10000"}, trial.sbatchArgs...))
408                 } else {
409                         c.Check(len(err.(dispatchcloud.ConstraintsNotSatisfiableError).AvailableTypes), Equals, len(trial.types))
410                 }
411         }
412 }
413
414 func (s *StubbedSuite) TestSbatchPartition(c *C) {
415         container := arvados.Container{
416                 UUID:                 "123",
417                 RuntimeConstraints:   arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 1},
418                 SchedulingParameters: arvados.SchedulingParameters{Partitions: []string{"blurb", "b2"}},
419                 Priority:             1,
420         }
421
422         args, err := s.disp.sbatchArgs(container)
423         c.Check(args, DeepEquals, []string{
424                 "--job-name=123", "--nice=10000",
425                 "--mem=239", "--cpus-per-task=1", "--tmp=0",
426                 "--partition=blurb,b2",
427         })
428         c.Check(err, IsNil)
429 }