1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
7 // Dispatcher service for Crunch that submits containers to the slurm queue.
22 "git.curoverse.com/arvados.git/sdk/go/arvados"
23 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
24 "git.curoverse.com/arvados.git/sdk/go/config"
25 "git.curoverse.com/arvados.git/sdk/go/dispatch"
26 "github.com/coreos/go-systemd/daemon"
31 // Config used by crunch-dispatch-slurm
35 SbatchArguments []string
36 PollPeriod arvados.Duration
38 // crunch-run command to invoke. The container UUID will be
39 // appended. If nil, []string{"crunch-run"} will be used.
41 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
42 CrunchRunCommand []string
44 // Minimum time between two attempts to run the same container
45 MinRetryPeriod arvados.Duration
57 sqCheck = &SqueueChecker{}
60 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
63 flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
64 flags.Usage = func() { usage(flags) }
66 configPath := flags.String(
69 "`path` to JSON or YAML configuration file")
70 dumpConfig := flag.Bool(
73 "write current configuration to stdout and exit")
74 getVersion := flags.Bool(
77 "Print version information and exit.")
78 // Parse args; omit the first arg which is the command name
79 flags.Parse(os.Args[1:])
81 // Print version information if requested
83 fmt.Printf("crunch-dispatch-slurm %s\n", version)
87 log.Printf("crunch-dispatch-slurm %s started", version)
89 err := readConfig(&theConfig, *configPath)
94 if theConfig.CrunchRunCommand == nil {
95 theConfig.CrunchRunCommand = []string{"crunch-run"}
98 if theConfig.PollPeriod == 0 {
99 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
102 if theConfig.Client.APIHost != "" || theConfig.Client.AuthToken != "" {
103 // Copy real configs into env vars so [a]
104 // MakeArvadosClient() uses them, and [b] they get
105 // propagated to crunch-run via SLURM.
106 os.Setenv("ARVADOS_API_HOST", theConfig.Client.APIHost)
107 os.Setenv("ARVADOS_API_TOKEN", theConfig.Client.AuthToken)
108 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
109 if theConfig.Client.Insecure {
110 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
112 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
113 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
115 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
119 log.Fatal(config.DumpAndExit(theConfig))
122 arv, err := arvadosclient.MakeArvadosClient()
124 log.Printf("Error making Arvados client: %v", err)
129 sqCheck = &SqueueChecker{Period: time.Duration(theConfig.PollPeriod)}
132 dispatcher := &dispatch.Dispatcher{
135 PollPeriod: time.Duration(theConfig.PollPeriod),
136 MinRetryPeriod: time.Duration(theConfig.MinRetryPeriod),
139 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
140 log.Printf("Error notifying init daemon: %v", err)
143 go checkSqueueForOrphans(dispatcher, sqCheck)
145 return dispatcher.Run(context.Background())
148 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
150 // Check the next squeue report, and invoke TrackContainer for all the
151 // containers in the report. This gives us a chance to cancel slurm
152 // jobs started by a previous dispatch process that never released
153 // their slurm allocations even though their container states are
154 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
155 func checkSqueueForOrphans(dispatcher *dispatch.Dispatcher, sqCheck *SqueueChecker) {
156 for _, uuid := range sqCheck.All() {
157 if !containerUuidPattern.MatchString(uuid) {
160 err := dispatcher.TrackContainer(uuid)
162 log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
167 func niceness(priority int) int {
174 // Niceness range 1-10000
175 return (1000 - priority) * 10
179 func sbatchFunc(container arvados.Container) *exec.Cmd {
180 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
183 for _, m := range container.Mounts {
188 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
190 var sbatchArgs []string
191 sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
192 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
193 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
194 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
195 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
196 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--nice=%d", niceness(container.Priority)))
197 if len(container.SchedulingParameters.Partitions) > 0 {
198 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
201 return exec.Command("sbatch", sbatchArgs...)
205 func scancelFunc(container arvados.Container) *exec.Cmd {
206 return exec.Command("scancel", "--name="+container.UUID)
210 func scontrolFunc(container arvados.Container) *exec.Cmd {
211 return exec.Command("scontrol", "update", "JobName="+container.UUID, fmt.Sprintf("Nice=%d", niceness(container.Priority)))
214 // Wrap these so that they can be overridden by tests
215 var sbatchCmd = sbatchFunc
216 var scancelCmd = scancelFunc
217 var scontrolCmd = scontrolFunc
219 // Submit job to slurm using sbatch.
220 func submit(dispatcher *dispatch.Dispatcher, container arvados.Container, crunchRunCommand []string) error {
221 cmd := sbatchCmd(container)
223 // Send a tiny script on stdin to execute the crunch-run
224 // command (slurm requires this to be a #! script)
225 cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
227 var stdout, stderr bytes.Buffer
231 // Mutex between squeue sync and running sbatch or scancel.
233 defer sqCheck.L.Unlock()
235 log.Printf("exec sbatch %+q", cmd.Args)
240 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
243 case *exec.ExitError:
244 dispatcher.Unlock(container.UUID)
245 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
248 dispatcher.Unlock(container.UUID)
249 return fmt.Errorf("exec failed: %v", err)
253 // Submit a container to the slurm queue (or resume monitoring if it's
254 // already in the queue). Cancel the slurm job if the container's
255 // priority changes to zero or its state indicates it's no longer
257 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
258 ctx, cancel := context.WithCancel(context.Background())
261 if ctr.State == dispatch.Locked && !sqCheck.HasUUID(ctr.UUID) {
262 log.Printf("Submitting container %s to slurm", ctr.UUID)
263 if err := submit(disp, ctr, theConfig.CrunchRunCommand); err != nil {
264 text := fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
267 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
268 "object_uuid": ctr.UUID,
269 "event_type": "dispatch",
270 "properties": map[string]string{"text": text}}}
271 disp.Arv.Create("logs", lr, nil)
273 disp.Unlock(ctr.UUID)
278 log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
279 defer log.Printf("Done monitoring container %s", ctr.UUID)
281 // If the container disappears from the slurm queue, there is
282 // no point in waiting for further dispatch updates: just
283 // clean up and return.
284 go func(uuid string) {
285 for ctx.Err() == nil && sqCheck.HasUUID(uuid) {
293 // Disappeared from squeue
294 if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
295 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
298 case dispatch.Running:
299 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
300 case dispatch.Locked:
301 disp.Unlock(ctr.UUID)
304 case updated, ok := <-status:
306 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
308 } else if updated.Priority == 0 {
309 log.Printf("Container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
311 } else if niceness(updated.Priority) != sqCheck.GetNiceness(ctr.UUID) && sqCheck.GetNiceness(ctr.UUID) != -1 {
312 // dynamically adjust priority
313 log.Printf("Container priority %v != %v", niceness(updated.Priority), sqCheck.GetNiceness(ctr.UUID))
314 scontrolUpdate(updated)
320 func scancel(ctr arvados.Container) {
322 cmd := scancelCmd(ctr)
323 msg, err := cmd.CombinedOutput()
327 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
328 time.Sleep(time.Second)
329 } else if sqCheck.HasUUID(ctr.UUID) {
330 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
331 time.Sleep(time.Second)
335 func scontrolUpdate(ctr arvados.Container) {
337 cmd := scontrolCmd(ctr)
338 msg, err := cmd.CombinedOutput()
342 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
343 time.Sleep(time.Second)
344 } else if sqCheck.HasUUID(ctr.UUID) {
345 log.Printf("Container %s priority is now %v, niceness is now %v",
346 ctr.UUID, ctr.Priority, sqCheck.GetNiceness(ctr.UUID))
350 func readConfig(dst interface{}, path string) error {
351 err := config.LoadFile(dst, path)
352 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
353 log.Printf("Config not specified. Continue with default configuration.")