3 // Dispatcher service for Crunch that submits containers to the slurm queue.
8 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
9 "git.curoverse.com/arvados.git/sdk/go/dispatch"
27 crunchRunCommand *string
32 flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
34 pollInterval := flags.Int(
37 "Interval in seconds to poll for queued containers")
39 crunchRunCommand = flags.String(
41 "/usr/bin/crunch-run",
42 "Crunch command to run container")
44 // Parse args; omit the first arg which is the command name
45 flags.Parse(os.Args[1:])
47 arv, err := arvadosclient.MakeArvadosClient()
49 log.Printf("Error making Arvados client: %v", err)
54 squeueUpdater.StartMonitor(time.Duration(*pollInterval) * time.Second)
55 defer squeueUpdater.Done()
57 dispatcher := dispatch.Dispatcher{
60 PollInterval: time.Duration(*pollInterval) * time.Second,
61 DoneProcessing: make(chan struct{})}
63 err = dispatcher.RunDispatcher()
72 func sbatchFunc(container dispatch.Container) *exec.Cmd {
73 memPerCPU := math.Ceil((float64(container.RuntimeConstraints["ram"])) / (float64(container.RuntimeConstraints["vcpus"] * 1048576)))
74 return exec.Command("sbatch", "--share", "--parsable",
75 fmt.Sprintf("--job-name=%s", container.UUID),
76 fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)),
77 fmt.Sprintf("--cpus-per-task=%d", int(container.RuntimeConstraints["vcpus"])),
78 fmt.Sprintf("--priority=%d", container.Priority))
82 func scancelFunc(container dispatch.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 dispatch.Container, crunchRunCommand string) (jobid string, submitErr error) {
96 // If we didn't get as far as submitting a slurm job,
97 // unlock the container and return it to the queue.
99 // OK, no cleanup needed
102 err := dispatcher.Arv.Update("containers", container.UUID,
104 "container": arvadosclient.Dict{"state": "Queued"}},
107 log.Printf("Error unlocking container %s: %v", container.UUID, err)
111 // Create the command and attach to stdin/stdout
112 cmd := sbatchCmd(container)
113 stdinWriter, stdinerr := cmd.StdinPipe()
115 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
119 stdoutReader, stdoutErr := cmd.StdoutPipe()
120 if stdoutErr != nil {
121 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
125 stderrReader, stderrErr := cmd.StderrPipe()
126 if stderrErr != nil {
127 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
131 // Mutex between squeue sync and running sbatch or scancel.
132 squeueUpdater.SlurmLock.Lock()
133 defer squeueUpdater.SlurmLock.Unlock()
137 submitErr = fmt.Errorf("Error starting %v: %v", cmd.Args, err)
141 stdoutChan := make(chan []byte)
143 b, _ := ioutil.ReadAll(stdoutReader)
148 stderrChan := make(chan []byte)
150 b, _ := ioutil.ReadAll(stderrReader)
155 // Send a tiny script on stdin to execute the crunch-run command
156 // slurm actually enforces that this must be a #! script
157 fmt.Fprintf(stdinWriter, "#!/bin/sh\nexec '%s' '%s'\n", crunchRunCommand, container.UUID)
162 stdoutMsg := <-stdoutChan
163 stderrmsg := <-stderrChan
169 submitErr = fmt.Errorf("Container submission failed %v: %v %v", cmd.Args, err, stderrmsg)
173 // If everything worked out, got the jobid on stdout
174 jobid = strings.TrimSpace(string(stdoutMsg))
179 // If the container is marked as Locked, check if it is already in the slurm
180 // queue. If not, submit it.
182 // If the container is marked as Running, check if it is in the slurm queue.
183 // If not, mark it as Cancelled.
184 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container dispatch.Container, monitorDone *bool) {
187 if squeueUpdater.CheckSqueue(container.UUID) {
188 // Found in the queue, so continue monitoring
190 } else if container.State == dispatch.Locked && !submitted {
191 // Not in queue but in Locked state and we haven't
192 // submitted it yet, so submit it.
194 log.Printf("About to submit queued container %v", container.UUID)
196 if _, err := submit(dispatcher, container, *crunchRunCommand); err != nil {
197 log.Printf("Error submitting container %s to slurm: %v",
199 // maybe sbatch is broken, put it back to queued
200 dispatcher.UpdateState(container.UUID, dispatch.Queued)
204 // Not in queue and we are not going to submit it.
205 // Refresh the container state. If it is
206 // Complete/Cancelled, do nothing, if it is Locked then
207 // release it back to the Queue, if it is Running then
208 // clean up the record.
210 var con dispatch.Container
211 err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
213 log.Printf("Error getting final container state: %v", err)
218 case dispatch.Locked:
220 case dispatch.Running:
221 st = dispatch.Cancelled
223 // Container state is Queued, Complete or Cancelled so stop monitoring it.
227 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
228 container.UUID, con.State, st)
229 dispatcher.UpdateState(container.UUID, st)
234 // Run or monitor a container.
236 // Monitor status updates. If the priority changes to zero, cancel the
237 // container using scancel.
238 func run(dispatcher *dispatch.Dispatcher,
239 container dispatch.Container,
240 status chan dispatch.Container) {
242 log.Printf("Monitoring container %v started", container.UUID)
243 defer log.Printf("Monitoring container %v finished", container.UUID)
246 go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
248 for container = range status {
249 if container.State == dispatch.Locked || container.State == dispatch.Running {
250 if container.Priority == 0 {
251 log.Printf("Canceling container %s", container.UUID)
253 // Mutex between squeue sync and running sbatch or scancel.
254 squeueUpdater.SlurmLock.Lock()
255 err := scancelCmd(container).Run()
256 squeueUpdater.SlurmLock.Unlock()
259 log.Printf("Error stopping container %s with scancel: %v",
261 if squeueUpdater.CheckSqueue(container.UUID) {
262 log.Printf("Container %s is still in squeue after scancel.",
268 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)