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"
24 // Config used by crunch-dispatch-slurm
28 SbatchArguments []string
29 PollPeriod arvados.Duration
31 // crunch-run command to invoke. The container UUID will be
32 // appended. If nil, []string{"crunch-run"} will be used.
34 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
35 CrunchRunCommand []string
37 // Minimum time between two attempts to run the same container
38 MinRetryPeriod arvados.Duration
50 sqCheck = &SqueueChecker{}
53 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
56 flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
57 flags.Usage = func() { usage(flags) }
59 configPath := flags.String(
62 "`path` to JSON or YAML configuration file")
63 dumpConfig := flag.Bool(
66 "write current configuration to stdout and exit")
68 // Parse args; omit the first arg which is the command name
69 flags.Parse(os.Args[1:])
71 err := readConfig(&theConfig, *configPath)
76 if theConfig.CrunchRunCommand == nil {
77 theConfig.CrunchRunCommand = []string{"crunch-run"}
80 if theConfig.PollPeriod == 0 {
81 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
84 if theConfig.Client.APIHost != "" || theConfig.Client.AuthToken != "" {
85 // Copy real configs into env vars so [a]
86 // MakeArvadosClient() uses them, and [b] they get
87 // propagated to crunch-run via SLURM.
88 os.Setenv("ARVADOS_API_HOST", theConfig.Client.APIHost)
89 os.Setenv("ARVADOS_API_TOKEN", theConfig.Client.AuthToken)
90 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
91 if theConfig.Client.Insecure {
92 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
94 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
95 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
97 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
101 log.Fatal(config.DumpAndExit(theConfig))
104 arv, err := arvadosclient.MakeArvadosClient()
106 log.Printf("Error making Arvados client: %v", err)
111 sqCheck = &SqueueChecker{Period: time.Duration(theConfig.PollPeriod)}
114 dispatcher := &dispatch.Dispatcher{
117 PollPeriod: time.Duration(theConfig.PollPeriod),
118 MinRetryPeriod: time.Duration(theConfig.MinRetryPeriod),
121 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
122 log.Printf("Error notifying init daemon: %v", err)
125 return dispatcher.Run(context.Background())
129 func sbatchFunc(container arvados.Container) *exec.Cmd {
130 memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
132 var sbatchArgs []string
133 sbatchArgs = append(sbatchArgs, "--share")
134 sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
135 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
136 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
137 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
138 if len(container.SchedulingParameters.Partitions) > 0 {
139 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
142 return exec.Command("sbatch", sbatchArgs...)
146 func scancelFunc(container arvados.Container) *exec.Cmd {
147 return exec.Command("scancel", "--name="+container.UUID)
150 // Wrap these so that they can be overridden by tests
151 var sbatchCmd = sbatchFunc
152 var scancelCmd = scancelFunc
154 // Submit job to slurm using sbatch.
155 func submit(dispatcher *dispatch.Dispatcher, container arvados.Container, crunchRunCommand []string) error {
156 cmd := sbatchCmd(container)
158 // Send a tiny script on stdin to execute the crunch-run
159 // command (slurm requires this to be a #! script)
160 cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
162 var stdout, stderr bytes.Buffer
166 // Mutex between squeue sync and running sbatch or scancel.
168 defer sqCheck.L.Unlock()
170 log.Printf("exec sbatch %+q", cmd.Args)
175 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
178 case *exec.ExitError:
179 dispatcher.Unlock(container.UUID)
180 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
183 dispatcher.Unlock(container.UUID)
184 return fmt.Errorf("exec failed: %v", err)
188 // Submit a container to the slurm queue (or resume monitoring if it's
189 // already in the queue). Cancel the slurm job if the container's
190 // priority changes to zero or its state indicates it's no longer
192 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
193 ctx, cancel := context.WithCancel(context.Background())
196 if ctr.State == dispatch.Locked && !sqCheck.HasUUID(ctr.UUID) {
197 log.Printf("Submitting container %s to slurm", ctr.UUID)
198 if err := submit(disp, ctr, theConfig.CrunchRunCommand); err != nil {
199 log.Printf("Error submitting container %s to slurm: %s", ctr.UUID, err)
200 disp.Unlock(ctr.UUID)
205 log.Printf("Start monitoring container %s", ctr.UUID)
206 defer log.Printf("Done monitoring container %s", ctr.UUID)
208 // If the container disappears from the slurm queue, there is
209 // no point in waiting for further dispatch updates: just
210 // clean up and return.
211 go func(uuid string) {
212 for ctx.Err() == nil && sqCheck.HasUUID(uuid) {
220 // Disappeared from squeue
221 if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
222 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
225 case dispatch.Running:
226 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
227 case dispatch.Locked:
228 disp.Unlock(ctr.UUID)
231 case updated, ok := <-status:
233 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
235 } else if updated.Priority == 0 {
236 log.Printf("Container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
243 func scancel(ctr arvados.Container) {
245 cmd := scancelCmd(ctr)
246 msg, err := cmd.CombinedOutput()
250 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
251 time.Sleep(time.Second)
252 } else if sqCheck.HasUUID(ctr.UUID) {
253 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
254 time.Sleep(time.Second)
258 func readConfig(dst interface{}, path string) error {
259 err := config.LoadFile(dst, path)
260 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
261 log.Printf("Config not specified. Continue with default configuration.")