3 // Dispatcher service for Crunch that submits containers to the slurm queue.
9 "git.curoverse.com/arvados.git/sdk/go/arvados"
10 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
11 "git.curoverse.com/arvados.git/sdk/go/dispatch"
21 // Config used by crunch-dispatch-slurm
23 SbatchArguments []string
24 PollPeriod *time.Duration
25 CrunchRunCommand *string
40 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/config.json"
43 flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
45 configPath := flags.String(
48 "`path` to json configuration file")
50 config.PollPeriod = flags.Duration(
53 "Time duration to poll for queued containers")
55 config.CrunchRunCommand = flags.String(
57 "/usr/bin/crunch-run",
58 "Crunch command to run container")
60 // Parse args; omit the first arg which is the command name
61 flags.Parse(os.Args[1:])
63 err := readConfig(&config, *configPath)
65 log.Printf("Error reading configuration: %v", err)
69 arv, err := arvadosclient.MakeArvadosClient()
71 log.Printf("Error making Arvados client: %v", err)
76 squeueUpdater.StartMonitor(*config.PollPeriod)
77 defer squeueUpdater.Done()
79 dispatcher := dispatch.Dispatcher{
82 PollInterval: *config.PollPeriod,
83 DoneProcessing: make(chan struct{})}
85 err = dispatcher.RunDispatcher()
94 func sbatchFunc(container arvados.Container) *exec.Cmd {
95 memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
97 var sbatchArgs []string
98 sbatchArgs = append(sbatchArgs, "--share")
99 sbatchArgs = append(sbatchArgs, config.SbatchArguments...)
100 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
101 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
102 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
104 return exec.Command("sbatch", sbatchArgs...)
108 func scancelFunc(container arvados.Container) *exec.Cmd {
109 return exec.Command("scancel", "--name="+container.UUID)
112 // Wrap these so that they can be overridden by tests
113 var sbatchCmd = sbatchFunc
114 var scancelCmd = scancelFunc
116 // Submit job to slurm using sbatch.
117 func submit(dispatcher *dispatch.Dispatcher,
118 container arvados.Container, crunchRunCommand string) (submitErr error) {
120 // If we didn't get as far as submitting a slurm job,
121 // unlock the container and return it to the queue.
122 if submitErr == nil {
123 // OK, no cleanup needed
126 err := dispatcher.Arv.Update("containers", container.UUID,
128 "container": arvadosclient.Dict{"state": "Queued"}},
131 log.Printf("Error unlocking container %s: %v", container.UUID, err)
135 // Create the command and attach to stdin/stdout
136 cmd := sbatchCmd(container)
137 stdinWriter, stdinerr := cmd.StdinPipe()
139 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
143 stdoutReader, stdoutErr := cmd.StdoutPipe()
144 if stdoutErr != nil {
145 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
149 stderrReader, stderrErr := cmd.StderrPipe()
150 if stderrErr != nil {
151 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
155 // Mutex between squeue sync and running sbatch or scancel.
156 squeueUpdater.SlurmLock.Lock()
157 defer squeueUpdater.SlurmLock.Unlock()
161 submitErr = fmt.Errorf("Error starting %v: %v", cmd.Args, err)
165 stdoutChan := make(chan []byte)
167 b, _ := ioutil.ReadAll(stdoutReader)
172 stderrChan := make(chan []byte)
174 b, _ := ioutil.ReadAll(stderrReader)
179 // Send a tiny script on stdin to execute the crunch-run command
180 // slurm actually enforces that this must be a #! script
181 fmt.Fprintf(stdinWriter, "#!/bin/sh\nexec '%s' '%s'\n", crunchRunCommand, container.UUID)
186 stdoutMsg := <-stdoutChan
187 stderrmsg := <-stderrChan
193 submitErr = fmt.Errorf("Container submission failed: %v: %v (stderr: %q)", cmd.Args, err, stderrmsg)
197 log.Printf("sbatch succeeded: %s", strings.TrimSpace(string(stdoutMsg)))
201 // If the container is marked as Locked, check if it is already in the slurm
202 // queue. If not, submit it.
204 // If the container is marked as Running, check if it is in the slurm queue.
205 // If not, mark it as Cancelled.
206 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
209 if squeueUpdater.CheckSqueue(container.UUID) {
210 // Found in the queue, so continue monitoring
212 } else if container.State == dispatch.Locked && !submitted {
213 // Not in queue but in Locked state and we haven't
214 // submitted it yet, so submit it.
216 log.Printf("About to submit queued container %v", container.UUID)
218 if err := submit(dispatcher, container, *config.CrunchRunCommand); err != nil {
219 log.Printf("Error submitting container %s to slurm: %v",
221 // maybe sbatch is broken, put it back to queued
222 dispatcher.UpdateState(container.UUID, dispatch.Queued)
226 // Not in queue and we are not going to submit it.
227 // Refresh the container state. If it is
228 // Complete/Cancelled, do nothing, if it is Locked then
229 // release it back to the Queue, if it is Running then
230 // clean up the record.
232 var con arvados.Container
233 err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
235 log.Printf("Error getting final container state: %v", err)
238 var st arvados.ContainerState
240 case dispatch.Locked:
242 case dispatch.Running:
243 st = dispatch.Cancelled
245 // Container state is Queued, Complete or Cancelled so stop monitoring it.
249 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
250 container.UUID, con.State, st)
251 dispatcher.UpdateState(container.UUID, st)
256 // Run or monitor a container.
258 // Monitor status updates. If the priority changes to zero, cancel the
259 // container using scancel.
260 func run(dispatcher *dispatch.Dispatcher,
261 container arvados.Container,
262 status chan arvados.Container) {
264 log.Printf("Monitoring container %v started", container.UUID)
265 defer log.Printf("Monitoring container %v finished", container.UUID)
268 go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
270 for container = range status {
271 if container.State == dispatch.Locked || container.State == dispatch.Running {
272 if container.Priority == 0 {
273 log.Printf("Canceling container %s", container.UUID)
275 // Mutex between squeue sync and running sbatch or scancel.
276 squeueUpdater.SlurmLock.Lock()
277 err := scancelCmd(container).Run()
278 squeueUpdater.SlurmLock.Unlock()
281 log.Printf("Error stopping container %s with scancel: %v",
283 if squeueUpdater.CheckSqueue(container.UUID) {
284 log.Printf("Container %s is still in squeue after scancel.",
290 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)
297 func readConfig(dst interface{}, path string) error {
298 if buf, err := ioutil.ReadFile(path); err != nil && os.IsNotExist(err) {
299 if path == defaultConfigPath {
300 log.Printf("Config not specified. Continue with default configuration.")
302 return fmt.Errorf("Config file not found %q: %v", path, err)
304 } else if err != nil {
305 return fmt.Errorf("Error reading config %q: %v", path, err)
306 } else if err = json.Unmarshal(buf, dst); err != nil {
307 return fmt.Errorf("Error decoding config %q: %v", path, err)