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"
28 const initialNiceValue int64 = 10000
32 defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
35 type Dispatcher struct {
37 cluster *arvados.Cluster
38 sqCheck *SqueueChecker
43 SbatchArguments []string
44 PollPeriod arvados.Duration
47 // crunch-run command to invoke. The container UUID will be
48 // appended. If nil, []string{"crunch-run"} will be used.
50 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
51 CrunchRunCommand []string
53 // Minimum time between two attempts to run the same container
54 MinRetryPeriod arvados.Duration
59 err := disp.Run(os.Args[0], os.Args[1:])
65 func (disp *Dispatcher) Run(prog string, args []string) error {
66 if err := disp.configure(prog, args); err != nil {
73 // configure() loads config files. Tests skip this.
74 func (disp *Dispatcher) configure(prog string, args []string) error {
75 flags := flag.NewFlagSet(prog, flag.ExitOnError)
76 flags.Usage = func() { usage(flags) }
78 configPath := flags.String(
81 "`path` to JSON or YAML configuration file")
82 dumpConfig := flag.Bool(
85 "write current configuration to stdout and exit")
86 getVersion := flags.Bool(
89 "Print version information and exit.")
90 // Parse args; omit the first arg which is the command name
93 // Print version information if requested
95 fmt.Printf("crunch-dispatch-slurm %s\n", version)
99 log.Printf("crunch-dispatch-slurm %s started", version)
101 err := disp.readConfig(*configPath)
106 if disp.CrunchRunCommand == nil {
107 disp.CrunchRunCommand = []string{"crunch-run"}
110 if disp.PollPeriod == 0 {
111 disp.PollPeriod = arvados.Duration(10 * time.Second)
114 if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
115 // Copy real configs into env vars so [a]
116 // MakeArvadosClient() uses them, and [b] they get
117 // propagated to crunch-run via SLURM.
118 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
119 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
120 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
121 if disp.Client.Insecure {
122 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
124 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(disp.Client.KeepServiceURIs, " "))
125 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
127 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
131 return config.DumpAndExit(disp)
134 siteConfig, err := arvados.GetConfig(arvados.DefaultConfigFile)
135 if os.IsNotExist(err) {
136 log.Printf("warning: no cluster config (%s), proceeding with no node types defined", err)
137 } else if err != nil {
138 return fmt.Errorf("error loading config: %s", err)
139 } else if disp.cluster, err = siteConfig.GetCluster(""); err != nil {
140 return fmt.Errorf("config error: %s", err)
146 // setup() initializes private fields after configure().
147 func (disp *Dispatcher) setup() {
148 arv, err := arvadosclient.MakeArvadosClient()
150 log.Fatalf("Error making Arvados client: %v", err)
154 disp.slurm = &slurmCLI{}
155 disp.sqCheck = &SqueueChecker{
156 Period: time.Duration(disp.PollPeriod),
157 PrioritySpread: disp.PrioritySpread,
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) sbatchArgs(container arvados.Container) ([]string, error) {
202 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
205 for _, m := range container.Mounts {
210 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
212 var sbatchArgs []string
213 sbatchArgs = append(sbatchArgs, disp.SbatchArguments...)
214 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
215 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
216 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
217 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
218 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--nice=%d", initialNiceValue))
219 if len(container.SchedulingParameters.Partitions) > 0 {
220 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
223 if disp.cluster == nil {
224 // no instance types configured
225 } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
227 } else if err != nil {
230 sbatchArgs = append(sbatchArgs, "--constraint=instancetype="+it.Name)
233 return sbatchArgs, nil
236 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
237 // append() here avoids modifying crunchRunCommand's
238 // underlying array, which is shared with other goroutines.
239 crArgs := append([]string(nil), crunchRunCommand...)
240 crArgs = append(crArgs, container.UUID)
241 crScript := strings.NewReader(execScript(crArgs))
243 disp.sqCheck.L.Lock()
244 defer disp.sqCheck.L.Unlock()
246 sbArgs, err := disp.sbatchArgs(container)
250 log.Printf("running sbatch %+q", sbArgs)
251 return disp.slurm.Batch(crScript, sbArgs)
254 // Submit a container to the slurm queue (or resume monitoring if it's
255 // already in the queue). Cancel the slurm job if the container's
256 // priority changes to zero or its state indicates it's no longer
258 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
259 ctx, cancel := context.WithCancel(context.Background())
262 if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
263 log.Printf("Submitting container %s to slurm", ctr.UUID)
264 if err := disp.submit(ctr, disp.CrunchRunCommand); err != nil {
266 if err == dispatchcloud.ErrConstraintsNotSatisfiable {
267 text = fmt.Sprintf("cannot run container %s: %s", ctr.UUID, err)
268 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
270 text = fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
274 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
275 "object_uuid": ctr.UUID,
276 "event_type": "dispatch",
277 "properties": map[string]string{"text": text}}}
278 disp.Arv.Create("logs", lr, nil)
280 disp.Unlock(ctr.UUID)
285 log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
286 defer log.Printf("Done monitoring container %s", ctr.UUID)
288 // If the container disappears from the slurm queue, there is
289 // no point in waiting for further dispatch updates: just
290 // clean up and return.
291 go func(uuid string) {
292 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
300 // Disappeared from squeue
301 if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
302 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
305 case dispatch.Running:
306 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
307 case dispatch.Locked:
308 disp.Unlock(ctr.UUID)
311 case updated, ok := <-status:
313 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
315 } else if updated.Priority == 0 {
316 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
319 p := int64(updated.Priority)
322 // user-assigned priority. If
323 // ctrs have equal priority,
324 // run the older one first.
325 p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
327 disp.sqCheck.SetPriority(ctr.UUID, p)
332 func (disp *Dispatcher) scancel(ctr arvados.Container) {
333 disp.sqCheck.L.Lock()
334 err := disp.slurm.Cancel(ctr.UUID)
335 disp.sqCheck.L.Unlock()
338 log.Printf("scancel: %s", err)
339 time.Sleep(time.Second)
340 } else if disp.sqCheck.HasUUID(ctr.UUID) {
341 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
342 time.Sleep(time.Second)
346 func (disp *Dispatcher) readConfig(path string) error {
347 err := config.LoadFile(disp, path)
348 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
349 log.Printf("Config not specified. Continue with default configuration.")