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)
134 } else if len(cmd.cluster.InstanceTypes) > 0 {
135 go dispatchcloud.SlurmNodeTypeFeatureKludge(cmd.cluster)
138 if cmd.slurm == nil {
139 cmd.slurm = &slurmCLI{}
142 cmd.sqCheck = &SqueueChecker{
143 Period: time.Duration(cmd.PollPeriod),
146 defer cmd.sqCheck.Stop()
148 cmd.dispatcher = &dispatch.Dispatcher{
150 RunContainer: cmd.run,
151 PollPeriod: time.Duration(cmd.PollPeriod),
152 MinRetryPeriod: time.Duration(cmd.MinRetryPeriod),
155 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
156 log.Printf("Error notifying init daemon: %v", err)
159 go cmd.checkSqueueForOrphans()
161 return cmd.dispatcher.Run(context.Background())
164 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
166 // Check the next squeue report, and invoke TrackContainer for all the
167 // containers in the report. This gives us a chance to cancel slurm
168 // jobs started by a previous dispatch process that never released
169 // their slurm allocations even though their container states are
170 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
171 func (cmd *command) checkSqueueForOrphans() {
172 for _, uuid := range cmd.sqCheck.All() {
173 if !containerUuidPattern.MatchString(uuid) {
176 err := cmd.dispatcher.TrackContainer(uuid)
178 log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
183 func (cmd *command) niceness(priority int) int {
190 // Niceness range 1-10000
191 return (1000 - priority) * 10
194 func (cmd *command) sbatchArgs(container arvados.Container) ([]string, error) {
195 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
198 for _, m := range container.Mounts {
203 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
205 var sbatchArgs []string
206 sbatchArgs = append(sbatchArgs, cmd.SbatchArguments...)
207 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
208 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
209 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
210 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
211 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--nice=%d", cmd.niceness(container.Priority)))
212 if len(container.SchedulingParameters.Partitions) > 0 {
213 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
216 if cmd.cluster == nil {
217 // no instance types configured
218 } else if it, err := dispatchcloud.ChooseInstanceType(cmd.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
220 } else if err != nil {
223 sbatchArgs = append(sbatchArgs, "--constraint="+it.Name)
226 return sbatchArgs, nil
229 func (cmd *command) submit(container arvados.Container, crunchRunCommand []string) error {
230 // append() here avoids modifying crunchRunCommand's
231 // underlying array, which is shared with other goroutines.
232 crArgs := append([]string(nil), crunchRunCommand...)
233 crArgs = append(crArgs, container.UUID)
234 crScript := strings.NewReader(execScript(crArgs))
237 defer cmd.sqCheck.L.Unlock()
239 sbArgs, err := cmd.sbatchArgs(container)
243 log.Printf("running sbatch %+q", sbArgs)
244 return cmd.slurm.Batch(crScript, sbArgs)
247 // Submit a container to the slurm queue (or resume monitoring if it's
248 // already in the queue). Cancel the slurm job if the container's
249 // priority changes to zero or its state indicates it's no longer
251 func (cmd *command) run(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
252 ctx, cancel := context.WithCancel(context.Background())
255 if ctr.State == dispatch.Locked && !cmd.sqCheck.HasUUID(ctr.UUID) {
256 log.Printf("Submitting container %s to slurm", ctr.UUID)
257 if err := cmd.submit(ctr, cmd.CrunchRunCommand); err != nil {
259 if err == dispatchcloud.ErrConstraintsNotSatisfiable {
260 text = fmt.Sprintf("cannot run container %s: %s", ctr.UUID, err)
261 cmd.dispatcher.UpdateState(ctr.UUID, dispatch.Cancelled)
263 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 cmd.dispatcher.Arv.Create("logs", lr, nil)
273 cmd.dispatcher.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 && cmd.sqCheck.HasUUID(uuid) {
293 // Disappeared from squeue
294 if err := cmd.dispatcher.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 cmd.dispatcher.UpdateState(ctr.UUID, dispatch.Cancelled)
300 case dispatch.Locked:
301 cmd.dispatcher.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)
318 func (cmd *command) scancel(ctr arvados.Container) {
320 err := cmd.slurm.Cancel(ctr.UUID)
321 cmd.sqCheck.L.Unlock()
324 log.Printf("scancel: %s", err)
325 time.Sleep(time.Second)
326 } else if cmd.sqCheck.HasUUID(ctr.UUID) {
327 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
328 time.Sleep(time.Second)
332 func (cmd *command) renice(ctr arvados.Container) {
333 nice := cmd.niceness(ctr.Priority)
334 oldnice := cmd.sqCheck.GetNiceness(ctr.UUID)
335 if nice == oldnice || oldnice == -1 {
338 log.Printf("updating slurm nice value to %d (was %d)", nice, oldnice)
340 err := cmd.slurm.Renice(ctr.UUID, nice)
341 cmd.sqCheck.L.Unlock()
344 log.Printf("renice: %s", err)
345 time.Sleep(time.Second)
348 if cmd.sqCheck.HasUUID(ctr.UUID) {
349 log.Printf("container %s has arvados priority %d, slurm nice %d",
350 ctr.UUID, ctr.Priority, cmd.sqCheck.GetNiceness(ctr.UUID))
354 func (cmd *command) readConfig(path string) error {
355 err := config.LoadFile(cmd, path)
356 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
357 log.Printf("Config not specified. Continue with default configuration.")