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