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