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