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),
79 fmt.Sprintf("--priority=%d", container.Priority))
83 func scancelFunc(container arvados.Container) *exec.Cmd {
84 return exec.Command("scancel", "--name="+container.UUID)
87 // Wrap these so that they can be overridden by tests
88 var sbatchCmd = sbatchFunc
89 var scancelCmd = scancelFunc
91 // Submit job to slurm using sbatch.
92 func submit(dispatcher *dispatch.Dispatcher,
93 container arvados.Container, crunchRunCommand string) (submitErr error) {
95 // If we didn't get as far as submitting a slurm job,
96 // unlock the container and return it to the queue.
98 // OK, no cleanup needed
101 err := dispatcher.Arv.Update("containers", container.UUID,
103 "container": arvadosclient.Dict{"state": "Queued"}},
106 log.Printf("Error unlocking container %s: %v", container.UUID, err)
110 // Create the command and attach to stdin/stdout
111 cmd := sbatchCmd(container)
112 stdinWriter, stdinerr := cmd.StdinPipe()
114 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
118 stdoutReader, stdoutErr := cmd.StdoutPipe()
119 if stdoutErr != nil {
120 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
124 stderrReader, stderrErr := cmd.StderrPipe()
125 if stderrErr != nil {
126 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
130 // Mutex between squeue sync and running sbatch or scancel.
131 squeueUpdater.SlurmLock.Lock()
132 defer squeueUpdater.SlurmLock.Unlock()
136 submitErr = fmt.Errorf("Error starting %v: %v", cmd.Args, err)
140 stdoutChan := make(chan []byte)
142 b, _ := ioutil.ReadAll(stdoutReader)
147 stderrChan := make(chan []byte)
149 b, _ := ioutil.ReadAll(stderrReader)
154 // Send a tiny script on stdin to execute the crunch-run command
155 // slurm actually enforces that this must be a #! script
156 fmt.Fprintf(stdinWriter, "#!/bin/sh\nexec '%s' '%s'\n", crunchRunCommand, container.UUID)
161 stdoutMsg := <-stdoutChan
162 stderrmsg := <-stderrChan
168 submitErr = fmt.Errorf("Container submission failed %v: %v %v", cmd.Args, err, stderrmsg)
172 log.Printf("sbatch succeeded: %s", strings.TrimSpace(string(stdoutMsg)))
176 // If the container is marked as Locked, check if it is already in the slurm
177 // queue. If not, submit it.
179 // If the container is marked as Running, check if it is in the slurm queue.
180 // If not, mark it as Cancelled.
181 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
184 if squeueUpdater.CheckSqueue(container.UUID) {
185 // Found in the queue, so continue monitoring
187 } else if container.State == dispatch.Locked && !submitted {
188 // Not in queue but in Locked state and we haven't
189 // submitted it yet, so submit it.
191 log.Printf("About to submit queued container %v", container.UUID)
193 if err := submit(dispatcher, container, *crunchRunCommand); err != nil {
194 log.Printf("Error submitting container %s to slurm: %v",
196 // maybe sbatch is broken, put it back to queued
197 dispatcher.UpdateState(container.UUID, dispatch.Queued)
201 // Not in queue and we are not going to submit it.
202 // Refresh the container state. If it is
203 // Complete/Cancelled, do nothing, if it is Locked then
204 // release it back to the Queue, if it is Running then
205 // clean up the record.
207 var con arvados.Container
208 err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
210 log.Printf("Error getting final container state: %v", err)
213 var st arvados.ContainerState
215 case dispatch.Locked:
217 case dispatch.Running:
218 st = dispatch.Cancelled
220 // Container state is Queued, Complete or Cancelled so stop monitoring it.
224 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
225 container.UUID, con.State, st)
226 dispatcher.UpdateState(container.UUID, st)
231 // Run or monitor a container.
233 // Monitor status updates. If the priority changes to zero, cancel the
234 // container using scancel.
235 func run(dispatcher *dispatch.Dispatcher,
236 container arvados.Container,
237 status chan arvados.Container) {
239 log.Printf("Monitoring container %v started", container.UUID)
240 defer log.Printf("Monitoring container %v finished", container.UUID)
243 go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
245 for container = range status {
246 if container.State == dispatch.Locked || container.State == dispatch.Running {
247 if container.Priority == 0 {
248 log.Printf("Canceling container %s", container.UUID)
250 // Mutex between squeue sync and running sbatch or scancel.
251 squeueUpdater.SlurmLock.Lock()
252 err := scancelCmd(container).Run()
253 squeueUpdater.SlurmLock.Unlock()
256 log.Printf("Error stopping container %s with scancel: %v",
258 if squeueUpdater.CheckSqueue(container.UUID) {
259 log.Printf("Container %s is still in squeue after scancel.",
265 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)