1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
16 type jobPriority struct {
21 // Squeue implements asynchronous polling monitor of the SLURM queue using the
23 type SqueueChecker struct {
26 uuids map[string]jobPriority
32 // HasUUID checks if a given container UUID is in the slurm queue.
33 // This does not run squeue directly, but instead blocks until woken
34 // up by next successful update of squeue.
35 func (sqc *SqueueChecker) HasUUID(uuid string) bool {
36 sqc.startOnce.Do(sqc.start)
41 // block until next squeue broadcast signaling an update.
43 _, exists := sqc.uuids[uuid]
47 // GetNiceness returns the niceness of a given uuid, or -1 if it doesn't exist.
48 func (sqc *SqueueChecker) GetNiceness(uuid string) int {
49 sqc.startOnce.Do(sqc.start)
54 n, exists := sqc.uuids[uuid]
62 // Stop stops the squeue monitoring goroutine. Do not call HasUUID
63 // after calling Stop.
64 func (sqc *SqueueChecker) Stop() {
70 // check gets the names of jobs in the SLURM queue (running and
71 // queued). If it succeeds, it updates squeue.uuids and wakes up any
72 // goroutines that are waiting in HasUUID() or All().
73 func (sqc *SqueueChecker) check() {
74 // Mutex between squeue sync and running sbatch or scancel. This
75 // establishes a sequence so that squeue doesn't run concurrently with
76 // sbatch or scancel; the next update of squeue will occur only after
77 // sbatch or scancel has completed.
81 cmd := sqc.Slurm.QueueCommand([]string{"--all", "--format=%j %y %Q"})
82 stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{}
83 cmd.Stdout, cmd.Stderr = stdout, stderr
84 if err := cmd.Run(); err != nil {
85 log.Printf("Error running %q %q: %s %q", cmd.Path, cmd.Args, err, stderr.String())
89 lines := strings.Split(stdout.String(), "\n")
90 sqc.uuids = make(map[string]jobPriority, len(lines))
91 for _, line := range lines {
95 fmt.Sscan(line, &uuid, &nice, &prio)
97 sqc.uuids[uuid] = jobPriority{nice, prio}
103 // Initialize, and start a goroutine to call check() once per
104 // squeue.Period until terminated by calling Stop().
105 func (sqc *SqueueChecker) start() {
106 sqc.L = &sync.Mutex{}
107 sqc.done = make(chan struct{})
109 ticker := time.NewTicker(sqc.Period)
122 // All waits for the next squeue invocation, and returns all job
123 // names reported by squeue.
124 func (sqc *SqueueChecker) All() []string {
125 sqc.startOnce.Do(sqc.start)
130 for uuid := range sqc.uuids {
131 uuids = append(uuids, uuid)