1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.curoverse.com/arvados.git/lib/dispatchcloud"
23 "git.curoverse.com/arvados.git/sdk/go/arvados"
24 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
25 "git.curoverse.com/arvados.git/sdk/go/arvadostest"
26 "git.curoverse.com/arvados.git/sdk/go/dispatch"
27 "github.com/Sirupsen/logrus"
31 // Gocheck boilerplate
32 func Test(t *testing.T) {
36 var _ = Suite(&IntegrationSuite{})
37 var _ = Suite(&StubbedSuite{})
39 type IntegrationSuite struct {
44 func (s *IntegrationSuite) SetUpTest(c *C) {
45 arvadostest.StartAPI()
46 os.Setenv("ARVADOS_API_TOKEN", arvadostest.Dispatch1Token)
52 func (s *IntegrationSuite) TearDownTest(c *C) {
53 arvadostest.ResetEnv()
57 type slurmFake struct {
64 // If non-nil, run this func during the 2nd+ call to Cancel()
66 // Error returned by Batch()
70 func (sf *slurmFake) Batch(script io.Reader, args []string) error {
71 sf.didBatch = append(sf.didBatch, args)
75 func (sf *slurmFake) QueueCommand(args []string) *exec.Cmd {
76 return exec.Command("echo", sf.queue)
79 func (sf *slurmFake) Release(name string) error {
80 sf.didRelease = append(sf.didRelease, name)
84 func (sf *slurmFake) Renice(name string, nice int64) error {
85 sf.didRenice = append(sf.didRenice, []string{name, fmt.Sprintf("%d", nice)})
86 if sf.rejectNice10K && nice > 10000 {
87 return errors.New("scontrol: error: Invalid nice value, must be between -10000 and 10000")
92 func (sf *slurmFake) Cancel(name string) error {
93 sf.didCancel = append(sf.didCancel, name)
94 if len(sf.didCancel) == 1 {
95 // simulate error on first attempt
96 return errors.New("something terrible happened")
98 if sf.onCancel != nil {
104 func (s *IntegrationSuite) integrationTest(c *C,
105 expectBatch [][]string,
106 runContainer func(*dispatch.Dispatcher, arvados.Container)) arvados.Container {
107 arvadostest.ResetEnv()
109 arv, err := arvadosclient.MakeArvadosClient()
112 // There should be one queued container
113 params := arvadosclient.Dict{
114 "filters": [][]string{{"state", "=", "Queued"}},
116 var containers arvados.ContainerList
117 err = arv.List("containers", params, &containers)
119 c.Assert(len(containers.Items), Equals, 1)
121 s.disp.CrunchRunCommand = []string{"echo"}
123 ctx, cancel := context.WithCancel(context.Background())
124 doneRun := make(chan struct{})
126 s.disp.Dispatcher = &dispatch.Dispatcher{
128 PollPeriod: time.Second,
129 RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
131 runContainer(disp, ctr)
133 doneRun <- struct{}{}
135 s.disp.runContainer(disp, ctr, status)
140 s.disp.slurm = &s.slurm
141 s.disp.sqCheck = &SqueueChecker{
142 Logger: logrus.StandardLogger(),
143 Period: 500 * time.Millisecond,
147 err = s.disp.Dispatcher.Run(ctx)
149 c.Assert(err, Equals, context.Canceled)
151 s.disp.sqCheck.Stop()
153 c.Check(s.slurm.didBatch, DeepEquals, expectBatch)
155 // There should be no queued containers now
156 err = arv.List("containers", params, &containers)
158 c.Check(len(containers.Items), Equals, 0)
160 // Previously "Queued" container should now be in "Complete" state
161 var container arvados.Container
162 err = arv.Get("containers", "zzzzz-dz642-queuedcontainer", nil, &container)
167 func (s *IntegrationSuite) TestNormal(c *C) {
168 s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
169 container := s.integrationTest(c,
171 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
172 dispatcher.UpdateState(container.UUID, dispatch.Running)
173 time.Sleep(3 * time.Second)
174 dispatcher.UpdateState(container.UUID, dispatch.Complete)
176 c.Check(container.State, Equals, arvados.ContainerStateComplete)
179 func (s *IntegrationSuite) TestCancel(c *C) {
180 s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
181 readyToCancel := make(chan bool)
182 s.slurm.onCancel = func() { <-readyToCancel }
183 container := s.integrationTest(c,
185 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
186 dispatcher.UpdateState(container.UUID, dispatch.Running)
187 time.Sleep(time.Second)
188 dispatcher.Arv.Update("containers", container.UUID,
190 "container": arvadosclient.Dict{"priority": 0}},
192 readyToCancel <- true
195 c.Check(container.State, Equals, arvados.ContainerStateCancelled)
196 c.Check(len(s.slurm.didCancel) > 1, Equals, true)
197 c.Check(s.slurm.didCancel[:2], DeepEquals, []string{"zzzzz-dz642-queuedcontainer", "zzzzz-dz642-queuedcontainer"})
200 func (s *IntegrationSuite) TestMissingFromSqueue(c *C) {
201 container := s.integrationTest(c,
203 fmt.Sprintf("--job-name=%s", "zzzzz-dz642-queuedcontainer"),
204 fmt.Sprintf("--nice=%d", 10000),
205 fmt.Sprintf("--mem=%d", 11445),
206 fmt.Sprintf("--cpus-per-task=%d", 4),
207 fmt.Sprintf("--tmp=%d", 45777),
209 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
210 dispatcher.UpdateState(container.UUID, dispatch.Running)
211 time.Sleep(3 * time.Second)
212 dispatcher.UpdateState(container.UUID, dispatch.Complete)
214 c.Check(container.State, Equals, arvados.ContainerStateCancelled)
217 func (s *IntegrationSuite) TestSbatchFail(c *C) {
218 s.slurm = slurmFake{errBatch: errors.New("something terrible happened")}
219 container := s.integrationTest(c,
220 [][]string{{"--job-name=zzzzz-dz642-queuedcontainer", "--nice=10000", "--mem=11445", "--cpus-per-task=4", "--tmp=45777"}},
221 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
222 dispatcher.UpdateState(container.UUID, dispatch.Running)
223 dispatcher.UpdateState(container.UUID, dispatch.Complete)
225 c.Check(container.State, Equals, arvados.ContainerStateComplete)
227 arv, err := arvadosclient.MakeArvadosClient()
230 var ll arvados.LogList
231 err = arv.List("logs", arvadosclient.Dict{"filters": [][]string{
232 {"object_uuid", "=", container.UUID},
233 {"event_type", "=", "dispatch"},
236 c.Assert(len(ll.Items), Equals, 1)
239 type StubbedSuite struct {
243 func (s *StubbedSuite) SetUpTest(c *C) {
244 s.disp = Dispatcher{}
248 func (s *StubbedSuite) TestAPIErrorGettingContainers(c *C) {
249 apiStubResponses := make(map[string]arvadostest.StubResponse)
250 apiStubResponses["/arvados/v1/api_client_authorizations/current"] = arvadostest.StubResponse{200, `{"uuid":"` + arvadostest.Dispatch1AuthUUID + `"}`}
251 apiStubResponses["/arvados/v1/containers"] = arvadostest.StubResponse{500, string(`{}`)}
253 s.testWithServerStub(c, apiStubResponses, "echo", "error getting count of containers")
256 func (s *StubbedSuite) testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubResponse, crunchCmd string, expected string) {
257 apiStub := arvadostest.ServerStub{apiStubResponses}
259 api := httptest.NewServer(&apiStub)
262 arv := &arvadosclient.ArvadosClient{
264 ApiServer: api.URL[7:],
266 Client: &http.Client{Transport: &http.Transport{}},
270 buf := bytes.NewBuffer(nil)
271 logrus.SetOutput(io.MultiWriter(buf, os.Stderr))
272 defer logrus.SetOutput(os.Stderr)
274 s.disp.CrunchRunCommand = []string{crunchCmd}
276 ctx, cancel := context.WithCancel(context.Background())
277 dispatcher := dispatch.Dispatcher{
279 PollPeriod: time.Second,
280 RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
282 time.Sleep(time.Second)
283 disp.UpdateState(ctr.UUID, dispatch.Running)
284 disp.UpdateState(ctr.UUID, dispatch.Complete)
286 s.disp.runContainer(disp, ctr, status)
292 for i := 0; i < 80 && !strings.Contains(buf.String(), expected); i++ {
293 time.Sleep(100 * time.Millisecond)
298 err := dispatcher.Run(ctx)
299 c.Assert(err, Equals, context.Canceled)
301 c.Check(buf.String(), Matches, `(?ms).*`+expected+`.*`)
304 func (s *StubbedSuite) TestNoSuchConfigFile(c *C) {
305 err := s.disp.readConfig("/nosuchdir89j7879/8hjwr7ojgyy7")
306 c.Assert(err, NotNil)
309 func (s *StubbedSuite) TestBadSbatchArgsConfig(c *C) {
310 tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
312 defer os.Remove(tmpfile.Name())
314 _, err = tmpfile.Write([]byte(`{"SbatchArguments": "oops this is not a string array"}`))
317 err = s.disp.readConfig(tmpfile.Name())
318 c.Assert(err, NotNil)
321 func (s *StubbedSuite) TestNoSuchArgInConfigIgnored(c *C) {
322 tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
324 defer os.Remove(tmpfile.Name())
326 _, err = tmpfile.Write([]byte(`{"NoSuchArg": "Nobody loves me, not one tiny hunk."}`))
329 err = s.disp.readConfig(tmpfile.Name())
331 c.Check(0, Equals, len(s.disp.SbatchArguments))
334 func (s *StubbedSuite) TestReadConfig(c *C) {
335 tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
337 defer os.Remove(tmpfile.Name())
339 args := []string{"--arg1=v1", "--arg2", "--arg3=v3"}
340 argsS := `{"SbatchArguments": ["--arg1=v1", "--arg2", "--arg3=v3"]}`
341 _, err = tmpfile.Write([]byte(argsS))
344 err = s.disp.readConfig(tmpfile.Name())
346 c.Check(args, DeepEquals, s.disp.SbatchArguments)
349 func (s *StubbedSuite) TestSbatchArgs(c *C) {
350 container := arvados.Container{
352 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
356 for _, defaults := range [][]string{
359 {"--arg1=v1", "--arg2"},
361 c.Logf("%#v", defaults)
362 s.disp.SbatchArguments = defaults
364 args, err := s.disp.sbatchArgs(container)
365 c.Check(args, DeepEquals, append(defaults, "--job-name=123", "--nice=10000", "--mem=239", "--cpus-per-task=2", "--tmp=0"))
370 func (s *StubbedSuite) TestSbatchInstanceTypeConstraint(c *C) {
371 container := arvados.Container{
373 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
377 for _, trial := range []struct {
378 types map[string]arvados.InstanceType
382 // Choose node type => use --constraint arg
384 types: map[string]arvados.InstanceType{
385 "a1.tiny": {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
386 "a1.small": {Name: "a1.small", Price: 0.04, RAM: 256000000, VCPUs: 2},
387 "a1.medium": {Name: "a1.medium", Price: 0.08, RAM: 512000000, VCPUs: 4},
388 "a1.large": {Name: "a1.large", Price: 0.16, RAM: 1024000000, VCPUs: 8},
390 sbatchArgs: []string{"--constraint=instancetype=a1.medium"},
392 // No node types configured => no slurm constraint
395 sbatchArgs: []string{"--mem=239", "--cpus-per-task=2", "--tmp=0"},
397 // No node type is big enough => error
399 types: map[string]arvados.InstanceType{
400 "a1.tiny": {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
402 err: dispatchcloud.ConstraintsNotSatisfiableError{},
406 s.disp.cluster = &arvados.Cluster{InstanceTypes: trial.types}
408 args, err := s.disp.sbatchArgs(container)
409 c.Check(err == nil, Equals, trial.err == nil)
410 if trial.err == nil {
411 c.Check(args, DeepEquals, append([]string{"--job-name=123", "--nice=10000"}, trial.sbatchArgs...))
413 c.Check(len(err.(dispatchcloud.ConstraintsNotSatisfiableError).AvailableTypes), Equals, len(trial.types))
418 func (s *StubbedSuite) TestSbatchPartition(c *C) {
419 container := arvados.Container{
421 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 1},
422 SchedulingParameters: arvados.SchedulingParameters{Partitions: []string{"blurb", "b2"}},
426 args, err := s.disp.sbatchArgs(container)
427 c.Check(args, DeepEquals, []string{
428 "--job-name=123", "--nice=10000",
429 "--mem=239", "--cpus-per-task=1", "--tmp=0",
430 "--partition=blurb,b2",