13959: Merge branch 'master' into 13959-timeouts-and-logging
[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         "net/http"
15         "net/http/httptest"
16         "os"
17         "os/exec"
18         "strings"
19         "testing"
20         "time"
21
22         "git.curoverse.com/arvados.git/lib/dispatchcloud"
23         "git.curoverse.com/arvados.git/sdk/go/arvados"
24         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
25         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
26         "git.curoverse.com/arvados.git/sdk/go/dispatch"
27         "github.com/Sirupsen/logrus"
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{
142                 Logger: logrus.StandardLogger(),
143                 Period: 500 * time.Millisecond,
144                 Slurm:  s.disp.slurm,
145         }
146
147         err = s.disp.Dispatcher.Run(ctx)
148         <-doneRun
149         c.Assert(err, Equals, context.Canceled)
150
151         s.disp.sqCheck.Stop()
152
153         c.Check(s.slurm.didBatch, DeepEquals, expectBatch)
154
155         // There should be no queued containers now
156         err = arv.List("containers", params, &containers)
157         c.Check(err, IsNil)
158         c.Check(len(containers.Items), Equals, 0)
159
160         // Previously "Queued" container should now be in "Complete" state
161         var container arvados.Container
162         err = arv.Get("containers", "zzzzz-dz642-queuedcontainer", nil, &container)
163         c.Check(err, IsNil)
164         return container
165 }
166
167 func (s *IntegrationSuite) TestNormal(c *C) {
168         s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
169         container := s.integrationTest(c,
170                 nil,
171                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
172                         dispatcher.UpdateState(container.UUID, dispatch.Running)
173                         time.Sleep(3 * time.Second)
174                         dispatcher.UpdateState(container.UUID, dispatch.Complete)
175                 })
176         c.Check(container.State, Equals, arvados.ContainerStateComplete)
177 }
178
179 func (s *IntegrationSuite) TestCancel(c *C) {
180         s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
181         readyToCancel := make(chan bool)
182         s.slurm.onCancel = func() { <-readyToCancel }
183         container := s.integrationTest(c,
184                 nil,
185                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
186                         dispatcher.UpdateState(container.UUID, dispatch.Running)
187                         time.Sleep(time.Second)
188                         dispatcher.Arv.Update("containers", container.UUID,
189                                 arvadosclient.Dict{
190                                         "container": arvadosclient.Dict{"priority": 0}},
191                                 nil)
192                         readyToCancel <- true
193                         close(readyToCancel)
194                 })
195         c.Check(container.State, Equals, arvados.ContainerStateCancelled)
196         c.Check(len(s.slurm.didCancel) > 1, Equals, true)
197         c.Check(s.slurm.didCancel[:2], DeepEquals, []string{"zzzzz-dz642-queuedcontainer", "zzzzz-dz642-queuedcontainer"})
198 }
199
200 func (s *IntegrationSuite) TestMissingFromSqueue(c *C) {
201         container := s.integrationTest(c,
202                 [][]string{{
203                         fmt.Sprintf("--job-name=%s", "zzzzz-dz642-queuedcontainer"),
204                         fmt.Sprintf("--nice=%d", 10000),
205                         fmt.Sprintf("--mem=%d", 11445),
206                         fmt.Sprintf("--cpus-per-task=%d", 4),
207                         fmt.Sprintf("--tmp=%d", 45777),
208                 }},
209                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
210                         dispatcher.UpdateState(container.UUID, dispatch.Running)
211                         time.Sleep(3 * time.Second)
212                         dispatcher.UpdateState(container.UUID, dispatch.Complete)
213                 })
214         c.Check(container.State, Equals, arvados.ContainerStateCancelled)
215 }
216
217 func (s *IntegrationSuite) TestSbatchFail(c *C) {
218         s.slurm = slurmFake{errBatch: errors.New("something terrible happened")}
219         container := s.integrationTest(c,
220                 [][]string{{"--job-name=zzzzz-dz642-queuedcontainer", "--nice=10000", "--mem=11445", "--cpus-per-task=4", "--tmp=45777"}},
221                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
222                         dispatcher.UpdateState(container.UUID, dispatch.Running)
223                         dispatcher.UpdateState(container.UUID, dispatch.Complete)
224                 })
225         c.Check(container.State, Equals, arvados.ContainerStateComplete)
226
227         arv, err := arvadosclient.MakeArvadosClient()
228         c.Assert(err, IsNil)
229
230         var ll arvados.LogList
231         err = arv.List("logs", arvadosclient.Dict{"filters": [][]string{
232                 {"object_uuid", "=", container.UUID},
233                 {"event_type", "=", "dispatch"},
234         }}, &ll)
235         c.Assert(err, IsNil)
236         c.Assert(len(ll.Items), Equals, 1)
237 }
238
239 type StubbedSuite struct {
240         disp Dispatcher
241 }
242
243 func (s *StubbedSuite) SetUpTest(c *C) {
244         s.disp = Dispatcher{}
245         s.disp.setup()
246 }
247
248 func (s *StubbedSuite) TestAPIErrorGettingContainers(c *C) {
249         apiStubResponses := make(map[string]arvadostest.StubResponse)
250         apiStubResponses["/arvados/v1/api_client_authorizations/current"] = arvadostest.StubResponse{200, `{"uuid":"` + arvadostest.Dispatch1AuthUUID + `"}`}
251         apiStubResponses["/arvados/v1/containers"] = arvadostest.StubResponse{500, string(`{}`)}
252
253         s.testWithServerStub(c, apiStubResponses, "echo", "error getting count of containers")
254 }
255
256 func (s *StubbedSuite) testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubResponse, crunchCmd string, expected string) {
257         apiStub := arvadostest.ServerStub{apiStubResponses}
258
259         api := httptest.NewServer(&apiStub)
260         defer api.Close()
261
262         arv := &arvadosclient.ArvadosClient{
263                 Scheme:    "http",
264                 ApiServer: api.URL[7:],
265                 ApiToken:  "abc123",
266                 Client:    &http.Client{Transport: &http.Transport{}},
267                 Retries:   0,
268         }
269
270         buf := bytes.NewBuffer(nil)
271         logrus.SetOutput(io.MultiWriter(buf, os.Stderr))
272         defer logrus.SetOutput(os.Stderr)
273
274         s.disp.CrunchRunCommand = []string{crunchCmd}
275
276         ctx, cancel := context.WithCancel(context.Background())
277         dispatcher := dispatch.Dispatcher{
278                 Arv:        arv,
279                 PollPeriod: time.Second,
280                 RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
281                         go func() {
282                                 time.Sleep(time.Second)
283                                 disp.UpdateState(ctr.UUID, dispatch.Running)
284                                 disp.UpdateState(ctr.UUID, dispatch.Complete)
285                         }()
286                         s.disp.runContainer(disp, ctr, status)
287                         cancel()
288                 },
289         }
290
291         go func() {
292                 for i := 0; i < 80 && !strings.Contains(buf.String(), expected); i++ {
293                         time.Sleep(100 * time.Millisecond)
294                 }
295                 cancel()
296         }()
297
298         err := dispatcher.Run(ctx)
299         c.Assert(err, Equals, context.Canceled)
300
301         c.Check(buf.String(), Matches, `(?ms).*`+expected+`.*`)
302 }
303
304 func (s *StubbedSuite) TestNoSuchConfigFile(c *C) {
305         err := s.disp.readConfig("/nosuchdir89j7879/8hjwr7ojgyy7")
306         c.Assert(err, NotNil)
307 }
308
309 func (s *StubbedSuite) TestBadSbatchArgsConfig(c *C) {
310         tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
311         c.Check(err, IsNil)
312         defer os.Remove(tmpfile.Name())
313
314         _, err = tmpfile.Write([]byte(`{"SbatchArguments": "oops this is not a string array"}`))
315         c.Check(err, IsNil)
316
317         err = s.disp.readConfig(tmpfile.Name())
318         c.Assert(err, NotNil)
319 }
320
321 func (s *StubbedSuite) TestNoSuchArgInConfigIgnored(c *C) {
322         tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
323         c.Check(err, IsNil)
324         defer os.Remove(tmpfile.Name())
325
326         _, err = tmpfile.Write([]byte(`{"NoSuchArg": "Nobody loves me, not one tiny hunk."}`))
327         c.Check(err, IsNil)
328
329         err = s.disp.readConfig(tmpfile.Name())
330         c.Assert(err, IsNil)
331         c.Check(0, Equals, len(s.disp.SbatchArguments))
332 }
333
334 func (s *StubbedSuite) TestReadConfig(c *C) {
335         tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
336         c.Check(err, IsNil)
337         defer os.Remove(tmpfile.Name())
338
339         args := []string{"--arg1=v1", "--arg2", "--arg3=v3"}
340         argsS := `{"SbatchArguments": ["--arg1=v1",  "--arg2", "--arg3=v3"]}`
341         _, err = tmpfile.Write([]byte(argsS))
342         c.Check(err, IsNil)
343
344         err = s.disp.readConfig(tmpfile.Name())
345         c.Assert(err, IsNil)
346         c.Check(args, DeepEquals, s.disp.SbatchArguments)
347 }
348
349 func (s *StubbedSuite) TestSbatchArgs(c *C) {
350         container := arvados.Container{
351                 UUID:               "123",
352                 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
353                 Priority:           1,
354         }
355
356         for _, defaults := range [][]string{
357                 nil,
358                 {},
359                 {"--arg1=v1", "--arg2"},
360         } {
361                 c.Logf("%#v", defaults)
362                 s.disp.SbatchArguments = defaults
363
364                 args, err := s.disp.sbatchArgs(container)
365                 c.Check(args, DeepEquals, append(defaults, "--job-name=123", "--nice=10000", "--mem=239", "--cpus-per-task=2", "--tmp=0"))
366                 c.Check(err, IsNil)
367         }
368 }
369
370 func (s *StubbedSuite) TestSbatchInstanceTypeConstraint(c *C) {
371         container := arvados.Container{
372                 UUID:               "123",
373                 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
374                 Priority:           1,
375         }
376
377         for _, trial := range []struct {
378                 types      map[string]arvados.InstanceType
379                 sbatchArgs []string
380                 err        error
381         }{
382                 // Choose node type => use --constraint arg
383                 {
384                         types: map[string]arvados.InstanceType{
385                                 "a1.tiny":   {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
386                                 "a1.small":  {Name: "a1.small", Price: 0.04, RAM: 256000000, VCPUs: 2},
387                                 "a1.medium": {Name: "a1.medium", Price: 0.08, RAM: 512000000, VCPUs: 4},
388                                 "a1.large":  {Name: "a1.large", Price: 0.16, RAM: 1024000000, VCPUs: 8},
389                         },
390                         sbatchArgs: []string{"--constraint=instancetype=a1.medium"},
391                 },
392                 // No node types configured => no slurm constraint
393                 {
394                         types:      nil,
395                         sbatchArgs: []string{"--mem=239", "--cpus-per-task=2", "--tmp=0"},
396                 },
397                 // No node type is big enough => error
398                 {
399                         types: map[string]arvados.InstanceType{
400                                 "a1.tiny": {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
401                         },
402                         err: dispatchcloud.ConstraintsNotSatisfiableError{},
403                 },
404         } {
405                 c.Logf("%#v", trial)
406                 s.disp.cluster = &arvados.Cluster{InstanceTypes: trial.types}
407
408                 args, err := s.disp.sbatchArgs(container)
409                 c.Check(err == nil, Equals, trial.err == nil)
410                 if trial.err == nil {
411                         c.Check(args, DeepEquals, append([]string{"--job-name=123", "--nice=10000"}, trial.sbatchArgs...))
412                 } else {
413                         c.Check(len(err.(dispatchcloud.ConstraintsNotSatisfiableError).AvailableTypes), Equals, len(trial.types))
414                 }
415         }
416 }
417
418 func (s *StubbedSuite) TestSbatchPartition(c *C) {
419         container := arvados.Container{
420                 UUID:                 "123",
421                 RuntimeConstraints:   arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 1},
422                 SchedulingParameters: arvados.SchedulingParameters{Partitions: []string{"blurb", "b2"}},
423                 Priority:             1,
424         }
425
426         args, err := s.disp.sbatchArgs(container)
427         c.Check(args, DeepEquals, []string{
428                 "--job-name=123", "--nice=10000",
429                 "--mem=239", "--cpus-per-task=1", "--tmp=0",
430                 "--partition=blurb,b2",
431         })
432         c.Check(err, IsNil)
433 }