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.
21 "git.curoverse.com/arvados.git/lib/dispatchcloud"
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"
29 const initialNiceValue int64 = 10000
33 defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
36 type Dispatcher struct {
38 cluster *arvados.Cluster
39 sqCheck *SqueueChecker
44 SbatchArguments []string
45 PollPeriod arvados.Duration
48 // crunch-run command to invoke. The container UUID will be
49 // appended. If nil, []string{"crunch-run"} will be used.
51 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
52 CrunchRunCommand []string
54 // Extra RAM to reserve (in Bytes) for SLURM job, in addition
55 // to the amount specified in the container's RuntimeConstraints
58 // Minimum time between two attempts to run the same container
59 MinRetryPeriod arvados.Duration
61 // Batch size for container queries
67 err := disp.Run(os.Args[0], os.Args[1:])
73 func (disp *Dispatcher) Run(prog string, args []string) error {
74 if err := disp.configure(prog, args); err != nil {
81 // configure() loads config files. Tests skip this.
82 func (disp *Dispatcher) configure(prog string, args []string) error {
83 flags := flag.NewFlagSet(prog, flag.ExitOnError)
84 flags.Usage = func() { usage(flags) }
86 configPath := flags.String(
89 "`path` to JSON or YAML configuration file")
90 dumpConfig := flag.Bool(
93 "write current configuration to stdout and exit")
94 getVersion := flags.Bool(
97 "Print version information and exit.")
98 // Parse args; omit the first arg which is the command name
101 // Print version information if requested
103 fmt.Printf("crunch-dispatch-slurm %s\n", version)
107 log.Printf("crunch-dispatch-slurm %s started", version)
109 err := disp.readConfig(*configPath)
114 if disp.CrunchRunCommand == nil {
115 disp.CrunchRunCommand = []string{"crunch-run"}
118 if disp.PollPeriod == 0 {
119 disp.PollPeriod = arvados.Duration(10 * time.Second)
122 if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
123 // Copy real configs into env vars so [a]
124 // MakeArvadosClient() uses them, and [b] they get
125 // propagated to crunch-run via SLURM.
126 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
127 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
128 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
129 if disp.Client.Insecure {
130 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
132 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(disp.Client.KeepServiceURIs, " "))
133 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
135 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
139 return config.DumpAndExit(disp)
142 siteConfig, err := arvados.GetConfig(arvados.DefaultConfigFile)
143 if os.IsNotExist(err) {
144 log.Printf("warning: no cluster config (%s), proceeding with no node types defined", err)
145 } else if err != nil {
146 return fmt.Errorf("error loading config: %s", err)
147 } else if disp.cluster, err = siteConfig.GetCluster(""); err != nil {
148 return fmt.Errorf("config error: %s", err)
154 // setup() initializes private fields after configure().
155 func (disp *Dispatcher) setup() {
156 arv, err := arvadosclient.MakeArvadosClient()
158 log.Fatalf("Error making Arvados client: %v", err)
162 disp.slurm = NewSlurmCLI()
163 disp.sqCheck = &SqueueChecker{
164 Period: time.Duration(disp.PollPeriod),
165 PrioritySpread: disp.PrioritySpread,
168 disp.Dispatcher = &dispatch.Dispatcher{
170 BatchSize: disp.BatchSize,
171 RunContainer: disp.runContainer,
172 PollPeriod: time.Duration(disp.PollPeriod),
173 MinRetryPeriod: time.Duration(disp.MinRetryPeriod),
177 func (disp *Dispatcher) run() error {
178 defer disp.sqCheck.Stop()
180 if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
181 go dispatchcloud.SlurmNodeTypeFeatureKludge(disp.cluster)
184 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
185 log.Printf("Error notifying init daemon: %v", err)
187 go disp.checkSqueueForOrphans()
188 return disp.Dispatcher.Run(context.Background())
191 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
193 // Check the next squeue report, and invoke TrackContainer for all the
194 // containers in the report. This gives us a chance to cancel slurm
195 // jobs started by a previous dispatch process that never released
196 // their slurm allocations even though their container states are
197 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
198 func (disp *Dispatcher) checkSqueueForOrphans() {
199 for _, uuid := range disp.sqCheck.All() {
200 if !containerUuidPattern.MatchString(uuid) {
203 err := disp.TrackContainer(uuid)
205 log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
210 func (disp *Dispatcher) slurmConstraintArgs(container arvados.Container) []string {
211 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM+disp.ReserveExtraRAM) / float64(1048576)))
214 for _, m := range container.Mounts {
219 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
221 fmt.Sprintf("--mem=%d", mem),
222 fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs),
223 fmt.Sprintf("--tmp=%d", disk),
227 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
229 args = append(args, disp.SbatchArguments...)
230 args = append(args, "--job-name="+container.UUID, fmt.Sprintf("--nice=%d", initialNiceValue))
232 if disp.cluster == nil {
233 // no instance types configured
234 args = append(args, disp.slurmConstraintArgs(container)...)
235 } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
237 args = append(args, disp.slurmConstraintArgs(container)...)
238 } else if err != nil {
241 // use instancetype constraint instead of slurm mem/cpu/tmp specs
242 args = append(args, "--constraint=instancetype="+it.Name)
245 if len(container.SchedulingParameters.Partitions) > 0 {
246 args = append(args, "--partition="+strings.Join(container.SchedulingParameters.Partitions, ","))
252 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
253 // append() here avoids modifying crunchRunCommand's
254 // underlying array, which is shared with other goroutines.
255 crArgs := append([]string(nil), crunchRunCommand...)
256 crArgs = append(crArgs, container.UUID)
257 crScript := strings.NewReader(execScript(crArgs))
259 sbArgs, err := disp.sbatchArgs(container)
263 log.Printf("running sbatch %+q", sbArgs)
264 return disp.slurm.Batch(crScript, sbArgs)
267 // Submit a container to the slurm queue (or resume monitoring if it's
268 // already in the queue). Cancel the slurm job if the container's
269 // priority changes to zero or its state indicates it's no longer
271 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
272 ctx, cancel := context.WithCancel(context.Background())
275 if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
276 log.Printf("Submitting container %s to slurm", ctr.UUID)
277 if err := disp.submit(ctr, disp.CrunchRunCommand); err != nil {
279 if err, ok := err.(dispatchcloud.ConstraintsNotSatisfiableError); ok {
280 var logBuf bytes.Buffer
281 fmt.Fprintf(&logBuf, "cannot run container %s: %s\n", ctr.UUID, err)
282 if len(err.AvailableTypes) == 0 {
283 fmt.Fprint(&logBuf, "No instance types are configured.\n")
285 fmt.Fprint(&logBuf, "Available instance types:\n")
286 for _, t := range err.AvailableTypes {
288 "Type %q: %d VCPUs, %d RAM, %d Scratch, %f Price\n",
289 t.Name, t.VCPUs, t.RAM, t.Scratch, t.Price,
293 text = logBuf.String()
294 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
296 text = fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
300 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
301 "object_uuid": ctr.UUID,
302 "event_type": "dispatch",
303 "properties": map[string]string{"text": text}}}
304 disp.Arv.Create("logs", lr, nil)
306 disp.Unlock(ctr.UUID)
311 log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
312 defer log.Printf("Done monitoring container %s", ctr.UUID)
314 // If the container disappears from the slurm queue, there is
315 // no point in waiting for further dispatch updates: just
316 // clean up and return.
317 go func(uuid string) {
318 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
326 // Disappeared from squeue
327 if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
328 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
331 case dispatch.Running:
332 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
333 case dispatch.Locked:
334 disp.Unlock(ctr.UUID)
337 case updated, ok := <-status:
339 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
341 } else if updated.Priority == 0 {
342 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
345 p := int64(updated.Priority)
348 // user-assigned priority. If
349 // ctrs have equal priority,
350 // run the older one first.
351 p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
353 disp.sqCheck.SetPriority(ctr.UUID, p)
358 func (disp *Dispatcher) scancel(ctr arvados.Container) {
359 err := disp.slurm.Cancel(ctr.UUID)
361 log.Printf("scancel: %s", err)
362 time.Sleep(time.Second)
363 } else if disp.sqCheck.HasUUID(ctr.UUID) {
364 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
365 time.Sleep(time.Second)
369 func (disp *Dispatcher) readConfig(path string) error {
370 err := config.LoadFile(disp, path)
371 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
372 log.Printf("Config not specified. Continue with default configuration.")