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"
22 // Config used by crunch-dispatch-slurm
26 SbatchArguments []string
27 PollPeriod arvados.Duration
29 // crunch-run command to invoke. The container UUID will be
30 // appended. If nil, []string{"crunch-run"} will be used.
32 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
33 CrunchRunCommand []string
48 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/config.json"
51 flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
52 flags.Usage = func() { usage(flags) }
54 configPath := flags.String(
57 "`path` to json configuration file")
59 // Parse args; omit the first arg which is the command name
60 flags.Parse(os.Args[1:])
62 err := readConfig(&config, *configPath)
64 log.Printf("Error reading configuration: %v", err)
68 if config.CrunchRunCommand == nil {
69 config.CrunchRunCommand = []string{"crunch-run"}
72 if config.PollPeriod == 0 {
73 config.PollPeriod = arvados.Duration(10 * time.Second)
76 if config.Client.APIHost != "" || config.Client.AuthToken != "" {
77 // Copy real configs into env vars so [a]
78 // MakeArvadosClient() uses them, and [b] they get
79 // propagated to crunch-run via SLURM.
80 os.Setenv("ARVADOS_API_HOST", config.Client.APIHost)
81 os.Setenv("ARVADOS_API_TOKEN", config.Client.AuthToken)
82 os.Setenv("ARVADOS_API_INSECURE", "")
83 if config.Client.Insecure {
84 os.Setenv("ARVADOS_API_INSECURE", "1")
86 os.Setenv("ARVADOS_KEEP_SERVICES", "")
87 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
89 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
92 arv, err := arvadosclient.MakeArvadosClient()
94 log.Printf("Error making Arvados client: %v", err)
99 squeueUpdater.StartMonitor(time.Duration(config.PollPeriod))
100 defer squeueUpdater.Done()
102 dispatcher := dispatch.Dispatcher{
105 PollInterval: time.Duration(config.PollPeriod),
106 DoneProcessing: make(chan struct{})}
108 err = dispatcher.RunDispatcher()
117 func sbatchFunc(container arvados.Container) *exec.Cmd {
118 memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
120 var sbatchArgs []string
121 sbatchArgs = append(sbatchArgs, "--share")
122 sbatchArgs = append(sbatchArgs, config.SbatchArguments...)
123 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
124 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
125 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
127 return exec.Command("sbatch", sbatchArgs...)
131 func scancelFunc(container arvados.Container) *exec.Cmd {
132 return exec.Command("scancel", "--name="+container.UUID)
135 // Wrap these so that they can be overridden by tests
136 var sbatchCmd = sbatchFunc
137 var scancelCmd = scancelFunc
139 // Submit job to slurm using sbatch.
140 func submit(dispatcher *dispatch.Dispatcher,
141 container arvados.Container, crunchRunCommand []string) (submitErr error) {
143 // If we didn't get as far as submitting a slurm job,
144 // unlock the container and return it to the queue.
145 if submitErr == nil {
146 // OK, no cleanup needed
149 err := dispatcher.Arv.Update("containers", container.UUID,
151 "container": arvadosclient.Dict{"state": "Queued"}},
154 log.Printf("Error unlocking container %s: %v", container.UUID, err)
158 // Create the command and attach to stdin/stdout
159 cmd := sbatchCmd(container)
160 stdinWriter, stdinerr := cmd.StdinPipe()
162 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
166 stdoutReader, stdoutErr := cmd.StdoutPipe()
167 if stdoutErr != nil {
168 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
172 stderrReader, stderrErr := cmd.StderrPipe()
173 if stderrErr != nil {
174 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
178 // Mutex between squeue sync and running sbatch or scancel.
179 squeueUpdater.SlurmLock.Lock()
180 defer squeueUpdater.SlurmLock.Unlock()
184 submitErr = fmt.Errorf("Error starting %v: %v", cmd.Args, err)
188 stdoutChan := make(chan []byte)
190 b, _ := ioutil.ReadAll(stdoutReader)
195 stderrChan := make(chan []byte)
197 b, _ := ioutil.ReadAll(stderrReader)
202 // Send a tiny script on stdin to execute the crunch-run command
203 // slurm actually enforces that this must be a #! script
204 io.WriteString(stdinWriter, execScript(append(crunchRunCommand, container.UUID)))
209 stdoutMsg := <-stdoutChan
210 stderrmsg := <-stderrChan
216 submitErr = fmt.Errorf("Container submission failed: %v: %v (stderr: %q)", cmd.Args, err, stderrmsg)
220 log.Printf("sbatch succeeded: %s", strings.TrimSpace(string(stdoutMsg)))
224 // If the container is marked as Locked, check if it is already in the slurm
225 // queue. If not, submit it.
227 // If the container is marked as Running, check if it is in the slurm queue.
228 // If not, mark it as Cancelled.
229 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
232 if squeueUpdater.CheckSqueue(container.UUID) {
233 // Found in the queue, so continue monitoring
235 } else if container.State == dispatch.Locked && !submitted {
236 // Not in queue but in Locked state and we haven't
237 // submitted it yet, so submit it.
239 log.Printf("About to submit queued container %v", container.UUID)
241 if err := submit(dispatcher, container, config.CrunchRunCommand); err != nil {
242 log.Printf("Error submitting container %s to slurm: %v",
244 // maybe sbatch is broken, put it back to queued
245 dispatcher.UpdateState(container.UUID, dispatch.Queued)
249 // Not in queue and we are not going to submit it.
250 // Refresh the container state. If it is
251 // Complete/Cancelled, do nothing, if it is Locked then
252 // release it back to the Queue, if it is Running then
253 // clean up the record.
255 var con arvados.Container
256 err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
258 log.Printf("Error getting final container state: %v", err)
261 var st arvados.ContainerState
263 case dispatch.Locked:
265 case dispatch.Running:
266 st = dispatch.Cancelled
268 // Container state is Queued, Complete or Cancelled so stop monitoring it.
272 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
273 container.UUID, con.State, st)
274 dispatcher.UpdateState(container.UUID, st)
279 // Run or monitor a container.
281 // Monitor status updates. If the priority changes to zero, cancel the
282 // container using scancel.
283 func run(dispatcher *dispatch.Dispatcher,
284 container arvados.Container,
285 status chan arvados.Container) {
287 log.Printf("Monitoring container %v started", container.UUID)
288 defer log.Printf("Monitoring container %v finished", container.UUID)
291 go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
293 for container = range status {
294 if container.State == dispatch.Locked || container.State == dispatch.Running {
295 if container.Priority == 0 {
296 log.Printf("Canceling container %s", container.UUID)
298 // Mutex between squeue sync and running sbatch or scancel.
299 squeueUpdater.SlurmLock.Lock()
300 err := scancelCmd(container).Run()
301 squeueUpdater.SlurmLock.Unlock()
304 log.Printf("Error stopping container %s with scancel: %v",
306 if squeueUpdater.CheckSqueue(container.UUID) {
307 log.Printf("Container %s is still in squeue after scancel.",
313 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)
320 func readConfig(dst interface{}, path string) error {
321 if buf, err := ioutil.ReadFile(path); err != nil && os.IsNotExist(err) {
322 if path == defaultConfigPath {
323 log.Printf("Config not specified. Continue with default configuration.")
325 return fmt.Errorf("Config file not found %q: %v", path, err)
327 } else if err != nil {
328 return fmt.Errorf("Error reading config %q: %v", path, err)
329 } else if err = json.Unmarshal(buf, dst); err != nil {
330 return fmt.Errorf("Error decoding config %q: %v", path, err)