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/lib/dispatchcloud"
21 "git.curoverse.com/arvados.git/sdk/go/arvados"
22 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
23 "git.curoverse.com/arvados.git/sdk/go/config"
24 "git.curoverse.com/arvados.git/sdk/go/dispatch"
25 "github.com/coreos/go-systemd/daemon"
30 defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
33 type Dispatcher struct {
35 cluster *arvados.Cluster
36 sqCheck *SqueueChecker
41 SbatchArguments []string
42 PollPeriod arvados.Duration
44 // crunch-run command to invoke. The container UUID will be
45 // appended. If nil, []string{"crunch-run"} will be used.
47 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
48 CrunchRunCommand []string
50 // Extra RAM to reserve (in Bytes) for SLURM job, in addition
51 // to the amount specified in the container's RuntimeConstraints
54 // Minimum time between two attempts to run the same container
55 MinRetryPeriod arvados.Duration
60 err := disp.Run(os.Args[0], os.Args[1:])
66 func (disp *Dispatcher) Run(prog string, args []string) error {
67 if err := disp.configure(prog, args); err != nil {
74 // configure() loads config files. Tests skip this.
75 func (disp *Dispatcher) configure(prog string, args []string) error {
76 flags := flag.NewFlagSet(prog, flag.ExitOnError)
77 flags.Usage = func() { usage(flags) }
79 configPath := flags.String(
82 "`path` to JSON or YAML configuration file")
83 dumpConfig := flag.Bool(
86 "write current configuration to stdout and exit")
87 getVersion := flags.Bool(
90 "Print version information and exit.")
91 // Parse args; omit the first arg which is the command name
94 // Print version information if requested
96 fmt.Printf("crunch-dispatch-slurm %s\n", version)
100 log.Printf("crunch-dispatch-slurm %s started", version)
102 err := disp.readConfig(*configPath)
107 if disp.CrunchRunCommand == nil {
108 disp.CrunchRunCommand = []string{"crunch-run"}
111 if disp.PollPeriod == 0 {
112 disp.PollPeriod = arvados.Duration(10 * time.Second)
115 if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
116 // Copy real configs into env vars so [a]
117 // MakeArvadosClient() uses them, and [b] they get
118 // propagated to crunch-run via SLURM.
119 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
120 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
121 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
122 if disp.Client.Insecure {
123 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
125 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(disp.Client.KeepServiceURIs, " "))
126 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
128 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
132 return config.DumpAndExit(disp)
135 siteConfig, err := arvados.GetConfig(arvados.DefaultConfigFile)
136 if os.IsNotExist(err) {
137 log.Printf("warning: no cluster config (%s), proceeding with no node types defined", err)
138 } else if err != nil {
139 return fmt.Errorf("error loading config: %s", err)
140 } else if disp.cluster, err = siteConfig.GetCluster(""); err != nil {
141 return fmt.Errorf("config error: %s", err)
147 // setup() initializes private fields after configure().
148 func (disp *Dispatcher) setup() {
149 arv, err := arvadosclient.MakeArvadosClient()
151 log.Fatalf("Error making Arvados client: %v", err)
155 disp.slurm = &slurmCLI{}
156 disp.sqCheck = &SqueueChecker{
157 Period: time.Duration(disp.PollPeriod),
160 disp.Dispatcher = &dispatch.Dispatcher{
162 RunContainer: disp.runContainer,
163 PollPeriod: time.Duration(disp.PollPeriod),
164 MinRetryPeriod: time.Duration(disp.MinRetryPeriod),
168 func (disp *Dispatcher) run() error {
169 defer disp.sqCheck.Stop()
171 if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
172 go dispatchcloud.SlurmNodeTypeFeatureKludge(disp.cluster)
175 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
176 log.Printf("Error notifying init daemon: %v", err)
178 go disp.checkSqueueForOrphans()
179 return disp.Dispatcher.Run(context.Background())
182 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
184 // Check the next squeue report, and invoke TrackContainer for all the
185 // containers in the report. This gives us a chance to cancel slurm
186 // jobs started by a previous dispatch process that never released
187 // their slurm allocations even though their container states are
188 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
189 func (disp *Dispatcher) checkSqueueForOrphans() {
190 for _, uuid := range disp.sqCheck.All() {
191 if !containerUuidPattern.MatchString(uuid) {
194 err := disp.TrackContainer(uuid)
196 log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
201 func (disp *Dispatcher) niceness(priority int) int {
208 // Niceness range 1-10000
209 return (1000 - priority) * 10
212 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
213 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM+disp.ReserveExtraRAM) / float64(1048576)))
216 for _, m := range container.Mounts {
221 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
223 var sbatchArgs []string
224 sbatchArgs = append(sbatchArgs, disp.SbatchArguments...)
225 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
226 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
227 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
228 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
229 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--nice=%d", disp.niceness(container.Priority)))
230 if len(container.SchedulingParameters.Partitions) > 0 {
231 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
234 if disp.cluster == nil {
235 // no instance types configured
236 } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
238 } else if err != nil {
241 sbatchArgs = append(sbatchArgs, "--constraint=instancetype="+it.Name)
244 return sbatchArgs, nil
247 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
248 // append() here avoids modifying crunchRunCommand's
249 // underlying array, which is shared with other goroutines.
250 crArgs := append([]string(nil), crunchRunCommand...)
251 crArgs = append(crArgs, container.UUID)
252 crScript := strings.NewReader(execScript(crArgs))
254 disp.sqCheck.L.Lock()
255 defer disp.sqCheck.L.Unlock()
257 sbArgs, err := disp.sbatchArgs(container)
261 log.Printf("running sbatch %+q", sbArgs)
262 return disp.slurm.Batch(crScript, sbArgs)
265 // Submit a container to the slurm queue (or resume monitoring if it's
266 // already in the queue). Cancel the slurm job if the container's
267 // priority changes to zero or its state indicates it's no longer
269 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
270 ctx, cancel := context.WithCancel(context.Background())
273 if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
274 log.Printf("Submitting container %s to slurm", ctr.UUID)
275 if err := disp.submit(ctr, disp.CrunchRunCommand); err != nil {
277 if err == dispatchcloud.ErrConstraintsNotSatisfiable {
278 text = fmt.Sprintf("cannot run container %s: %s", ctr.UUID, err)
279 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
281 text = fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
285 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
286 "object_uuid": ctr.UUID,
287 "event_type": "dispatch",
288 "properties": map[string]string{"text": text}}}
289 disp.Arv.Create("logs", lr, nil)
291 disp.Unlock(ctr.UUID)
296 log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
297 defer log.Printf("Done monitoring container %s", ctr.UUID)
299 // If the container disappears from the slurm queue, there is
300 // no point in waiting for further dispatch updates: just
301 // clean up and return.
302 go func(uuid string) {
303 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
311 // Disappeared from squeue
312 if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
313 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
316 case dispatch.Running:
317 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
318 case dispatch.Locked:
319 disp.Unlock(ctr.UUID)
322 case updated, ok := <-status:
324 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
326 } else if updated.Priority == 0 {
327 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
336 func (disp *Dispatcher) scancel(ctr arvados.Container) {
337 disp.sqCheck.L.Lock()
338 err := disp.slurm.Cancel(ctr.UUID)
339 disp.sqCheck.L.Unlock()
342 log.Printf("scancel: %s", err)
343 time.Sleep(time.Second)
344 } else if disp.sqCheck.HasUUID(ctr.UUID) {
345 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
346 time.Sleep(time.Second)
350 func (disp *Dispatcher) renice(ctr arvados.Container) {
351 nice := disp.niceness(ctr.Priority)
352 oldnice := disp.sqCheck.GetNiceness(ctr.UUID)
353 if nice == oldnice || oldnice == -1 {
356 log.Printf("updating slurm nice value to %d (was %d)", nice, oldnice)
357 disp.sqCheck.L.Lock()
358 err := disp.slurm.Renice(ctr.UUID, nice)
359 disp.sqCheck.L.Unlock()
362 log.Printf("renice: %s", err)
363 time.Sleep(time.Second)
366 if disp.sqCheck.HasUUID(ctr.UUID) {
367 log.Printf("container %s has arvados priority %d, slurm nice %d",
368 ctr.UUID, ctr.Priority, disp.sqCheck.GetNiceness(ctr.UUID))
372 func (disp *Dispatcher) readConfig(path string) error {
373 err := config.LoadFile(disp, path)
374 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
375 log.Printf("Config not specified. Continue with default configuration.")