Merge branch 'master' into 11850-singlecontainer-max-requirements
[arvados.git] / services / crunch-dispatch-slurm / crunch-dispatch-slurm_test.go
index de25fc3d01c2b322d47aac991e47e7458828d373..830976d66bdd9e3dbce855936a241b7b83ec8e7b 100644 (file)
@@ -1,12 +1,14 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
 package main
 
 import (
        "bytes"
+       "context"
+       "errors"
        "fmt"
-       "git.curoverse.com/arvados.git/sdk/go/arvados"
-       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
-       "git.curoverse.com/arvados.git/sdk/go/arvadostest"
-       "git.curoverse.com/arvados.git/sdk/go/dispatch"
        "io"
        "io/ioutil"
        "log"
@@ -18,6 +20,10 @@ import (
        "testing"
        "time"
 
+       "git.curoverse.com/arvados.git/sdk/go/arvados"
+       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
+       "git.curoverse.com/arvados.git/sdk/go/arvadostest"
+       "git.curoverse.com/arvados.git/sdk/go/dispatch"
        . "gopkg.in/check.v1"
 )
 
@@ -51,6 +57,7 @@ func (s *TestSuite) SetUpTest(c *C) {
 
 func (s *TestSuite) TearDownTest(c *C) {
        os.Args = initialArgs
+       arvadostest.ResetEnv()
        arvadostest.StopAPI()
 }
 
@@ -58,82 +65,55 @@ func (s *MockArvadosServerSuite) TearDownTest(c *C) {
        arvadostest.ResetEnv()
 }
 
-func (s *TestSuite) TestIntegrationNormal(c *C) {
-       container := s.integrationTest(c, func() *exec.Cmd { return exec.Command("echo", "zzzzz-dz642-queuedcontainer") },
-               []string(nil),
-               func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
-                       dispatcher.UpdateState(container.UUID, dispatch.Running)
-                       time.Sleep(3 * time.Second)
-                       dispatcher.UpdateState(container.UUID, dispatch.Complete)
-               })
-       c.Check(container.State, Equals, arvados.ContainerStateComplete)
+type slurmFake struct {
+       didBatch  [][]string
+       didCancel []string
+       didRenice [][]string
+       queue     string
+       // If non-nil, run this func during the 2nd+ call to Cancel()
+       onCancel func()
+       // Error returned by Batch()
+       errBatch error
 }
 
-func (s *TestSuite) TestIntegrationCancel(c *C) {
+func (sf *slurmFake) Batch(script io.Reader, args []string) error {
+       sf.didBatch = append(sf.didBatch, args)
+       return sf.errBatch
+}
 
-       // Override sbatchCmd
-       var scancelCmdLine []string
-       defer func(orig func(arvados.Container) *exec.Cmd) {
-               scancelCmd = orig
-       }(scancelCmd)
-       scancelCmd = func(container arvados.Container) *exec.Cmd {
-               scancelCmdLine = scancelFunc(container).Args
-               return exec.Command("echo")
-       }
+func (sf *slurmFake) QueueCommand(args []string) *exec.Cmd {
+       return exec.Command("echo", sf.queue)
+}
 
-       container := s.integrationTest(c,
-               func() *exec.Cmd { return exec.Command("echo", "zzzzz-dz642-queuedcontainer") },
-               []string(nil),
-               func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
-                       dispatcher.UpdateState(container.UUID, dispatch.Running)
-                       time.Sleep(1 * time.Second)
-                       dispatcher.Arv.Update("containers", container.UUID,
-                               arvadosclient.Dict{
-                                       "container": arvadosclient.Dict{"priority": 0}},
-                               nil)
-               })
-       c.Check(container.State, Equals, arvados.ContainerStateCancelled)
-       c.Check(scancelCmdLine, DeepEquals, []string{"scancel", "--name=zzzzz-dz642-queuedcontainer"})
+func (sf *slurmFake) Renice(name string, nice int) error {
+       sf.didRenice = append(sf.didRenice, []string{name, fmt.Sprintf("%d", nice)})
+       return nil
 }
 
-func (s *TestSuite) TestIntegrationMissingFromSqueue(c *C) {
-       container := s.integrationTest(c, func() *exec.Cmd { return exec.Command("echo") }, []string{"sbatch", "--share",
-               fmt.Sprintf("--job-name=%s", "zzzzz-dz642-queuedcontainer"),
-               fmt.Sprintf("--mem-per-cpu=%d", 2862),
-               fmt.Sprintf("--cpus-per-task=%d", 4)},
-               func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
-                       dispatcher.UpdateState(container.UUID, dispatch.Running)
-                       time.Sleep(3 * time.Second)
-                       dispatcher.UpdateState(container.UUID, dispatch.Complete)
-               })
-       c.Check(container.State, Equals, arvados.ContainerStateCancelled)
+func (sf *slurmFake) Cancel(name string) error {
+       sf.didCancel = append(sf.didCancel, name)
+       if len(sf.didCancel) == 1 {
+               // simulate error on first attempt
+               return errors.New("something terrible happened")
+       }
+       if sf.onCancel != nil {
+               sf.onCancel()
+       }
+       return nil
 }
 
-func (s *TestSuite) integrationTest(c *C,
-       newSqueueCmd func() *exec.Cmd,
-       sbatchCmdComps []string,
+func (s *TestSuite) integrationTest(c *C, slurm *slurmFake,
+       expectBatch [][]string,
        runContainer func(*dispatch.Dispatcher, arvados.Container)) arvados.Container {
        arvadostest.ResetEnv()
 
        arv, err := arvadosclient.MakeArvadosClient()
        c.Assert(err, IsNil)
 
-       var sbatchCmdLine []string
-
-       // Override sbatchCmd
-       defer func(orig func(arvados.Container) *exec.Cmd) {
-               sbatchCmd = orig
-       }(sbatchCmd)
-       sbatchCmd = func(container arvados.Container) *exec.Cmd {
-               sbatchCmdLine = sbatchFunc(container).Args
-               return exec.Command("sh")
-       }
-
-       // Override squeueCmd
-       defer func(orig func() *exec.Cmd) {
-               squeueCmd = orig
-       }(squeueCmd)
-       squeueCmd = newSqueueCmd
+       defer func(orig Slurm) {
+               theConfig.slurm = orig
+       }(theConfig.slurm)
+       theConfig.slurm = slurm
 
        // There should be one queued container
        params := arvadosclient.Dict{
@@ -146,26 +126,32 @@ func (s *TestSuite) integrationTest(c *C,
 
        theConfig.CrunchRunCommand = []string{"echo"}
 
+       ctx, cancel := context.WithCancel(context.Background())
+       doneRun := make(chan struct{})
+
        dispatcher := dispatch.Dispatcher{
                Arv:        arv,
                PollPeriod: time.Duration(1) * time.Second,
-               RunContainer: func(dispatcher *dispatch.Dispatcher,
-                       container arvados.Container,
-                       status chan arvados.Container) {
-                       go runContainer(dispatcher, container)
-                       run(dispatcher, container, status)
-                       dispatcher.Stop()
+               RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
+                       go func() {
+                               runContainer(disp, ctr)
+                               slurm.queue = ""
+                               doneRun <- struct{}{}
+                       }()
+                       run(disp, ctr, status)
+                       cancel()
                },
        }
 
-       squeueUpdater.StartMonitor(time.Duration(500) * time.Millisecond)
+       sqCheck = &SqueueChecker{Period: 500 * time.Millisecond}
 
-       err = dispatcher.Run()
-       c.Assert(err, IsNil)
+       err = dispatcher.Run(ctx)
+       <-doneRun
+       c.Assert(err, Equals, context.Canceled)
 
-       squeueUpdater.Done()
+       sqCheck.Stop()
 
-       c.Check(sbatchCmdLine, DeepEquals, sbatchCmdComps)
+       c.Check(slurm.didBatch, DeepEquals, expectBatch)
 
        // There should be no queued containers now
        err = arv.List("containers", params, &containers)
@@ -179,6 +165,77 @@ func (s *TestSuite) integrationTest(c *C,
        return container
 }
 
+func (s *TestSuite) TestIntegrationNormal(c *C) {
+       container := s.integrationTest(c,
+               &slurmFake{queue: "zzzzz-dz642-queuedcontainer 9990 100\n"},
+               nil,
+               func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
+                       dispatcher.UpdateState(container.UUID, dispatch.Running)
+                       time.Sleep(3 * time.Second)
+                       dispatcher.UpdateState(container.UUID, dispatch.Complete)
+               })
+       c.Check(container.State, Equals, arvados.ContainerStateComplete)
+}
+
+func (s *TestSuite) TestIntegrationCancel(c *C) {
+       slurm := &slurmFake{queue: "zzzzz-dz642-queuedcontainer 9990 100\n"}
+       readyToCancel := make(chan bool)
+       slurm.onCancel = func() { <-readyToCancel }
+       container := s.integrationTest(c,
+               slurm,
+               nil,
+               func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
+                       dispatcher.UpdateState(container.UUID, dispatch.Running)
+                       time.Sleep(time.Second)
+                       dispatcher.Arv.Update("containers", container.UUID,
+                               arvadosclient.Dict{
+                                       "container": arvadosclient.Dict{"priority": 0}},
+                               nil)
+                       readyToCancel <- true
+                       close(readyToCancel)
+               })
+       c.Check(container.State, Equals, arvados.ContainerStateCancelled)
+       c.Check(len(slurm.didCancel) > 1, Equals, true)
+       c.Check(slurm.didCancel[:2], DeepEquals, []string{"zzzzz-dz642-queuedcontainer", "zzzzz-dz642-queuedcontainer"})
+}
+
+func (s *TestSuite) TestIntegrationMissingFromSqueue(c *C) {
+       container := s.integrationTest(c, &slurmFake{},
+               [][]string{{
+                       fmt.Sprintf("--job-name=%s", "zzzzz-dz642-queuedcontainer"),
+                       fmt.Sprintf("--mem=%d", 11445),
+                       fmt.Sprintf("--cpus-per-task=%d", 4),
+                       fmt.Sprintf("--tmp=%d", 45777),
+                       fmt.Sprintf("--nice=%d", 9990)}},
+               func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
+                       dispatcher.UpdateState(container.UUID, dispatch.Running)
+                       time.Sleep(3 * time.Second)
+                       dispatcher.UpdateState(container.UUID, dispatch.Complete)
+               })
+       c.Check(container.State, Equals, arvados.ContainerStateCancelled)
+}
+
+func (s *TestSuite) TestSbatchFail(c *C) {
+       container := s.integrationTest(c,
+               &slurmFake{errBatch: errors.New("something terrible happened")},
+               [][]string{{"--job-name=zzzzz-dz642-queuedcontainer", "--mem=11445", "--cpus-per-task=4", "--tmp=45777", "--nice=9990"}},
+               func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
+                       dispatcher.UpdateState(container.UUID, dispatch.Running)
+                       dispatcher.UpdateState(container.UUID, dispatch.Complete)
+               })
+       c.Check(container.State, Equals, arvados.ContainerStateComplete)
+
+       arv, err := arvadosclient.MakeArvadosClient()
+       c.Assert(err, IsNil)
+
+       var ll arvados.LogList
+       err = arv.List("logs", arvadosclient.Dict{"filters": [][]string{
+               {"object_uuid", "=", container.UUID},
+               {"event_type", "=", "dispatch"},
+       }}, &ll)
+       c.Assert(len(ll.Items), Equals, 1)
+}
+
 func (s *MockArvadosServerSuite) TestAPIErrorGettingContainers(c *C) {
        apiStubResponses := make(map[string]arvadostest.StubResponse)
        apiStubResponses["/arvados/v1/api_client_authorizations/current"] = arvadostest.StubResponse{200, `{"uuid":"` + arvadostest.Dispatch1AuthUUID + `"}`}
@@ -207,19 +264,18 @@ func testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubRespon
 
        theConfig.CrunchRunCommand = []string{crunchCmd}
 
+       ctx, cancel := context.WithCancel(context.Background())
        dispatcher := dispatch.Dispatcher{
                Arv:        arv,
                PollPeriod: time.Duration(1) * time.Second,
-               RunContainer: func(dispatcher *dispatch.Dispatcher,
-                       container arvados.Container,
-                       status chan arvados.Container) {
+               RunContainer: func(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
                        go func() {
                                time.Sleep(1 * time.Second)
-                               dispatcher.UpdateState(container.UUID, dispatch.Running)
-                               dispatcher.UpdateState(container.UUID, dispatch.Complete)
+                               disp.UpdateState(ctr.UUID, dispatch.Running)
+                               disp.UpdateState(ctr.UUID, dispatch.Complete)
                        }()
-                       run(dispatcher, container, status)
-                       dispatcher.Stop()
+                       run(disp, ctr, status)
+                       cancel()
                },
        }
 
@@ -227,11 +283,11 @@ func testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubRespon
                for i := 0; i < 80 && !strings.Contains(buf.String(), expected); i++ {
                        time.Sleep(100 * time.Millisecond)
                }
-               dispatcher.Stop()
+               cancel()
        }()
 
-       err := dispatcher.Run()
-       c.Assert(err, IsNil)
+       err := dispatcher.Run(ctx)
+       c.Assert(err, Equals, context.Canceled)
 
        c.Check(buf.String(), Matches, `(?ms).*`+expected+`.*`)
 }
@@ -302,27 +358,47 @@ func (s *MockArvadosServerSuite) TestSbatchFuncWithConfigArgs(c *C) {
 }
 
 func testSbatchFuncWithArgs(c *C, args []string) {
+       defer func() { theConfig.SbatchArguments = nil }()
        theConfig.SbatchArguments = append(theConfig.SbatchArguments, args...)
 
-       container := arvados.Container{UUID: "123", RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2}}
-       sbatchCmd := sbatchFunc(container)
+       container := arvados.Container{
+               UUID:               "123",
+               RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 2},
+               Priority:           1}
 
        var expected []string
-       expected = append(expected, "sbatch", "--share")
        expected = append(expected, theConfig.SbatchArguments...)
-       expected = append(expected, "--job-name=123", "--mem-per-cpu=120", "--cpus-per-task=2")
-
-       c.Check(sbatchCmd.Args, DeepEquals, expected)
+       expected = append(expected, "--job-name=123", "--mem=239", "--cpus-per-task=2", "--tmp=0", "--nice=9990")
+       c.Check(sbatchArgs(container), DeepEquals, expected)
 }
 
 func (s *MockArvadosServerSuite) TestSbatchPartition(c *C) {
-       theConfig.SbatchArguments = nil
-       container := arvados.Container{UUID: "123", RuntimeConstraints: arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 1}, SchedulingParameters: arvados.SchedulingParameters{Partitions: []string{"blurb", "b2"}}}
-       sbatchCmd := sbatchFunc(container)
-
-       var expected []string
-       expected = append(expected, "sbatch", "--share")
-       expected = append(expected, "--job-name=123", "--mem-per-cpu=239", "--cpus-per-task=1", "--partition=blurb,b2")
+       container := arvados.Container{
+               UUID:                 "123",
+               RuntimeConstraints:   arvados.RuntimeConstraints{RAM: 250000000, VCPUs: 1},
+               SchedulingParameters: arvados.SchedulingParameters{Partitions: []string{"blurb", "b2"}},
+               Priority:             1}
+
+       c.Check(sbatchArgs(container), DeepEquals, []string{
+               "--job-name=123", "--mem=239", "--cpus-per-task=1", "--tmp=0", "--nice=9990",
+               "--partition=blurb,b2",
+       })
+}
 
-       c.Check(sbatchCmd.Args, DeepEquals, expected)
+func (s *TestSuite) TestIntegrationChangePriority(c *C) {
+       slurm := &slurmFake{queue: "zzzzz-dz642-queuedcontainer 9990 100\n"}
+       container := s.integrationTest(c, slurm, nil,
+               func(dispatcher *dispatch.Dispatcher, container arvados.Container) {
+                       dispatcher.UpdateState(container.UUID, dispatch.Running)
+                       time.Sleep(time.Second)
+                       dispatcher.Arv.Update("containers", container.UUID,
+                               arvadosclient.Dict{
+                                       "container": arvadosclient.Dict{"priority": 600}},
+                               nil)
+                       time.Sleep(time.Second)
+                       dispatcher.UpdateState(container.UUID, dispatch.Complete)
+               })
+       c.Check(container.State, Equals, arvados.ContainerStateComplete)
+       c.Assert(len(slurm.didRenice), Not(Equals), 0)
+       c.Check(slurm.didRenice[len(slurm.didRenice)-1], DeepEquals, []string{"zzzzz-dz642-queuedcontainer", "4000"})
 }