3 // Dispatcher service for Crunch that submits containers to the slurm queue.
8 "git.curoverse.com/arvados.git/sdk/go/arvados"
9 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
10 "git.curoverse.com/arvados.git/sdk/go/dispatch"
28 crunchRunCommand *string
33 flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
35 pollInterval := flags.Int(
38 "Interval in seconds to poll for queued containers")
40 crunchRunCommand = flags.String(
42 "/usr/bin/crunch-run",
43 "Crunch command to run container")
45 // Parse args; omit the first arg which is the command name
46 flags.Parse(os.Args[1:])
48 arv, err := arvadosclient.MakeArvadosClient()
50 log.Printf("Error making Arvados client: %v", err)
55 squeueUpdater.StartMonitor(time.Duration(*pollInterval) * time.Second)
56 defer squeueUpdater.Done()
58 dispatcher := dispatch.Dispatcher{
61 PollInterval: time.Duration(*pollInterval) * time.Second,
62 DoneProcessing: make(chan struct{})}
64 err = dispatcher.RunDispatcher()
73 func sbatchFunc(container arvados.Container) *exec.Cmd {
74 memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
75 return exec.Command("sbatch", "--share",
76 fmt.Sprintf("--job-name=%s", container.UUID),
77 fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)),
78 fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
82 func scancelFunc(container arvados.Container) *exec.Cmd {
83 return exec.Command("scancel", "--name="+container.UUID)
86 // Wrap these so that they can be overridden by tests
87 var sbatchCmd = sbatchFunc
88 var scancelCmd = scancelFunc
90 // Submit job to slurm using sbatch.
91 func submit(dispatcher *dispatch.Dispatcher,
92 container arvados.Container, crunchRunCommand string) (submitErr error) {
94 // If we didn't get as far as submitting a slurm job,
95 // unlock the container and return it to the queue.
97 // OK, no cleanup needed
100 err := dispatcher.Arv.Update("containers", container.UUID,
102 "container": arvadosclient.Dict{"state": "Queued"}},
105 log.Printf("Error unlocking container %s: %v", container.UUID, err)
109 // Create the command and attach to stdin/stdout
110 cmd := sbatchCmd(container)
111 stdinWriter, stdinerr := cmd.StdinPipe()
113 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
117 stdoutReader, stdoutErr := cmd.StdoutPipe()
118 if stdoutErr != nil {
119 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
123 stderrReader, stderrErr := cmd.StderrPipe()
124 if stderrErr != nil {
125 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
129 // Mutex between squeue sync and running sbatch or scancel.
130 squeueUpdater.SlurmLock.Lock()
131 defer squeueUpdater.SlurmLock.Unlock()
135 submitErr = fmt.Errorf("Error starting %v: %v", cmd.Args, err)
139 stdoutChan := make(chan []byte)
141 b, _ := ioutil.ReadAll(stdoutReader)
146 stderrChan := make(chan []byte)
148 b, _ := ioutil.ReadAll(stderrReader)
153 // Send a tiny script on stdin to execute the crunch-run command
154 // slurm actually enforces that this must be a #! script
155 fmt.Fprintf(stdinWriter, "#!/bin/sh\nexec '%s' '%s'\n", crunchRunCommand, container.UUID)
160 stdoutMsg := <-stdoutChan
161 stderrmsg := <-stderrChan
167 submitErr = fmt.Errorf("Container submission failed %v: %v %v", cmd.Args, err, stderrmsg)
171 log.Printf("sbatch succeeded: %s", strings.TrimSpace(string(stdoutMsg)))
175 // If the container is marked as Locked, check if it is already in the slurm
176 // queue. If not, submit it.
178 // If the container is marked as Running, check if it is in the slurm queue.
179 // If not, mark it as Cancelled.
180 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
183 if squeueUpdater.CheckSqueue(container.UUID) {
184 // Found in the queue, so continue monitoring
186 } else if container.State == dispatch.Locked && !submitted {
187 // Not in queue but in Locked state and we haven't
188 // submitted it yet, so submit it.
190 log.Printf("About to submit queued container %v", container.UUID)
192 if err := submit(dispatcher, container, *crunchRunCommand); err != nil {
193 log.Printf("Error submitting container %s to slurm: %v",
195 // maybe sbatch is broken, put it back to queued
196 dispatcher.UpdateState(container.UUID, dispatch.Queued)
200 // Not in queue and we are not going to submit it.
201 // Refresh the container state. If it is
202 // Complete/Cancelled, do nothing, if it is Locked then
203 // release it back to the Queue, if it is Running then
204 // clean up the record.
206 var con arvados.Container
207 err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
209 log.Printf("Error getting final container state: %v", err)
212 var st arvados.ContainerState
214 case dispatch.Locked:
216 case dispatch.Running:
217 st = dispatch.Cancelled
219 // Container state is Queued, Complete or Cancelled so stop monitoring it.
223 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
224 container.UUID, con.State, st)
225 dispatcher.UpdateState(container.UUID, st)
230 // Run or monitor a container.
232 // Monitor status updates. If the priority changes to zero, cancel the
233 // container using scancel.
234 func run(dispatcher *dispatch.Dispatcher,
235 container arvados.Container,
236 status chan arvados.Container) {
238 log.Printf("Monitoring container %v started", container.UUID)
239 defer log.Printf("Monitoring container %v finished", container.UUID)
242 go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
244 for container = range status {
245 if container.State == dispatch.Locked || container.State == dispatch.Running {
246 if container.Priority == 0 {
247 log.Printf("Canceling container %s", container.UUID)
249 // Mutex between squeue sync and running sbatch or scancel.
250 squeueUpdater.SlurmLock.Lock()
251 err := scancelCmd(container).Run()
252 squeueUpdater.SlurmLock.Unlock()
255 log.Printf("Error stopping container %s with scancel: %v",
257 if squeueUpdater.CheckSqueue(container.UUID) {
258 log.Printf("Container %s is still in squeue after scancel.",
264 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)