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("Version: %s\n", version)
87 log.Printf("crunch-dispatch-slurm %q 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)
168 func sbatchFunc(container arvados.Container) *exec.Cmd {
169 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
172 for _, m := range container.Mounts {
177 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
179 var sbatchArgs []string
180 sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
181 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
182 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
183 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
184 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
185 if len(container.SchedulingParameters.Partitions) > 0 {
186 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
189 return exec.Command("sbatch", sbatchArgs...)
193 func scancelFunc(container arvados.Container) *exec.Cmd {
194 return exec.Command("scancel", "--name="+container.UUID)
197 // Wrap these so that they can be overridden by tests
198 var sbatchCmd = sbatchFunc
199 var scancelCmd = scancelFunc
201 // Submit job to slurm using sbatch.
202 func submit(dispatcher *dispatch.Dispatcher, container arvados.Container, crunchRunCommand []string) error {
203 cmd := sbatchCmd(container)
205 // Send a tiny script on stdin to execute the crunch-run
206 // command (slurm requires this to be a #! script)
207 cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
209 var stdout, stderr bytes.Buffer
213 // Mutex between squeue sync and running sbatch or scancel.
215 defer sqCheck.L.Unlock()
217 log.Printf("exec sbatch %+q", cmd.Args)
222 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
225 case *exec.ExitError:
226 dispatcher.Unlock(container.UUID)
227 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
230 dispatcher.Unlock(container.UUID)
231 return fmt.Errorf("exec failed: %v", err)
235 // Submit a container to the slurm queue (or resume monitoring if it's
236 // already in the queue). Cancel the slurm job if the container's
237 // priority changes to zero or its state indicates it's no longer
239 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
240 ctx, cancel := context.WithCancel(context.Background())
243 if ctr.State == dispatch.Locked && !sqCheck.HasUUID(ctr.UUID) {
244 log.Printf("Submitting container %s to slurm", ctr.UUID)
245 if err := submit(disp, ctr, theConfig.CrunchRunCommand); err != nil {
246 text := fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
249 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
250 "object_uuid": ctr.UUID,
251 "event_type": "dispatch",
252 "properties": map[string]string{"text": text}}}
253 disp.Arv.Create("logs", lr, nil)
255 disp.Unlock(ctr.UUID)
260 log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
261 defer log.Printf("Done monitoring container %s", ctr.UUID)
263 // If the container disappears from the slurm queue, there is
264 // no point in waiting for further dispatch updates: just
265 // clean up and return.
266 go func(uuid string) {
267 for ctx.Err() == nil && sqCheck.HasUUID(uuid) {
275 // Disappeared from squeue
276 if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
277 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
280 case dispatch.Running:
281 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
282 case dispatch.Locked:
283 disp.Unlock(ctr.UUID)
286 case updated, ok := <-status:
288 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
290 } else if updated.Priority == 0 {
291 log.Printf("Container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
298 func scancel(ctr arvados.Container) {
300 cmd := scancelCmd(ctr)
301 msg, err := cmd.CombinedOutput()
305 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
306 time.Sleep(time.Second)
307 } else if sqCheck.HasUUID(ctr.UUID) {
308 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
309 time.Sleep(time.Second)
313 func readConfig(dst interface{}, path string) error {
314 err := config.LoadFile(dst, path)
315 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
316 log.Printf("Config not specified. Continue with default configuration.")