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 // Minimum time between two attempts to run the same container
51 MinRetryPeriod arvados.Duration
56 err := disp.Run(os.Args[0], os.Args[1:])
62 func (disp *Dispatcher) Run(prog string, args []string) error {
63 if err := disp.configure(prog, args); err != nil {
70 // configure() loads config files. Tests skip this.
71 func (disp *Dispatcher) configure(prog string, args []string) error {
72 flags := flag.NewFlagSet(prog, flag.ExitOnError)
73 flags.Usage = func() { usage(flags) }
75 configPath := flags.String(
78 "`path` to JSON or YAML configuration file")
79 dumpConfig := flag.Bool(
82 "write current configuration to stdout and exit")
83 getVersion := flags.Bool(
86 "Print version information and exit.")
87 // Parse args; omit the first arg which is the command name
90 // Print version information if requested
92 fmt.Printf("crunch-dispatch-slurm %s\n", version)
96 log.Printf("crunch-dispatch-slurm %s started", version)
98 err := disp.readConfig(*configPath)
103 if disp.CrunchRunCommand == nil {
104 disp.CrunchRunCommand = []string{"crunch-run"}
107 if disp.PollPeriod == 0 {
108 disp.PollPeriod = arvados.Duration(10 * time.Second)
111 if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
112 // Copy real configs into env vars so [a]
113 // MakeArvadosClient() uses them, and [b] they get
114 // propagated to crunch-run via SLURM.
115 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
116 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
117 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
118 if disp.Client.Insecure {
119 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
121 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(disp.Client.KeepServiceURIs, " "))
122 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
124 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
128 return config.DumpAndExit(disp)
131 siteConfig, err := arvados.GetConfig(arvados.DefaultConfigFile)
132 if os.IsNotExist(err) {
133 log.Printf("warning: no cluster config (%s), proceeding with no node types defined", err)
134 } else if err != nil {
135 return fmt.Errorf("error loading config: %s", err)
136 } else if disp.cluster, err = siteConfig.GetCluster(""); err != nil {
137 return fmt.Errorf("config error: %s", err)
143 // setup() initializes private fields after configure().
144 func (disp *Dispatcher) setup() {
145 arv, err := arvadosclient.MakeArvadosClient()
147 log.Fatalf("Error making Arvados client: %v", err)
151 disp.slurm = &slurmCLI{}
152 disp.sqCheck = &SqueueChecker{
153 Period: time.Duration(disp.PollPeriod),
156 disp.Dispatcher = &dispatch.Dispatcher{
158 RunContainer: disp.runContainer,
159 PollPeriod: time.Duration(disp.PollPeriod),
160 MinRetryPeriod: time.Duration(disp.MinRetryPeriod),
164 func (disp *Dispatcher) run() error {
165 defer disp.sqCheck.Stop()
167 if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
168 go dispatchcloud.SlurmNodeTypeFeatureKludge(disp.cluster)
171 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
172 log.Printf("Error notifying init daemon: %v", err)
174 go disp.checkSqueueForOrphans()
175 return disp.Dispatcher.Run(context.Background())
178 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
180 // Check the next squeue report, and invoke TrackContainer for all the
181 // containers in the report. This gives us a chance to cancel slurm
182 // jobs started by a previous dispatch process that never released
183 // their slurm allocations even though their container states are
184 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
185 func (disp *Dispatcher) checkSqueueForOrphans() {
186 for _, uuid := range disp.sqCheck.All() {
187 if !containerUuidPattern.MatchString(uuid) {
190 err := disp.TrackContainer(uuid)
192 log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
197 func (disp *Dispatcher) niceness(priority int) int {
204 // Niceness range 1-10000
205 return (1000 - priority) * 10
208 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
209 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
212 for _, m := range container.Mounts {
217 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
219 var sbatchArgs []string
220 sbatchArgs = append(sbatchArgs, disp.SbatchArguments...)
221 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
222 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
223 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
224 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
225 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--nice=%d", disp.niceness(container.Priority)))
226 if len(container.SchedulingParameters.Partitions) > 0 {
227 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
230 if disp.cluster == nil {
231 // no instance types configured
232 } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
234 } else if err != nil {
237 sbatchArgs = append(sbatchArgs, "--constraint=instancetype="+it.Name)
240 return sbatchArgs, nil
243 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
244 // append() here avoids modifying crunchRunCommand's
245 // underlying array, which is shared with other goroutines.
246 crArgs := append([]string(nil), crunchRunCommand...)
247 crArgs = append(crArgs, container.UUID)
248 crScript := strings.NewReader(execScript(crArgs))
250 disp.sqCheck.L.Lock()
251 defer disp.sqCheck.L.Unlock()
253 sbArgs, err := disp.sbatchArgs(container)
257 log.Printf("running sbatch %+q", sbArgs)
258 return disp.slurm.Batch(crScript, sbArgs)
261 // Submit a container to the slurm queue (or resume monitoring if it's
262 // already in the queue). Cancel the slurm job if the container's
263 // priority changes to zero or its state indicates it's no longer
265 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
266 ctx, cancel := context.WithCancel(context.Background())
269 if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
270 log.Printf("Submitting container %s to slurm", ctr.UUID)
271 if err := disp.submit(ctr, disp.CrunchRunCommand); err != nil {
273 if err == dispatchcloud.ErrConstraintsNotSatisfiable {
274 text = fmt.Sprintf("cannot run container %s: %s", ctr.UUID, err)
275 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
277 text = fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
281 lr := arvadosclient.Dict{"log": arvadosclient.Dict{
282 "object_uuid": ctr.UUID,
283 "event_type": "dispatch",
284 "properties": map[string]string{"text": text}}}
285 disp.Arv.Create("logs", lr, nil)
287 disp.Unlock(ctr.UUID)
292 log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
293 defer log.Printf("Done monitoring container %s", ctr.UUID)
295 // If the container disappears from the slurm queue, there is
296 // no point in waiting for further dispatch updates: just
297 // clean up and return.
298 go func(uuid string) {
299 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
307 // Disappeared from squeue
308 if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
309 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
312 case dispatch.Running:
313 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
314 case dispatch.Locked:
315 disp.Unlock(ctr.UUID)
318 case updated, ok := <-status:
320 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
322 } else if updated.Priority == 0 {
323 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
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) renice(ctr arvados.Container) {
347 nice := disp.niceness(ctr.Priority)
348 oldnice := disp.sqCheck.GetNiceness(ctr.UUID)
349 if nice == oldnice || oldnice == -1 {
352 log.Printf("updating slurm nice value to %d (was %d)", nice, oldnice)
353 disp.sqCheck.L.Lock()
354 err := disp.slurm.Renice(ctr.UUID, nice)
355 disp.sqCheck.L.Unlock()
358 log.Printf("renice: %s", err)
359 time.Sleep(time.Second)
362 if disp.sqCheck.HasUUID(ctr.UUID) {
363 log.Printf("container %s has arvados priority %d, slurm nice %d",
364 ctr.UUID, ctr.Priority, disp.sqCheck.GetNiceness(ctr.UUID))
368 func (disp *Dispatcher) readConfig(path string) error {
369 err := config.LoadFile(disp, path)
370 if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
371 log.Printf("Config not specified. Continue with default configuration.")