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