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