1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
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)
48 s.disp.cluster = &arvados.Cluster{}
53 func (s *IntegrationSuite) TearDownTest(c *C) {
54 arvadostest.ResetEnv()
58 type slurmFake struct {
65 // If non-nil, run this func during the 2nd+ call to Cancel()
67 // Error returned by Batch()
71 func (sf *slurmFake) Batch(script io.Reader, args []string) error {
72 sf.didBatch = append(sf.didBatch, args)
76 func (sf *slurmFake) QueueCommand(args []string) *exec.Cmd {
77 return exec.Command("echo", sf.queue)
80 func (sf *slurmFake) Release(name string) error {
81 sf.didRelease = append(sf.didRelease, name)
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")
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")
99 if sf.onCancel != nil {
105 func (s *IntegrationSuite) integrationTest(c *C,
106 expectBatch [][]string,
107 runContainer func(*dispatch.Dispatcher, arvados.Container)) arvados.Container {
108 arvadostest.ResetEnv()
110 arv, err := arvadosclient.MakeArvadosClient()
113 // There should be one queued container
114 params := arvadosclient.Dict{
115 "filters": [][]string{{"state", "=", "Queued"}},
117 var containers arvados.ContainerList
118 err = arv.List("containers", params, &containers)
120 c.Assert(len(containers.Items), Equals, 1)
122 s.disp.cluster.Containers.CrunchRunCommand = "echo"
124 ctx, cancel := context.WithCancel(context.Background())
125 doneRun := make(chan struct{})
127 s.disp.Dispatcher = &dispatch.Dispatcher{
129 PollPeriod: time.Second,
130 RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
132 runContainer(disp, ctr)
134 doneRun <- struct{}{}
136 s.disp.runContainer(disp, ctr, status)
141 s.disp.slurm = &s.slurm
142 s.disp.sqCheck = &SqueueChecker{
143 Logger: logrus.StandardLogger(),
144 Period: 500 * time.Millisecond,
148 err = s.disp.Dispatcher.Run(ctx)
150 c.Assert(err, Equals, context.Canceled)
152 s.disp.sqCheck.Stop()
154 c.Check(s.slurm.didBatch, DeepEquals, expectBatch)
156 // There should be no queued containers now
157 err = arv.List("containers", params, &containers)
159 c.Check(len(containers.Items), Equals, 0)
161 // Previously "Queued" container should now be in "Complete" state
162 var container arvados.Container
163 err = arv.Get("containers", "zzzzz-dz642-queuedcontainer", nil, &container)
168 func (s *IntegrationSuite) TestNormal(c *C) {
169 s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
170 container := s.integrationTest(c,
172 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
173 dispatcher.UpdateState(container.UUID, dispatch.Running)
174 time.Sleep(3 * time.Second)
175 dispatcher.UpdateState(container.UUID, dispatch.Complete)
177 c.Check(container.State, Equals, arvados.ContainerStateComplete)
180 func (s *IntegrationSuite) TestCancel(c *C) {
181 s.slurm = slurmFake{queue: "zzzzz-dz642-queuedcontainer 10000 100 PENDING Resources\n"}
182 readyToCancel := make(chan bool)
183 s.slurm.onCancel = func() { <-readyToCancel }
184 container := s.integrationTest(c,
186 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
187 dispatcher.UpdateState(container.UUID, dispatch.Running)
188 time.Sleep(time.Second)
189 dispatcher.Arv.Update("containers", container.UUID,
191 "container": arvadosclient.Dict{"priority": 0}},
193 readyToCancel <- true
196 c.Check(container.State, Equals, arvados.ContainerStateCancelled)
197 c.Check(len(s.slurm.didCancel) > 1, Equals, true)
198 c.Check(s.slurm.didCancel[:2], DeepEquals, []string{"zzzzz-dz642-queuedcontainer", "zzzzz-dz642-queuedcontainer"})
201 func (s *IntegrationSuite) TestMissingFromSqueue(c *C) {
202 container := s.integrationTest(c,
204 fmt.Sprintf("--job-name=%s", "zzzzz-dz642-queuedcontainer"),
205 fmt.Sprintf("--nice=%d", 10000),
207 fmt.Sprintf("--mem=%d", 11445),
208 fmt.Sprintf("--cpus-per-task=%d", 4),
209 fmt.Sprintf("--tmp=%d", 45777),
211 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
212 dispatcher.UpdateState(container.UUID, dispatch.Running)
213 time.Sleep(3 * time.Second)
214 dispatcher.UpdateState(container.UUID, dispatch.Complete)
216 c.Check(container.State, Equals, arvados.ContainerStateCancelled)
219 func (s *IntegrationSuite) TestSbatchFail(c *C) {
220 s.slurm = slurmFake{errBatch: errors.New("something terrible happened")}
221 container := s.integrationTest(c,
222 [][]string{{"--job-name=zzzzz-dz642-queuedcontainer", "--nice=10000", "--no-requeue", "--mem=11445", "--cpus-per-task=4", "--tmp=45777"}},
223 func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
224 dispatcher.UpdateState(container.UUID, dispatch.Running)
225 dispatcher.UpdateState(container.UUID, dispatch.Complete)
227 c.Check(container.State, Equals, arvados.ContainerStateComplete)
229 arv, err := arvadosclient.MakeArvadosClient()
232 var ll arvados.LogList
233 err = arv.List("logs", arvadosclient.Dict{"filters": [][]string{
234 {"object_uuid", "=", container.UUID},
235 {"event_type", "=", "dispatch"},
238 c.Assert(len(ll.Items), Equals, 1)
241 type StubbedSuite struct {
245 func (s *StubbedSuite) SetUpTest(c *C) {
246 s.disp = Dispatcher{}
247 s.disp.cluster = &arvados.Cluster{}
251 func (s *StubbedSuite) TestAPIErrorGettingContainers(c *C) {
252 apiStubResponses := make(map[string]arvadostest.StubResponse)
253 apiStubResponses["/arvados/v1/api_client_authorizations/current"] = arvadostest.StubResponse{200, `{"uuid":"` + arvadostest.Dispatch1AuthUUID + `"}`}
254 apiStubResponses["/arvados/v1/containers"] = arvadostest.StubResponse{500, string(`{}`)}
256 s.testWithServerStub(c, apiStubResponses, "echo", "error getting count of containers")
259 func (s *StubbedSuite) testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubResponse, crunchCmd string, expected string) {
260 apiStub := arvadostest.ServerStub{apiStubResponses}
262 api := httptest.NewServer(&apiStub)
265 arv := &arvadosclient.ArvadosClient{
267 ApiServer: api.URL[7:],
269 Client: &http.Client{Transport: &http.Transport{}},
273 buf := bytes.NewBuffer(nil)
274 logrus.SetOutput(io.MultiWriter(buf, os.Stderr))
275 defer logrus.SetOutput(os.Stderr)
277 s.disp.cluster.Containers.CrunchRunCommand = "crunchCmd"
279 ctx, cancel := context.WithCancel(context.Background())
280 dispatcher := dispatch.Dispatcher{
282 PollPeriod: time.Second,
283 RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
285 time.Sleep(time.Second)
286 disp.UpdateState(ctr.UUID, dispatch.Running)
287 disp.UpdateState(ctr.UUID, dispatch.Complete)
289 s.disp.runContainer(disp, ctr, status)
295 for i := 0; i < 80 && !strings.Contains(buf.String(), expected); i++ {
296 time.Sleep(100 * time.Millisecond)
301 err := dispatcher.Run(ctx)
302 c.Assert(err, Equals, context.Canceled)
304 c.Check(buf.String(), Matches, `(?ms).*`+expected+`.*`)
307 func (s *StubbedSuite) TestSbatchArgs(c *C) {
308 container := arvados.Container{
310 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
314 for _, defaults := range [][]string{
317 {"--arg1=v1", "--arg2"},
319 c.Logf("%#v", defaults)
320 s.disp.cluster.Containers.SLURM.SbatchArgumentsList = defaults
322 args, err := s.disp.sbatchArgs(container)
323 c.Check(args, DeepEquals, append(defaults, "--job-name=123", "--nice=10000", "--no-requeue", "--mem=239", "--cpus-per-task=2", "--tmp=0"))
328 func (s *StubbedSuite) TestSbatchInstanceTypeConstraint(c *C) {
329 container := arvados.Container{
331 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
335 for _, trial := range []struct {
336 types map[string]arvados.InstanceType
340 // Choose node type => use --constraint arg
342 types: map[string]arvados.InstanceType{
343 "a1.tiny": {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
344 "a1.small": {Name: "a1.small", Price: 0.04, RAM: 256000000, VCPUs: 2},
345 "a1.medium": {Name: "a1.medium", Price: 0.08, RAM: 512000000, VCPUs: 4},
346 "a1.large": {Name: "a1.large", Price: 0.16, RAM: 1024000000, VCPUs: 8},
348 sbatchArgs: []string{"--constraint=instancetype=a1.medium"},
350 // No node types configured => no slurm constraint
353 sbatchArgs: []string{"--mem=239", "--cpus-per-task=2", "--tmp=0"},
355 // No node type is big enough => error
357 types: map[string]arvados.InstanceType{
358 "a1.tiny": {Name: "a1.tiny", Price: 0.02, RAM: 128000000, VCPUs: 1},
360 err: dispatchcloud.ConstraintsNotSatisfiableError{},
364 s.disp.cluster = &arvados.Cluster{InstanceTypes: trial.types}
366 args, err := s.disp.sbatchArgs(container)
367 c.Check(err == nil, Equals, trial.err == nil)
368 if trial.err == nil {
369 c.Check(args, DeepEquals, append([]string{"--job-name=123", "--nice=10000", "--no-requeue"}, trial.sbatchArgs...))
371 c.Check(len(err.(dispatchcloud.ConstraintsNotSatisfiableError).AvailableTypes), Equals, len(trial.types))
376 func (s *StubbedSuite) TestSbatchPartition(c *C) {
377 container := arvados.Container{
379 RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 1},
380 SchedulingParameters: arvados.SchedulingParameters{Partitions: []string{"blurb", "b2"}},
384 args, err := s.disp.sbatchArgs(container)
385 c.Check(args, DeepEquals, []string{
386 "--job-name=123", "--nice=10000", "--no-requeue",
387 "--mem=239", "--cpus-per-task=1", "--tmp=0",
388 "--partition=blurb,b2",
393 func (s *StubbedSuite) TestLoadLegacyConfig(c *C) {
399 - https://example.com/keep1
400 - https://example.com/keep2
401 SbatchArguments: ["--foo", "bar"]
404 CrunchRunCommand: ["x-crunch-run", "--cgroup-parent-subsystem=memory"]
405 ReserveExtraRAM: 12345
409 tmpfile, err := ioutil.TempFile("", "example")
414 defer os.Remove(tmpfile.Name()) // clean up
416 if _, err := tmpfile.Write(content); err != nil {
419 if err := tmpfile.Close(); err != nil {
423 os.Setenv("ARVADOS_KEEP_SERVICES", "")
424 err = s.disp.configure("crunch-dispatch-slurm", []string{"-config", tmpfile.Name()})
427 c.Check(s.disp.cluster.Services.Controller.ExternalURL, Equals, arvados.URL{Scheme: "https", Host: "example.com", Path: "/"})
428 c.Check(s.disp.cluster.SystemRootToken, Equals, "abcdefg")
429 c.Check(s.disp.cluster.Containers.SLURM.SbatchArgumentsList, DeepEquals, []string{"--foo", "bar"})
430 c.Check(s.disp.cluster.Containers.CloudVMs.PollInterval, Equals, arvados.Duration(12*time.Second))
431 c.Check(s.disp.cluster.Containers.SLURM.PrioritySpread, Equals, int64(42))
432 c.Check(s.disp.cluster.Containers.CrunchRunCommand, Equals, "x-crunch-run")
433 c.Check(s.disp.cluster.Containers.CrunchRunArgumentsList, DeepEquals, []string{"--cgroup-parent-subsystem=memory"})
434 c.Check(s.disp.cluster.Containers.ReserveExtraRAM, Equals, arvados.ByteSize(12345))
435 c.Check(s.disp.cluster.Containers.MinRetryPeriod, Equals, arvados.Duration(13*time.Second))
436 c.Check(s.disp.cluster.API.MaxItemsPerResponse, Equals, 99)
437 c.Check(s.disp.cluster.Containers.SLURM.SbatchEnvironmentVariables, DeepEquals, map[string]string{
438 "ARVADOS_KEEP_SERVICES": "https://example.com/keep1 https://example.com/keep2",
440 c.Check(os.Getenv("ARVADOS_KEEP_SERVICES"), Equals, "https://example.com/keep1 https://example.com/keep2")