1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
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 {
63 // If non-nil, run this func during the 2nd+ call to Cancel()
65 // Error returned by Batch()
69 func (sf *slurmFake) Batch(script io.Reader, args []string) error {
70 sf.didBatch = append(sf.didBatch, args)
74 func (sf *slurmFake) QueueCommand(args []string) *exec.Cmd {
75 return exec.Command("echo", sf.queue)
78 func (sf *slurmFake) Release(name string) error {
79 sf.didRelease = append(sf.didRelease, name)
83 func (sf *slurmFake) Renice(name string, nice int64) error {
84 sf.didRenice = append(sf.didRenice, []string{name, fmt.Sprintf("%d", nice)})
88 func (sf *slurmFake) Cancel(name string) error {
89 sf.didCancel = append(sf.didCancel, name)
90 if len(sf.didCancel) == 1 {
91 // simulate error on first attempt
92 return errors.New("something terrible happened")
94 if sf.onCancel != nil {
100 func (s *IntegrationSuite) integrationTest(c *C,
101 expectBatch [][]string,
102 runContainer func(*dispatch.Dispatcher, arvados.Container)) arvados.Container {
103 arvadostest.ResetEnv()
105 arv, err := arvadosclient.MakeArvadosClient()
108 // There should be one queued container
109 params := arvadosclient.Dict{
110 "filters": [][]string{{"state", "=", "Queued"}},
112 var containers arvados.ContainerList
113 err = arv.List("containers", params, &containers)
115 c.Check(len(containers.Items), Equals, 1)
117 s.disp.CrunchRunCommand = []string{"echo"}
119 ctx, cancel := context.WithCancel(context.Background())
120 doneRun := make(chan struct{})
122 s.disp.Dispatcher = &dispatch.Dispatcher{
124 PollPeriod: time.Second,
125 RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
127 runContainer(disp, ctr)
129 doneRun <- struct{}{}
131 s.disp.runContainer(disp, ctr, status)
136 s.disp.slurm = &s.slurm
137 s.disp.sqCheck = &SqueueChecker{Period: 500 * time.Millisecond, Slurm: s.disp.slurm}
139 err = s.disp.Dispatcher.Run(ctx)
141 c.Assert(err, Equals, context.Canceled)
143 s.disp.sqCheck.Stop()
145 c.Check(s.slurm.didBatch, DeepEquals, expectBatch)
147 // There should be no queued containers now
148 err = arv.List("containers", params, &containers)
150 c.Check(len(containers.Items), Equals, 0)
152 // Previously "Queued" container should now be in "Complete" state
153 var container arvados.Container
154 err = arv.Get("containers", "zzzzz-dz642-queuedcontainer", nil, &container)
159 func (s *IntegrationSuite) TestNormal(c *C) {
160 s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
161 container := s.integrationTest(c,
163 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
164 dispatcher.UpdateState(container.UUID, dispatch.Running)
165 time.Sleep(3 * time.Second)
166 dispatcher.UpdateState(container.UUID, dispatch.Complete)
168 c.Check(container.State, Equals, arvados.ContainerStateComplete)
171 func (s *IntegrationSuite) TestCancel(c *C) {
172 s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
173 readyToCancel := make(chan bool)
174 s.slurm.onCancel = func() { <-readyToCancel }
175 container := s.integrationTest(c,
177 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
178 dispatcher.UpdateState(container.UUID, dispatch.Running)
179 time.Sleep(time.Second)
180 dispatcher.Arv.Update("containers", container.UUID,
182 "container": arvadosclient.Dict{"priority": 0}},
184 readyToCancel <- true
187 c.Check(container.State, Equals, arvados.ContainerStateCancelled)
188 c.Check(len(s.slurm.didCancel) > 1, Equals, true)
189 c.Check(s.slurm.didCancel[:2], DeepEquals, []string{"zzzzz-dz642-queuedcontainer", "zzzzz-dz642-queuedcontainer"})
192 func (s *IntegrationSuite) TestMissingFromSqueue(c *C) {
193 container := s.integrationTest(c,
195 fmt.Sprintf("--job-name=%s", "zzzzz-dz642-queuedcontainer"),
196 fmt.Sprintf("--nice=%d", 10000),
197 fmt.Sprintf("--mem=%d", 11445),
198 fmt.Sprintf("--cpus-per-task=%d", 4),
199 fmt.Sprintf("--tmp=%d", 45777),
201 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
202 dispatcher.UpdateState(container.UUID, dispatch.Running)
203 time.Sleep(3 * time.Second)
204 dispatcher.UpdateState(container.UUID, dispatch.Complete)
206 c.Check(container.State, Equals, arvados.ContainerStateCancelled)
209 func (s *IntegrationSuite) TestSbatchFail(c *C) {
210 s.slurm = slurmFake{errBatch: errors.New("something terrible happened")}
211 container := s.integrationTest(c,
212 [][]string{{"--job-name=zzzzz-dz642-queuedcontainer", "--nice=10000", "--mem=11445", "--cpus-per-task=4", "--tmp=45777"}},
213 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
214 dispatcher.UpdateState(container.UUID, dispatch.Running)
215 dispatcher.UpdateState(container.UUID, dispatch.Complete)
217 c.Check(container.State, Equals, arvados.ContainerStateComplete)
219 arv, err := arvadosclient.MakeArvadosClient()
222 var ll arvados.LogList
223 err = arv.List("logs", arvadosclient.Dict{"filters": [][]string{
224 {"object_uuid", "=", container.UUID},
225 {"event_type", "=", "dispatch"},
228 c.Assert(len(ll.Items), Equals, 1)
231 type StubbedSuite struct {
235 func (s *StubbedSuite) SetUpTest(c *C) {
236 s.disp = Dispatcher{}
240 func (s *StubbedSuite) TestAPIErrorGettingContainers(c *C) {
241 apiStubResponses := make(map[string]arvadostest.StubResponse)
242 apiStubResponses["/arvados/v1/api_client_authorizations/current"] = arvadostest.StubResponse{200, `{"uuid":"` + arvadostest.Dispatch1AuthUUID + `"}`}
243 apiStubResponses["/arvados/v1/containers"] = arvadostest.StubResponse{500, string(`{}`)}
245 s.testWithServerStub(c, apiStubResponses, "echo", "Error getting list of containers")
248 func (s *StubbedSuite) testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubResponse, crunchCmd string, expected string) {
249 apiStub := arvadostest.ServerStub{apiStubResponses}
251 api := httptest.NewServer(&apiStub)
254 arv := &arvadosclient.ArvadosClient{
256 ApiServer: api.URL[7:],
258 Client: &http.Client{Transport: &http.Transport{}},
262 buf := bytes.NewBuffer(nil)
263 log.SetOutput(io.MultiWriter(buf, os.Stderr))
264 defer log.SetOutput(os.Stderr)
266 s.disp.CrunchRunCommand = []string{crunchCmd}
268 ctx, cancel := context.WithCancel(context.Background())
269 dispatcher := dispatch.Dispatcher{
271 PollPeriod: time.Second,
272 RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
274 time.Sleep(time.Second)
275 disp.UpdateState(ctr.UUID, dispatch.Running)
276 disp.UpdateState(ctr.UUID, dispatch.Complete)
278 s.disp.runContainer(disp, ctr, status)
284 for i := 0; i < 80 && !strings.Contains(buf.String(), expected); i++ {
285 time.Sleep(100 * time.Millisecond)
290 err := dispatcher.Run(ctx)
291 c.Assert(err, Equals, context.Canceled)
293 c.Check(buf.String(), Matches, `(?ms).*`+expected+`.*`)
296 func (s *StubbedSuite) TestNoSuchConfigFile(c *C) {
297 err := s.disp.readConfig("/nosuchdir89j7879/8hjwr7ojgyy7")
298 c.Assert(err, NotNil)
301 func (s *StubbedSuite) TestBadSbatchArgsConfig(c *C) {
302 tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
304 defer os.Remove(tmpfile.Name())
306 _, err = tmpfile.Write([]byte(`{"SbatchArguments": "oops this is not a string array"}`))
309 err = s.disp.readConfig(tmpfile.Name())
310 c.Assert(err, NotNil)
313 func (s *StubbedSuite) TestNoSuchArgInConfigIgnored(c *C) {
314 tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
316 defer os.Remove(tmpfile.Name())
318 _, err = tmpfile.Write([]byte(`{"NoSuchArg": "Nobody loves me, not one tiny hunk."}`))
321 err = s.disp.readConfig(tmpfile.Name())
323 c.Check(0, Equals, len(s.disp.SbatchArguments))
326 func (s *StubbedSuite) TestReadConfig(c *C) {
327 tmpfile, err := ioutil.TempFile(os.TempDir(), "config")
329 defer os.Remove(tmpfile.Name())
331 args := []string{"--arg1=v1", "--arg2", "--arg3=v3"}
332 argsS := `{"SbatchArguments": ["--arg1=v1", "--arg2", "--arg3=v3"]}`
333 _, err = tmpfile.Write([]byte(argsS))
336 err = s.disp.readConfig(tmpfile.Name())
338 c.Check(args, DeepEquals, s.disp.SbatchArguments)
341 func (s *StubbedSuite) TestSbatchArgs(c *C) {
342 container := arvados.Container{
344 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
348 for _, defaults := range [][]string{
351 {"--arg1=v1", "--arg2"},
353 c.Logf("%#v", defaults)
354 s.disp.SbatchArguments = defaults
356 args, err := s.disp.sbatchArgs(container)
357 c.Check(args, DeepEquals, append(defaults, "--job-name=123", "--nice=10000", "--mem=239", "--cpus-per-task=2", "--tmp=0"))
362 func (s *StubbedSuite) TestSbatchInstanceTypeConstraint(c *C) {
363 container := arvados.Container{
365 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
369 for _, trial := range []struct {
370 types []arvados.InstanceType
374 // Choose node type => use --constraint arg
376 types: []arvados.InstanceType{
377 {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
378 {Name: "a1.small", Price: 0.04, RAM: 256000000, VCPUs: 2},
379 {Name: "a1.medium", Price: 0.08, RAM: 512000000, VCPUs: 4},
380 {Name: "a1.large", Price: 0.16, RAM: 1024000000, VCPUs: 8},
382 sbatchArgs: []string{"--constraint=instancetype=a1.medium"},
384 // No node types configured => no slurm constraint
387 sbatchArgs: []string{"--mem=239", "--cpus-per-task=2", "--tmp=0"},
389 // No node type is big enough => error
391 types: []arvados.InstanceType{
392 {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
394 err: dispatchcloud.ConstraintsNotSatisfiableError{},
398 s.disp.cluster = &arvados.Cluster{InstanceTypes: trial.types}
400 args, err := s.disp.sbatchArgs(container)
401 c.Check(err == nil, Equals, trial.err == nil)
402 if trial.err == nil {
403 c.Check(args, DeepEquals, append([]string{"--job-name=123", "--nice=10000"}, trial.sbatchArgs...))
405 c.Check(len(err.(dispatchcloud.ConstraintsNotSatisfiableError).AvailableTypes), Equals, len(trial.types))
410 func (s *StubbedSuite) TestSbatchPartition(c *C) {
411 container := arvados.Container{
413 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 1},
414 SchedulingParameters: arvados.SchedulingParameters{Partitions: []string{"blurb", "b2"}},
418 args, err := s.disp.sbatchArgs(container)
419 c.Check(args, DeepEquals, []string{
420 "--job-name=123", "--nice=10000",
421 "--mem=239", "--cpus-per-task=1", "--tmp=0",
422 "--partition=blurb,b2",