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.
20 "git.curoverse.com/arvados.git/sdk/go/arvados"
21 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
22 "git.curoverse.com/arvados.git/sdk/go/config"
23 "git.curoverse.com/arvados.git/sdk/go/dispatch"
24 "git.curoverse.com/arvados.git/services/dispatchcloud"
25 "github.com/coreos/go-systemd/daemon"
31 dispatcher *dispatch.Dispatcher
32 cluster *arvados.Cluster
33 sqCheck *SqueueChecker
38 SbatchArguments []string
39 PollPeriod arvados.Duration
41 // crunch-run command to invoke. The container UUID will be
42 // appended. If nil, []string{"crunch-run"} will be used.
44 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
45 CrunchRunCommand []string
47 // Minimum time between two attempts to run the same container
48 MinRetryPeriod arvados.Duration
52 err := (&command{}).Run(os.Args[0], os.Args[1:])
58 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
60 func (cmd *command) Run(prog string, args []string) error {
61 flags := flag.NewFlagSet(prog, flag.ExitOnError)
62 flags.Usage = func() { usage(flags) }
64 configPath := flags.String(
67 "`path` to JSON or YAML configuration file")
68 dumpConfig := flag.Bool(
71 "write current configuration to stdout and exit")
72 getVersion := flags.Bool(
75 "Print version information and exit.")
76 // Parse args; omit the first arg which is the command name
79 // Print version information if requested
81 fmt.Printf("crunch-dispatch-slurm %s\n", version)
85 log.Printf("crunch-dispatch-slurm %s started", version)
87 err := cmd.readConfig(*configPath)
92 if cmd.CrunchRunCommand == nil {
93 cmd.CrunchRunCommand = []string{"crunch-run"}
96 if cmd.PollPeriod == 0 {
97 cmd.PollPeriod = arvados.Duration(10 * time.Second)
100 if cmd.Client.APIHost != "" || cmd.Client.AuthToken != "" {
101 // Copy real configs into env vars so [a]
102 // MakeArvadosClient() uses them, and [b] they get
103 // propagated to crunch-run via SLURM.
104 os.Setenv("ARVADOS_API_HOST", cmd.Client.APIHost)
105 os.Setenv("ARVADOS_API_TOKEN", cmd.Client.AuthToken)
106 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
107 if cmd.Client.Insecure {
108 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
110 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(cmd.Client.KeepServiceURIs, " "))
111 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
113 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
117 log.Fatal(config.DumpAndExit(cmd))
120 arv, err := arvadosclient.MakeArvadosClient()
122 log.Printf("Error making Arvados client: %v", err)
127 siteConfig, err := arvados.GetConfig(arvados.DefaultConfigFile)
128 if os.IsNotExist(err) {
129 log.Printf("warning: no cluster config file %q (%s), proceeding with no node types defined", arvados.DefaultConfigFile, err)
130 } else if err != nil {
131 log.Fatalf("error loading config: %s", err)
132 } else if cmd.cluster, err = siteConfig.GetCluster(""); err != nil {
133 log.Fatalf("config error: %s", err)
136 if cmd.slurm == nil {
137 cmd.slurm = &slurmCLI{}
140 cmd.sqCheck = &SqueueChecker{
141 Period: time.Duration(cmd.PollPeriod),
144 defer cmd.sqCheck.Stop()
146 cmd.dispatcher = &dispatch.Dispatcher{
148 RunContainer: cmd.run,
149 PollPeriod: time.Duration(cmd.PollPeriod),
150 MinRetryPeriod: time.Duration(cmd.MinRetryPeriod),
153 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
154 log.Printf("Error notifying init daemon: %v", err)
157 go cmd.checkSqueueForOrphans()
159 return cmd.dispatcher.Run(context.Background())
162 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
164 // Check the next squeue report, and invoke TrackContainer for all the
165 // containers in the report. This gives us a chance to cancel slurm
166 // jobs started by a previous dispatch process that never released
167 // their slurm allocations even though their container states are
168 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
169 func (cmd *command) checkSqueueForOrphans() {
170 for _, uuid := range cmd.sqCheck.All() {
171 if !containerUuidPattern.MatchString(uuid) {
174 err := cmd.dispatcher.TrackContainer(uuid)
176 log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
181 func (cmd *command) niceness(priority int) int {
188 // Niceness range 1-10000
189 return (1000 - priority) * 10
192 func (cmd *command) sbatchArgs(container arvados.Container) ([]string, error) {
193 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
196 for _, m := range container.Mounts {
201 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
203 var sbatchArgs []string
204 sbatchArgs = append(sbatchArgs, cmd.SbatchArguments...)
205 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
206 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
207 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
208 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
209 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--nice=%d", cmd.niceness(container.Priority)))
210 if len(container.SchedulingParameters.Partitions) > 0 {
211 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
214 return sbatchArgs, nil
217 func (cmd *command) submit(container arvados.Container, crunchRunCommand []string) error {
218 // append() here avoids modifying crunchRunCommand's
219 // underlying array, which is shared with other goroutines.
220 crArgs := append([]string(nil), crunchRunCommand...)
221 crArgs = append(crArgs, container.UUID)
222 crScript := strings.NewReader(execScript(crArgs))
225 defer cmd.sqCheck.L.Unlock()
227 sbArgs, err := cmd.sbatchArgs(container)
231 log.Printf("running sbatch %+q", sbArgs)
232 return cmd.slurm.Batch(crScript, sbArgs)
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 (cmd *command) run(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
240 ctx, cancel := context.WithCancel(context.Background())
243 if ctr.State == dispatch.Locked && !cmd.sqCheck.HasUUID(ctr.UUID) {
244 log.Printf("Submitting container %s to slurm", ctr.UUID)
245 if err := cmd.submit(ctr, cmd.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 cmd.dispatcher.Arv.Create("logs", lr, nil)
255 cmd.dispatcher.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 && cmd.sqCheck.HasUUID(uuid) {
275 // Disappeared from squeue
276 if err := cmd.dispatcher.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 cmd.dispatcher.UpdateState(ctr.UUID, dispatch.Cancelled)
282 case dispatch.Locked:
283 cmd.dispatcher.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)
300 func (cmd *command) scancel(ctr arvados.Container) {
302 err := cmd.slurm.Cancel(ctr.UUID)
303 cmd.sqCheck.L.Unlock()
306 log.Printf("scancel: %s", err)
307 time.Sleep(time.Second)
308 } else if cmd.sqCheck.HasUUID(ctr.UUID) {
309 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
310 time.Sleep(time.Second)
314 func (cmd *command) renice(ctr arvados.Container) {
315 nice := cmd.niceness(ctr.Priority)
316 oldnice := cmd.sqCheck.GetNiceness(ctr.UUID)
317 if nice == oldnice || oldnice == -1 {
320 log.Printf("updating slurm nice value to %d (was %d)", nice, oldnice)
322 err := cmd.slurm.Renice(ctr.UUID, nice)
323 cmd.sqCheck.L.Unlock()
326 log.Printf("renice: %s", err)
327 time.Sleep(time.Second)
330 if cmd.sqCheck.HasUUID(ctr.UUID) {
331 log.Printf("container %s has arvados priority %d, slurm nice %d",
332 ctr.UUID, ctr.Priority, cmd.sqCheck.GetNiceness(ctr.UUID))
336 func (cmd *command) readConfig(path string) error {
337 err := config.LoadFile(cmd, path)
338 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
339 log.Printf("Config not specified. Continue with default configuration.")