1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 // Squeue implements asynchronous polling monitor of the SLURM queue using the
19 type SqueueChecker struct {
27 func squeueFunc() *exec.Cmd {
28 return exec.Command("squeue", "--all", "--format=%j %y")
31 var squeueCmd = squeueFunc
33 // HasUUID checks if a given container UUID is in the slurm queue.
34 // This does not run squeue directly, but instead blocks until woken
35 // up by next successful update of squeue.
36 func (sqc *SqueueChecker) HasUUID(uuid string) bool {
37 sqc.startOnce.Do(sqc.start)
42 // block until next squeue broadcast signaling an update.
44 _, exists := sqc.uuids[uuid]
48 // GetNiceness returns the niceness of a given uuid, or -1 if it doesn't exist.
49 func (sqc *SqueueChecker) GetNiceness(uuid string) int {
50 sqc.startOnce.Do(sqc.start)
55 n, exists := sqc.uuids[uuid]
63 // Stop stops the squeue monitoring goroutine. Do not call HasUUID
64 // after calling Stop.
65 func (sqc *SqueueChecker) Stop() {
71 // check gets the names of jobs in the SLURM queue (running and
72 // queued). If it succeeds, it updates squeue.uuids and wakes up any
73 // goroutines that are waiting in HasUUID() or All().
74 func (sqc *SqueueChecker) check() {
75 // Mutex between squeue sync and running sbatch or scancel. This
76 // establishes a sequence so that squeue doesn't run concurrently with
77 // sbatch or scancel; the next update of squeue will occur only after
78 // sbatch or scancel has completed.
83 stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{}
84 cmd.Stdout, cmd.Stderr = stdout, stderr
85 if err := cmd.Run(); err != nil {
86 log.Printf("Error running %q %q: %s %q", cmd.Path, cmd.Args, err, stderr.String())
90 lines := strings.Split(stdout.String(), "\n")
91 sqc.uuids = make(map[string]int, len(lines))
92 for _, line := range lines {
95 fmt.Sscan(line, &uuid, &nice)
97 sqc.uuids[uuid] = nice
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)