3 // Dispatcher service for Crunch that submits containers to the slurm queue.
16 "git.curoverse.com/arvados.git/sdk/go/arvados"
17 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
18 "git.curoverse.com/arvados.git/sdk/go/config"
19 "git.curoverse.com/arvados.git/sdk/go/dispatch"
20 "github.com/coreos/go-systemd/daemon"
23 // Config used by crunch-dispatch-slurm
27 SbatchArguments []string
28 PollPeriod arvados.Duration
30 // crunch-run command to invoke. The container UUID will be
31 // appended. If nil, []string{"crunch-run"} will be used.
33 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
34 CrunchRunCommand []string
36 // Minimum time between two attempts to run the same container
37 MinRetryPeriod arvados.Duration
52 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
55 flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
56 flags.Usage = func() { usage(flags) }
58 configPath := flags.String(
61 "`path` to JSON or YAML configuration file")
62 dumpConfig := flag.Bool(
65 "write current configuration to stdout and exit")
67 // Parse args; omit the first arg which is the command name
68 flags.Parse(os.Args[1:])
70 err := readConfig(&theConfig, *configPath)
75 if theConfig.CrunchRunCommand == nil {
76 theConfig.CrunchRunCommand = []string{"crunch-run"}
79 if theConfig.PollPeriod == 0 {
80 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
83 if theConfig.Client.APIHost != "" || theConfig.Client.AuthToken != "" {
84 // Copy real configs into env vars so [a]
85 // MakeArvadosClient() uses them, and [b] they get
86 // propagated to crunch-run via SLURM.
87 os.Setenv("ARVADOS_API_HOST", theConfig.Client.APIHost)
88 os.Setenv("ARVADOS_API_TOKEN", theConfig.Client.AuthToken)
89 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
90 if theConfig.Client.Insecure {
91 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
93 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
94 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
96 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
100 log.Fatal(config.DumpAndExit(theConfig))
103 arv, err := arvadosclient.MakeArvadosClient()
105 log.Printf("Error making Arvados client: %v", err)
110 sqCheck = SqueueChecker{Period: time.Duration(theConfig.PollPeriod)}
113 dispatcher := dispatch.Dispatcher{
116 PollPeriod: time.Duration(theConfig.PollPeriod),
117 MinRetryPeriod: time.Duration(theConfig.MinRetryPeriod),
120 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
121 log.Printf("Error notifying init daemon: %v", err)
124 return dispatcher.Run()
128 func sbatchFunc(container arvados.Container) *exec.Cmd {
129 memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
131 var sbatchArgs []string
132 sbatchArgs = append(sbatchArgs, "--share")
133 sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
134 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
135 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
136 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
137 if container.SchedulingParameters.Partitions != nil {
138 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
141 return exec.Command("sbatch", sbatchArgs...)
145 func scancelFunc(container arvados.Container) *exec.Cmd {
146 return exec.Command("scancel", "--name="+container.UUID)
149 // Wrap these so that they can be overridden by tests
150 var sbatchCmd = sbatchFunc
151 var scancelCmd = scancelFunc
153 // Submit job to slurm using sbatch.
154 func submit(dispatcher *dispatch.Dispatcher,
155 container arvados.Container, crunchRunCommand []string) (submitErr error) {
157 // If we didn't get as far as submitting a slurm job,
158 // unlock the container and return it to the queue.
159 if submitErr == nil {
160 // OK, no cleanup needed
163 dispatcher.Unlock(container.UUID)
166 cmd := sbatchCmd(container)
168 // Send a tiny script on stdin to execute the crunch-run
169 // command (slurm requires this to be a #! script)
170 cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
172 var stdout, stderr bytes.Buffer
176 // Mutex between squeue sync and running sbatch or scancel.
178 defer sqCheck.L.Unlock()
180 log.Printf("exec sbatch %+q", cmd.Args)
184 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
186 case *exec.ExitError:
187 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr)
189 return fmt.Errorf("exec failed: %v", err)
193 // If the container is marked as Locked, check if it is already in the slurm
194 // queue. If not, submit it.
196 // If the container is marked as Running, check if it is in the slurm queue.
197 // If not, mark it as Cancelled.
198 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
201 if sqCheck.HasUUID(container.UUID) {
202 // Found in the queue, so continue monitoring
204 } else if container.State == dispatch.Locked && !submitted {
205 // Not in queue but in Locked state and we haven't
206 // submitted it yet, so submit it.
208 log.Printf("About to submit queued container %v", container.UUID)
210 if err := submit(dispatcher, container, theConfig.CrunchRunCommand); err != nil {
211 log.Printf("Error submitting container %s to slurm: %v",
213 // maybe sbatch is broken, put it back to queued
214 dispatcher.Unlock(container.UUID)
218 // Not in queue and we are not going to submit it.
219 // Refresh the container state. If it is
220 // Complete/Cancelled, do nothing, if it is Locked then
221 // release it back to the Queue, if it is Running then
222 // clean up the record.
224 var con arvados.Container
225 err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
227 log.Printf("Error getting final container state: %v", err)
231 case dispatch.Locked:
232 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
233 container.UUID, con.State, dispatch.Queued)
234 dispatcher.Unlock(container.UUID)
235 case dispatch.Running:
236 st := dispatch.Cancelled
237 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
238 container.UUID, con.State, st)
239 dispatcher.UpdateState(container.UUID, st)
241 // Container state is Queued, Complete or Cancelled so stop monitoring it.
248 // Run or monitor a container.
250 // Monitor status updates. If the priority changes to zero, cancel the
251 // container using scancel.
252 func run(dispatcher *dispatch.Dispatcher,
253 container arvados.Container,
254 status chan arvados.Container) {
256 log.Printf("Monitoring container %v started", container.UUID)
257 defer log.Printf("Monitoring container %v finished", container.UUID)
260 go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
262 for container = range status {
263 if container.Priority == 0 && (container.State == dispatch.Locked || container.State == dispatch.Running) {
264 log.Printf("Canceling container %s", container.UUID)
265 // Mutex between squeue sync and running sbatch or scancel.
267 cmd := scancelCmd(container)
268 msg, err := cmd.CombinedOutput()
272 log.Printf("Error stopping container %s with %v %v: %v %v", container.UUID, cmd.Path, cmd.Args, err, string(msg))
273 if sqCheck.HasUUID(container.UUID) {
274 log.Printf("Container %s is still in squeue after scancel.", container.UUID)
279 // Ignore errors; if necessary, we'll try again next time
280 dispatcher.UpdateState(container.UUID, dispatch.Cancelled)
286 func readConfig(dst interface{}, path string) error {
287 err := config.LoadFile(dst, path)
288 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
289 log.Printf("Config not specified. Continue with default configuration.")