9180: Changed some of the logic on ThreadLimiter and made unit tests to validate...
[arvados.git] / services / crunch-dispatch-slurm / crunch-dispatch-slurm.go
1 package main
2
3 // Dispatcher service for Crunch that submits containers to the slurm queue.
4
5 import (
6         "flag"
7         "fmt"
8         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
9         "git.curoverse.com/arvados.git/sdk/go/dispatch"
10         "io/ioutil"
11         "log"
12         "math"
13         "os"
14         "os/exec"
15         "strings"
16         "time"
17 )
18
19 func main() {
20         err := doMain()
21         if err != nil {
22                 log.Fatalf("%q", err)
23         }
24 }
25
26 var (
27         crunchRunCommand *string
28         squeueUpdater    Squeue
29 )
30
31 func doMain() error {
32         flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
33
34         pollInterval := flags.Int(
35                 "poll-interval",
36                 10,
37                 "Interval in seconds to poll for queued containers")
38
39         crunchRunCommand = flags.String(
40                 "crunch-run-command",
41                 "/usr/bin/crunch-run",
42                 "Crunch command to run container")
43
44         // Parse args; omit the first arg which is the command name
45         flags.Parse(os.Args[1:])
46
47         arv, err := arvadosclient.MakeArvadosClient()
48         if err != nil {
49                 log.Printf("Error making Arvados client: %v", err)
50                 return err
51         }
52         arv.Retries = 25
53
54         squeueUpdater.StartMonitor(time.Duration(*pollInterval) * time.Second)
55         defer squeueUpdater.Done()
56
57         dispatcher := dispatch.Dispatcher{
58                 Arv:            arv,
59                 RunContainer:   run,
60                 PollInterval:   time.Duration(*pollInterval) * time.Second,
61                 DoneProcessing: make(chan struct{})}
62
63         err = dispatcher.RunDispatcher()
64         if err != nil {
65                 return err
66         }
67
68         return nil
69 }
70
71 // sbatchCmd
72 func sbatchFunc(container dispatch.Container) *exec.Cmd {
73         memPerCPU := math.Ceil((float64(container.RuntimeConstraints["ram"])) / (float64(container.RuntimeConstraints["vcpus"] * 1048576)))
74         return exec.Command("sbatch", "--share", "--parsable",
75                 fmt.Sprintf("--job-name=%s", container.UUID),
76                 fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)),
77                 fmt.Sprintf("--cpus-per-task=%d", int(container.RuntimeConstraints["vcpus"])),
78                 fmt.Sprintf("--priority=%d", container.Priority))
79 }
80
81 // scancelCmd
82 func scancelFunc(container dispatch.Container) *exec.Cmd {
83         return exec.Command("scancel", "--name="+container.UUID)
84 }
85
86 // Wrap these so that they can be overridden by tests
87 var sbatchCmd = sbatchFunc
88 var scancelCmd = scancelFunc
89
90 // Submit job to slurm using sbatch.
91 func submit(dispatcher *dispatch.Dispatcher,
92         container dispatch.Container, crunchRunCommand string) (jobid string, submitErr error) {
93         submitErr = nil
94
95         defer func() {
96                 // If we didn't get as far as submitting a slurm job,
97                 // unlock the container and return it to the queue.
98                 if submitErr == nil {
99                         // OK, no cleanup needed
100                         return
101                 }
102                 err := dispatcher.Arv.Update("containers", container.UUID,
103                         arvadosclient.Dict{
104                                 "container": arvadosclient.Dict{"state": "Queued"}},
105                         nil)
106                 if err != nil {
107                         log.Printf("Error unlocking container %s: %v", container.UUID, err)
108                 }
109         }()
110
111         // Create the command and attach to stdin/stdout
112         cmd := sbatchCmd(container)
113         stdinWriter, stdinerr := cmd.StdinPipe()
114         if stdinerr != nil {
115                 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
116                 return
117         }
118
119         stdoutReader, stdoutErr := cmd.StdoutPipe()
120         if stdoutErr != nil {
121                 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
122                 return
123         }
124
125         stderrReader, stderrErr := cmd.StderrPipe()
126         if stderrErr != nil {
127                 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
128                 return
129         }
130
131         // Mutex between squeue sync and running sbatch or scancel.
132         squeueUpdater.SlurmLock.Lock()
133         defer squeueUpdater.SlurmLock.Unlock()
134
135         err := cmd.Start()
136         if err != nil {
137                 submitErr = fmt.Errorf("Error starting %v: %v", cmd.Args, err)
138                 return
139         }
140
141         stdoutChan := make(chan []byte)
142         go func() {
143                 b, _ := ioutil.ReadAll(stdoutReader)
144                 stdoutReader.Close()
145                 stdoutChan <- b
146         }()
147
148         stderrChan := make(chan []byte)
149         go func() {
150                 b, _ := ioutil.ReadAll(stderrReader)
151                 stderrReader.Close()
152                 stderrChan <- b
153         }()
154
155         // Send a tiny script on stdin to execute the crunch-run command
156         // slurm actually enforces that this must be a #! script
157         fmt.Fprintf(stdinWriter, "#!/bin/sh\nexec '%s' '%s'\n", crunchRunCommand, container.UUID)
158         stdinWriter.Close()
159
160         err = cmd.Wait()
161
162         stdoutMsg := <-stdoutChan
163         stderrmsg := <-stderrChan
164
165         close(stdoutChan)
166         close(stderrChan)
167
168         if err != nil {
169                 submitErr = fmt.Errorf("Container submission failed %v: %v %v", cmd.Args, err, stderrmsg)
170                 return
171         }
172
173         // If everything worked out, got the jobid on stdout
174         jobid = strings.TrimSpace(string(stdoutMsg))
175
176         return
177 }
178
179 // If the container is marked as Locked, check if it is already in the slurm
180 // queue.  If not, submit it.
181 //
182 // If the container is marked as Running, check if it is in the slurm queue.
183 // If not, mark it as Cancelled.
184 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container dispatch.Container, monitorDone *bool) {
185         submitted := false
186         for !*monitorDone {
187                 if squeueUpdater.CheckSqueue(container.UUID) {
188                         // Found in the queue, so continue monitoring
189                         submitted = true
190                 } else if container.State == dispatch.Locked && !submitted {
191                         // Not in queue but in Locked state and we haven't
192                         // submitted it yet, so submit it.
193
194                         log.Printf("About to submit queued container %v", container.UUID)
195
196                         if _, err := submit(dispatcher, container, *crunchRunCommand); err != nil {
197                                 log.Printf("Error submitting container %s to slurm: %v",
198                                         container.UUID, err)
199                                 // maybe sbatch is broken, put it back to queued
200                                 dispatcher.UpdateState(container.UUID, dispatch.Queued)
201                         }
202                         submitted = true
203                 } else {
204                         // Not in queue and we are not going to submit it.
205                         // Refresh the container state. If it is
206                         // Complete/Cancelled, do nothing, if it is Locked then
207                         // release it back to the Queue, if it is Running then
208                         // clean up the record.
209
210                         var con dispatch.Container
211                         err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
212                         if err != nil {
213                                 log.Printf("Error getting final container state: %v", err)
214                         }
215
216                         var st string
217                         switch con.State {
218                         case dispatch.Locked:
219                                 st = dispatch.Queued
220                         case dispatch.Running:
221                                 st = dispatch.Cancelled
222                         default:
223                                 // Container state is Queued, Complete or Cancelled so stop monitoring it.
224                                 return
225                         }
226
227                         log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
228                                 container.UUID, con.State, st)
229                         dispatcher.UpdateState(container.UUID, st)
230                 }
231         }
232 }
233
234 // Run or monitor a container.
235 //
236 // Monitor status updates.  If the priority changes to zero, cancel the
237 // container using scancel.
238 func run(dispatcher *dispatch.Dispatcher,
239         container dispatch.Container,
240         status chan dispatch.Container) {
241
242         log.Printf("Monitoring container %v started", container.UUID)
243         defer log.Printf("Monitoring container %v finished", container.UUID)
244
245         monitorDone := false
246         go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
247
248         for container = range status {
249                 if container.State == dispatch.Locked || container.State == dispatch.Running {
250                         if container.Priority == 0 {
251                                 log.Printf("Canceling container %s", container.UUID)
252
253                                 // Mutex between squeue sync and running sbatch or scancel.
254                                 squeueUpdater.SlurmLock.Lock()
255                                 err := scancelCmd(container).Run()
256                                 squeueUpdater.SlurmLock.Unlock()
257
258                                 if err != nil {
259                                         log.Printf("Error stopping container %s with scancel: %v",
260                                                 container.UUID, err)
261                                         if squeueUpdater.CheckSqueue(container.UUID) {
262                                                 log.Printf("Container %s is still in squeue after scancel.",
263                                                         container.UUID)
264                                                 continue
265                                         }
266                                 }
267
268                                 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)
269                         }
270                 }
271         }
272         monitorDone = true
273 }