Update documentation about get_anonymous_user_token.rb to prevent duplicates
[arvados.git] / services / crunch-dispatch-slurm / crunch-dispatch-slurm_test.go
1 package main
2
3 import (
4         "bytes"
5         "fmt"
6         "git.curoverse.com/arvados.git/sdk/go/arvados"
7         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
8         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
9         "git.curoverse.com/arvados.git/sdk/go/dispatch"
10         "io"
11         "io/ioutil"
12         "log"
13         "net/http"
14         "net/http/httptest"
15         "os"
16         "os/exec"
17         "strings"
18         "testing"
19         "time"
20
21         . "gopkg.in/check.v1"
22 )
23
24 // Gocheck boilerplate
25 func Test(t *testing.T) {
26         TestingT(t)
27 }
28
29 var _ = Suite(&TestSuite{})
30 var _ = Suite(&MockArvadosServerSuite{})
31
32 type TestSuite struct{}
33 type MockArvadosServerSuite struct{}
34
35 var initialArgs []string
36
37 func (s *TestSuite) SetUpSuite(c *C) {
38         initialArgs = os.Args
39 }
40
41 func (s *TestSuite) TearDownSuite(c *C) {
42 }
43
44 func (s *TestSuite) SetUpTest(c *C) {
45         args := []string{"crunch-dispatch-slurm"}
46         os.Args = args
47
48         arvadostest.StartAPI()
49         os.Setenv("ARVADOS_API_TOKEN", arvadostest.Dispatch1Token)
50 }
51
52 func (s *TestSuite) TearDownTest(c *C) {
53         os.Args = initialArgs
54         arvadostest.StopAPI()
55 }
56
57 func (s *MockArvadosServerSuite) TearDownTest(c *C) {
58         arvadostest.ResetEnv()
59 }
60
61 func (s *TestSuite) TestIntegrationNormal(c *C) {
62         container := s.integrationTest(c, func() *exec.Cmd { return exec.Command("echo", "zzzzz-dz642-queuedcontainer") },
63                 []string(nil),
64                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
65                         dispatcher.UpdateState(container.UUID, dispatch.Running)
66                         time.Sleep(3 * time.Second)
67                         dispatcher.UpdateState(container.UUID, dispatch.Complete)
68                 })
69         c.Check(container.State, Equals, arvados.ContainerStateComplete)
70 }
71
72 func (s *TestSuite) TestIntegrationCancel(c *C) {
73
74         // Override sbatchCmd
75         var scancelCmdLine []string
76         defer func(orig func(arvados.Container) *exec.Cmd) {
77                 scancelCmd = orig
78         }(scancelCmd)
79         scancelCmd = func(container arvados.Container) *exec.Cmd {
80                 scancelCmdLine = scancelFunc(container).Args
81                 return exec.Command("echo")
82         }
83
84         container := s.integrationTest(c, func() *exec.Cmd { return exec.Command("echo", "zzzzz-dz642-queuedcontainer") },
85                 []string(nil),
86                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
87                         dispatcher.UpdateState(container.UUID, dispatch.Running)
88                         time.Sleep(1 * time.Second)
89                         dispatcher.Arv.Update("containers", container.UUID,
90                                 arvadosclient.Dict{
91                                         "container": arvadosclient.Dict{"priority": 0}},
92                                 nil)
93                 })
94         c.Check(container.State, Equals, arvados.ContainerStateCancelled)
95         c.Check(scancelCmdLine, DeepEquals, []string{"scancel", "--name=zzzzz-dz642-queuedcontainer"})
96 }
97
98 func (s *TestSuite) TestIntegrationMissingFromSqueue(c *C) {
99         container := s.integrationTest(c, func() *exec.Cmd { return exec.Command("echo") }, []string{"sbatch", "--share",
100                 fmt.Sprintf("--job-name=%s", "zzzzz-dz642-queuedcontainer"),
101                 fmt.Sprintf("--mem-per-cpu=%d", 2862),
102                 fmt.Sprintf("--cpus-per-task=%d", 4)},
103                 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
104                         dispatcher.UpdateState(container.UUID, dispatch.Running)
105                         time.Sleep(3 * time.Second)
106                         dispatcher.UpdateState(container.UUID, dispatch.Complete)
107                 })
108         c.Check(container.State, Equals, arvados.ContainerStateCancelled)
109 }
110
111 func (s *TestSuite) integrationTest(c *C,
112         newSqueueCmd func() *exec.Cmd,
113         sbatchCmdComps []string,
114         runContainer func(*dispatch.Dispatcher, arvados.Container)) arvados.Container {
115         arvadostest.ResetEnv()
116
117         arv, err := arvadosclient.MakeArvadosClient()
118         c.Assert(err, IsNil)
119
120         var sbatchCmdLine []string
121
122         // Override sbatchCmd
123         defer func(orig func(arvados.Container) *exec.Cmd) {
124                 sbatchCmd = orig
125         }(sbatchCmd)
126         sbatchCmd = func(container arvados.Container) *exec.Cmd {
127                 sbatchCmdLine = sbatchFunc(container).Args
128                 return exec.Command("sh")
129         }
130
131         // Override squeueCmd
132         defer func(orig func() *exec.Cmd) {
133                 squeueCmd = orig
134         }(squeueCmd)
135         squeueCmd = newSqueueCmd
136
137         // There should be no queued containers now
138         params := arvadosclient.Dict{
139                 "filters": [][]string{{"state", "=", "Queued"}},
140         }
141         var containers arvados.ContainerList
142         err = arv.List("containers", params, &containers)
143         c.Check(err, IsNil)
144         c.Check(len(containers.Items), Equals, 1)
145
146         theConfig.CrunchRunCommand = []string{"echo"}
147
148         doneProcessing := make(chan struct{})
149         dispatcher := dispatch.Dispatcher{
150                 Arv:          arv,
151                 PollInterval: time.Duration(1) * time.Second,
152                 RunContainer: func(dispatcher *dispatch.Dispatcher,
153                         container arvados.Container,
154                         status chan arvados.Container) {
155                         go runContainer(dispatcher, container)
156                         run(dispatcher, container, status)
157                         doneProcessing <- struct{}{}
158                 },
159                 DoneProcessing: doneProcessing}
160
161         squeueUpdater.StartMonitor(time.Duration(500) * time.Millisecond)
162
163         err = dispatcher.RunDispatcher()
164         c.Assert(err, IsNil)
165
166         squeueUpdater.Done()
167
168         c.Check(sbatchCmdLine, DeepEquals, sbatchCmdComps)
169
170         // There should be no queued containers now
171         err = arv.List("containers", params, &containers)
172         c.Check(err, IsNil)
173         c.Check(len(containers.Items), Equals, 0)
174
175         // Previously "Queued" container should now be in "Complete" state
176         var container arvados.Container
177         err = arv.Get("containers", "zzzzz-dz642-queuedcontainer", nil, &container)
178         c.Check(err, IsNil)
179         return container
180 }
181
182 func (s *MockArvadosServerSuite) TestAPIErrorGettingContainers(c *C) {
183         apiStubResponses := make(map[string]arvadostest.StubResponse)
184         apiStubResponses["/arvados/v1/api_client_authorizations/current"] = arvadostest.StubResponse{200, `{"uuid":"` + arvadostest.Dispatch1AuthUUID + `"}`}
185         apiStubResponses["/arvados/v1/containers"] = arvadostest.StubResponse{500, string(`{}`)}
186
187         testWithServerStub(c, apiStubResponses, "echo", "Error getting list of containers")
188 }
189
190 func testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubResponse, crunchCmd string, expected string) {
191         apiStub := arvadostest.ServerStub{apiStubResponses}
192
193         api := httptest.NewServer(&apiStub)
194         defer api.Close()
195
196         arv := &arvadosclient.ArvadosClient{
197                 Scheme:    "http",
198                 ApiServer: api.URL[7:],
199                 ApiToken:  "abc123",
200                 Client:    &http.Client{Transport: &http.Transport{}},
201                 Retries:   0,
202         }
203
204         buf := bytes.NewBuffer(nil)
205         log.SetOutput(io.MultiWriter(buf, os.Stderr))
206         defer log.SetOutput(os.Stderr)
207
208         theConfig.CrunchRunCommand = []string{crunchCmd}
209
210         doneProcessing := make(chan struct{})
211         dispatcher := dispatch.Dispatcher{
212                 Arv:          arv,
213                 PollInterval: time.Duration(1) * time.Second,
214                 RunContainer: func(dispatcher *dispatch.Dispatcher,
215                         container arvados.Container,
216                         status chan arvados.Container) {
217                         go func() {
218                                 time.Sleep(1 * time.Second)
219                                 dispatcher.UpdateState(container.UUID, dispatch.Running)
220                                 dispatcher.UpdateState(container.UUID, dispatch.Complete)
221                         }()
222                         run(dispatcher, container, status)
223                         doneProcessing <- struct{}{}
224                 },
225                 DoneProcessing: doneProcessing}
226
227         go func() {
228                 for i := 0; i < 80 && !strings.Contains(buf.String(), expected); i++ {
229                         time.Sleep(100 * time.Millisecond)
230                 }
231                 dispatcher.DoneProcessing <- struct{}{}
232         }()
233
234         err := dispatcher.RunDispatcher()
235         c.Assert(err, IsNil)
236
237         c.Check(buf.String(), Matches, `(?ms).*`+expected+`.*`)
238 }
239
240 func (s *MockArvadosServerSuite) TestNoSuchConfigFile(c *C) {
241         var config Config
242         err := readConfig(&config, "/nosuchdir89j7879/8hjwr7ojgyy7")
243         c.Assert(err, NotNil)
244 }
245
246 func (s *MockArvadosServerSuite) TestBadSbatchArgsConfig(c *C) {
247         var config Config
248
249         tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
250         c.Check(err, IsNil)
251         defer os.Remove(tmpfile.Name())
252
253         _, err = tmpfile.Write([]byte(`{"SbatchArguments": "oops this is not a string array"}`))
254         c.Check(err, IsNil)
255
256         err = readConfig(&config, tmpfile.Name())
257         c.Assert(err, NotNil)
258 }
259
260 func (s *MockArvadosServerSuite) TestNoSuchArgInConfigIgnored(c *C) {
261         var config Config
262
263         tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
264         c.Check(err, IsNil)
265         defer os.Remove(tmpfile.Name())
266
267         _, err = tmpfile.Write([]byte(`{"NoSuchArg": "Nobody loves me, not one tiny hunk."}`))
268         c.Check(err, IsNil)
269
270         err = readConfig(&config, tmpfile.Name())
271         c.Assert(err, IsNil)
272         c.Check(0, Equals, len(config.SbatchArguments))
273 }
274
275 func (s *MockArvadosServerSuite) TestReadConfig(c *C) {
276         var config Config
277
278         tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
279         c.Check(err, IsNil)
280         defer os.Remove(tmpfile.Name())
281
282         args := []string{"--arg1=v1", "--arg2", "--arg3=v3"}
283         argsS := `{"SbatchArguments": ["--arg1=v1",  "--arg2", "--arg3=v3"]}`
284         _, err = tmpfile.Write([]byte(argsS))
285         c.Check(err, IsNil)
286
287         err = readConfig(&config, tmpfile.Name())
288         c.Assert(err, IsNil)
289         c.Check(3, Equals, len(config.SbatchArguments))
290         c.Check(args, DeepEquals, config.SbatchArguments)
291 }
292
293 func (s *MockArvadosServerSuite) TestSbatchFuncWithNoConfigArgs(c *C) {
294         testSbatchFuncWithArgs(c, nil)
295 }
296
297 func (s *MockArvadosServerSuite) TestSbatchFuncWithEmptyConfigArgs(c *C) {
298         testSbatchFuncWithArgs(c, []string{})
299 }
300
301 func (s *MockArvadosServerSuite) TestSbatchFuncWithConfigArgs(c *C) {
302         testSbatchFuncWithArgs(c, []string{"--arg1=v1", "--arg2"})
303 }
304
305 func testSbatchFuncWithArgs(c *C, args []string) {
306         theConfig.SbatchArguments = append(theConfig.SbatchArguments, args...)
307
308         container := arvados.Container{UUID: "123", RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2}}
309         sbatchCmd := sbatchFunc(container)
310
311         var expected []string
312         expected = append(expected, "sbatch", "--share")
313         expected = append(expected, theConfig.SbatchArguments...)
314         expected = append(expected, "--job-name=123", "--mem-per-cpu=120", "--cpus-per-task=2")
315
316         c.Check(sbatchCmd.Args, DeepEquals, expected)
317 }
318
319 func (s *MockArvadosServerSuite) TestSbatchPartition(c *C) {
320         theConfig.SbatchArguments = nil
321         container := arvados.Container{UUID: "123", RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 1}, SchedulingParameters: arvados.SchedulingParameters{Partitions: []string{"blurb", "b2"}}}
322         sbatchCmd := sbatchFunc(container)
323
324         var expected []string
325         expected = append(expected, "sbatch", "--share")
326         expected = append(expected, "--job-name=123", "--mem-per-cpu=239", "--cpus-per-task=1", "--partition=blurb,b2")
327
328         c.Check(sbatchCmd.Args, DeepEquals, expected)
329 }