3 // Dispatcher service for Crunch that submits containers to the slurm queue.
17 "git.curoverse.com/arvados.git/sdk/go/arvados"
18 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
19 "git.curoverse.com/arvados.git/sdk/go/config"
20 "git.curoverse.com/arvados.git/sdk/go/dispatch"
21 "github.com/coreos/go-systemd/daemon"
22 "github.com/ghodss/yaml"
25 // Config used by crunch-dispatch-slurm
29 SbatchArguments []string
30 PollPeriod arvados.Duration
32 // crunch-run command to invoke. The container UUID will be
33 // appended. If nil, []string{"crunch-run"} will be used.
35 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
36 CrunchRunCommand []string
51 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
54 flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
55 flags.Usage = func() { usage(flags) }
57 configPath := flags.String(
60 "`path` to JSON or YAML configuration file")
61 dumpConfig := flag.Bool(
64 "write current configuration to stdout and exit")
66 // Parse args; omit the first arg which is the command name
67 flags.Parse(os.Args[1:])
69 err := readConfig(&theConfig, *configPath)
74 if theConfig.CrunchRunCommand == nil {
75 theConfig.CrunchRunCommand = []string{"crunch-run"}
78 if theConfig.PollPeriod == 0 {
79 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
82 if theConfig.Client.APIHost != "" || theConfig.Client.AuthToken != "" {
83 // Copy real configs into env vars so [a]
84 // MakeArvadosClient() uses them, and [b] they get
85 // propagated to crunch-run via SLURM.
86 os.Setenv("ARVADOS_API_HOST", theConfig.Client.APIHost)
87 os.Setenv("ARVADOS_API_TOKEN", theConfig.Client.AuthToken)
88 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
89 if theConfig.Client.Insecure {
90 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
92 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
93 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
95 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
99 y, err := yaml.Marshal(theConfig)
107 arv, err := arvadosclient.MakeArvadosClient()
109 log.Printf("Error making Arvados client: %v", err)
114 squeueUpdater.StartMonitor(time.Duration(theConfig.PollPeriod))
115 defer squeueUpdater.Done()
117 dispatcher := dispatch.Dispatcher{
120 PollInterval: time.Duration(theConfig.PollPeriod),
121 DoneProcessing: make(chan struct{})}
123 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
124 log.Printf("Error notifying init daemon: %v", err)
127 err = dispatcher.RunDispatcher()
136 func sbatchFunc(container arvados.Container) *exec.Cmd {
137 memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
139 var sbatchArgs []string
140 sbatchArgs = append(sbatchArgs, "--share")
141 sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
142 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
143 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
144 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
145 if container.SchedulingParameters.Partitions != nil {
146 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
149 return exec.Command("sbatch", sbatchArgs...)
153 func scancelFunc(container arvados.Container) *exec.Cmd {
154 return exec.Command("scancel", "--name="+container.UUID)
157 // Wrap these so that they can be overridden by tests
158 var sbatchCmd = sbatchFunc
159 var scancelCmd = scancelFunc
161 // Submit job to slurm using sbatch.
162 func submit(dispatcher *dispatch.Dispatcher,
163 container arvados.Container, crunchRunCommand []string) (submitErr error) {
165 // If we didn't get as far as submitting a slurm job,
166 // unlock the container and return it to the queue.
167 if submitErr == nil {
168 // OK, no cleanup needed
171 err := dispatcher.Unlock(container.UUID)
173 log.Printf("Error unlocking container %s: %v", container.UUID, err)
177 // Create the command and attach to stdin/stdout
178 cmd := sbatchCmd(container)
179 stdinWriter, stdinerr := cmd.StdinPipe()
181 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
185 stdoutReader, stdoutErr := cmd.StdoutPipe()
186 if stdoutErr != nil {
187 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
191 stderrReader, stderrErr := cmd.StderrPipe()
192 if stderrErr != nil {
193 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
197 // Mutex between squeue sync and running sbatch or scancel.
198 squeueUpdater.SlurmLock.Lock()
199 defer squeueUpdater.SlurmLock.Unlock()
201 log.Printf("sbatch starting: %+q", cmd.Args)
204 submitErr = fmt.Errorf("Error starting sbatch: %v", err)
208 stdoutChan := make(chan []byte)
210 b, _ := ioutil.ReadAll(stdoutReader)
216 stderrChan := make(chan []byte)
218 b, _ := ioutil.ReadAll(stderrReader)
224 // Send a tiny script on stdin to execute the crunch-run command
225 // slurm actually enforces that this must be a #! script
226 io.WriteString(stdinWriter, execScript(append(crunchRunCommand, container.UUID)))
229 stdoutMsg := <-stdoutChan
230 stderrmsg := <-stderrChan
235 submitErr = fmt.Errorf("Container submission failed: %v: %v (stderr: %q)", cmd.Args, err, stderrmsg)
239 log.Printf("sbatch succeeded: %s", strings.TrimSpace(string(stdoutMsg)))
243 // If the container is marked as Locked, check if it is already in the slurm
244 // queue. If not, submit it.
246 // If the container is marked as Running, check if it is in the slurm queue.
247 // If not, mark it as Cancelled.
248 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
251 if squeueUpdater.CheckSqueue(container.UUID) {
252 // Found in the queue, so continue monitoring
254 } else if container.State == dispatch.Locked && !submitted {
255 // Not in queue but in Locked state and we haven't
256 // submitted it yet, so submit it.
258 log.Printf("About to submit queued container %v", container.UUID)
260 if err := submit(dispatcher, container, theConfig.CrunchRunCommand); err != nil {
261 log.Printf("Error submitting container %s to slurm: %v",
263 // maybe sbatch is broken, put it back to queued
264 dispatcher.Unlock(container.UUID)
268 // Not in queue and we are not going to submit it.
269 // Refresh the container state. If it is
270 // Complete/Cancelled, do nothing, if it is Locked then
271 // release it back to the Queue, if it is Running then
272 // clean up the record.
274 var con arvados.Container
275 err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
277 log.Printf("Error getting final container state: %v", err)
281 case dispatch.Locked:
282 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
283 container.UUID, con.State, dispatch.Queued)
284 dispatcher.Unlock(container.UUID)
285 case dispatch.Running:
286 st := dispatch.Cancelled
287 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
288 container.UUID, con.State, st)
289 dispatcher.UpdateState(container.UUID, st)
291 // Container state is Queued, Complete or Cancelled so stop monitoring it.
298 // Run or monitor a container.
300 // Monitor status updates. If the priority changes to zero, cancel the
301 // container using scancel.
302 func run(dispatcher *dispatch.Dispatcher,
303 container arvados.Container,
304 status chan arvados.Container) {
306 log.Printf("Monitoring container %v started", container.UUID)
307 defer log.Printf("Monitoring container %v finished", container.UUID)
310 go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
312 for container = range status {
313 if container.State == dispatch.Locked || container.State == dispatch.Running {
314 if container.Priority == 0 {
315 log.Printf("Canceling container %s", container.UUID)
317 // Mutex between squeue sync and running sbatch or scancel.
318 squeueUpdater.SlurmLock.Lock()
319 cmd := scancelCmd(container)
320 msg, err := cmd.CombinedOutput()
321 squeueUpdater.SlurmLock.Unlock()
324 log.Printf("Error stopping container %s with %v %v: %v %v",
325 container.UUID, cmd.Path, cmd.Args, err, string(msg))
326 if squeueUpdater.CheckSqueue(container.UUID) {
327 log.Printf("Container %s is still in squeue after scancel.",
333 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)
340 func readConfig(dst interface{}, path string) error {
341 err := config.LoadFile(dst, path)
342 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
343 log.Printf("Config not specified. Continue with default configuration.")