10703: Do not catch signals in crunch-dispatch-slurm. Simplify "stop dispatcher loop...
[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/config"
11         "git.curoverse.com/arvados.git/sdk/go/dispatch"
12         "github.com/coreos/go-systemd/daemon"
13         "io"
14         "io/ioutil"
15         "log"
16         "math"
17         "os"
18         "os/exec"
19         "strings"
20         "time"
21 )
22
23 // Config used by crunch-dispatch-slurm
24 type Config struct {
25         Client arvados.Client
26
27         SbatchArguments []string
28         PollPeriod      arvados.Duration
29
30         // crunch-run command to invoke. The container UUID will be
31         // appended. If nil, []string{"crunch-run"} will be used.
32         //
33         // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
34         CrunchRunCommand []string
35 }
36
37 func main() {
38         err := doMain()
39         if err != nil {
40                 log.Fatal(err)
41         }
42 }
43
44 var (
45         theConfig     Config
46         squeueUpdater Squeue
47 )
48
49 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
50
51 func doMain() error {
52         flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
53         flags.Usage = func() { usage(flags) }
54
55         configPath := flags.String(
56                 "config",
57                 defaultConfigPath,
58                 "`path` to JSON or YAML configuration file")
59
60         // Parse args; omit the first arg which is the command name
61         flags.Parse(os.Args[1:])
62
63         err := readConfig(&theConfig, *configPath)
64         if err != nil {
65                 return err
66         }
67
68         if theConfig.CrunchRunCommand == nil {
69                 theConfig.CrunchRunCommand = []string{"crunch-run"}
70         }
71
72         if theConfig.PollPeriod == 0 {
73                 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
74         }
75
76         if theConfig.Client.APIHost != "" || theConfig.Client.AuthToken != "" {
77                 // Copy real configs into env vars so [a]
78                 // MakeArvadosClient() uses them, and [b] they get
79                 // propagated to crunch-run via SLURM.
80                 os.Setenv("ARVADOS_API_HOST", theConfig.Client.APIHost)
81                 os.Setenv("ARVADOS_API_TOKEN", theConfig.Client.AuthToken)
82                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
83                 if theConfig.Client.Insecure {
84                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
85                 }
86                 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
87                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
88         } else {
89                 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
90         }
91
92         arv, err := arvadosclient.MakeArvadosClient()
93         if err != nil {
94                 log.Printf("Error making Arvados client: %v", err)
95                 return err
96         }
97         arv.Retries = 25
98
99         squeueUpdater.StartMonitor(time.Duration(theConfig.PollPeriod))
100         defer squeueUpdater.Done()
101
102         dispatcher := dispatch.Dispatcher{
103                 Arv:          arv,
104                 RunContainer: run,
105                 PollInterval: time.Duration(theConfig.PollPeriod),
106         }
107
108         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
109                 log.Printf("Error notifying init daemon: %v", err)
110         }
111
112         return dispatcher.Run()
113 }
114
115 // sbatchCmd
116 func sbatchFunc(container arvados.Container) *exec.Cmd {
117         memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
118
119         var sbatchArgs []string
120         sbatchArgs = append(sbatchArgs, "--share")
121         sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
122         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
123         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
124         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
125         if container.SchedulingParameters.Partitions != nil {
126                 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
127         }
128
129         return exec.Command("sbatch", sbatchArgs...)
130 }
131
132 // scancelCmd
133 func scancelFunc(container arvados.Container) *exec.Cmd {
134         return exec.Command("scancel", "--name="+container.UUID)
135 }
136
137 // Wrap these so that they can be overridden by tests
138 var sbatchCmd = sbatchFunc
139 var scancelCmd = scancelFunc
140
141 // Submit job to slurm using sbatch.
142 func submit(dispatcher *dispatch.Dispatcher,
143         container arvados.Container, crunchRunCommand []string) (submitErr error) {
144         defer func() {
145                 // If we didn't get as far as submitting a slurm job,
146                 // unlock the container and return it to the queue.
147                 if submitErr == nil {
148                         // OK, no cleanup needed
149                         return
150                 }
151                 err := dispatcher.Unlock(container.UUID)
152                 if err != nil {
153                         log.Printf("Error unlocking container %s: %v", container.UUID, err)
154                 }
155         }()
156
157         // Create the command and attach to stdin/stdout
158         cmd := sbatchCmd(container)
159         stdinWriter, stdinerr := cmd.StdinPipe()
160         if stdinerr != nil {
161                 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
162                 return
163         }
164
165         stdoutReader, stdoutErr := cmd.StdoutPipe()
166         if stdoutErr != nil {
167                 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
168                 return
169         }
170
171         stderrReader, stderrErr := cmd.StderrPipe()
172         if stderrErr != nil {
173                 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
174                 return
175         }
176
177         // Mutex between squeue sync and running sbatch or scancel.
178         squeueUpdater.SlurmLock.Lock()
179         defer squeueUpdater.SlurmLock.Unlock()
180
181         log.Printf("sbatch starting: %+q", cmd.Args)
182         err := cmd.Start()
183         if err != nil {
184                 submitErr = fmt.Errorf("Error starting sbatch: %v", err)
185                 return
186         }
187
188         stdoutChan := make(chan []byte)
189         go func() {
190                 b, _ := ioutil.ReadAll(stdoutReader)
191                 stdoutReader.Close()
192                 stdoutChan <- b
193                 close(stdoutChan)
194         }()
195
196         stderrChan := make(chan []byte)
197         go func() {
198                 b, _ := ioutil.ReadAll(stderrReader)
199                 stderrReader.Close()
200                 stderrChan <- b
201                 close(stderrChan)
202         }()
203
204         // Send a tiny script on stdin to execute the crunch-run command
205         // slurm actually enforces that this must be a #! script
206         io.WriteString(stdinWriter, execScript(append(crunchRunCommand, container.UUID)))
207         stdinWriter.Close()
208
209         stdoutMsg := <-stdoutChan
210         stderrmsg := <-stderrChan
211
212         err = cmd.Wait()
213
214         if err != nil {
215                 submitErr = fmt.Errorf("Container submission failed: %v: %v (stderr: %q)", cmd.Args, err, stderrmsg)
216                 return
217         }
218
219         log.Printf("sbatch succeeded: %s", strings.TrimSpace(string(stdoutMsg)))
220         return
221 }
222
223 // If the container is marked as Locked, check if it is already in the slurm
224 // queue.  If not, submit it.
225 //
226 // If the container is marked as Running, check if it is in the slurm queue.
227 // If not, mark it as Cancelled.
228 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
229         submitted := false
230         for !*monitorDone {
231                 if squeueUpdater.CheckSqueue(container.UUID) {
232                         // Found in the queue, so continue monitoring
233                         submitted = true
234                 } else if container.State == dispatch.Locked && !submitted {
235                         // Not in queue but in Locked state and we haven't
236                         // submitted it yet, so submit it.
237
238                         log.Printf("About to submit queued container %v", container.UUID)
239
240                         if err := submit(dispatcher, container, theConfig.CrunchRunCommand); err != nil {
241                                 log.Printf("Error submitting container %s to slurm: %v",
242                                         container.UUID, err)
243                                 // maybe sbatch is broken, put it back to queued
244                                 dispatcher.Unlock(container.UUID)
245                         }
246                         submitted = true
247                 } else {
248                         // Not in queue and we are not going to submit it.
249                         // Refresh the container state. If it is
250                         // Complete/Cancelled, do nothing, if it is Locked then
251                         // release it back to the Queue, if it is Running then
252                         // clean up the record.
253
254                         var con arvados.Container
255                         err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
256                         if err != nil {
257                                 log.Printf("Error getting final container state: %v", err)
258                         }
259
260                         switch con.State {
261                         case dispatch.Locked:
262                                 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
263                                         container.UUID, con.State, dispatch.Queued)
264                                 dispatcher.Unlock(container.UUID)
265                         case dispatch.Running:
266                                 st := dispatch.Cancelled
267                                 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
268                                         container.UUID, con.State, st)
269                                 dispatcher.UpdateState(container.UUID, st)
270                         default:
271                                 // Container state is Queued, Complete or Cancelled so stop monitoring it.
272                                 return
273                         }
274                 }
275         }
276 }
277
278 // Run or monitor a container.
279 //
280 // Monitor status updates.  If the priority changes to zero, cancel the
281 // container using scancel.
282 func run(dispatcher *dispatch.Dispatcher,
283         container arvados.Container,
284         status chan arvados.Container) {
285
286         log.Printf("Monitoring container %v started", container.UUID)
287         defer log.Printf("Monitoring container %v finished", container.UUID)
288
289         monitorDone := false
290         go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
291
292         for container = range status {
293                 if container.State == dispatch.Locked || container.State == dispatch.Running {
294                         if container.Priority == 0 {
295                                 log.Printf("Canceling container %s", container.UUID)
296
297                                 // Mutex between squeue sync and running sbatch or scancel.
298                                 squeueUpdater.SlurmLock.Lock()
299                                 cmd := scancelCmd(container)
300                                 msg, err := cmd.CombinedOutput()
301                                 squeueUpdater.SlurmLock.Unlock()
302
303                                 if err != nil {
304                                         log.Printf("Error stopping container %s with %v %v: %v %v",
305                                                 container.UUID, cmd.Path, cmd.Args, err, string(msg))
306                                         if squeueUpdater.CheckSqueue(container.UUID) {
307                                                 log.Printf("Container %s is still in squeue after scancel.",
308                                                         container.UUID)
309                                                 continue
310                                         }
311                                 }
312
313                                 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)
314                         }
315                 }
316         }
317         monitorDone = true
318 }
319
320 func readConfig(dst interface{}, path string) error {
321         err := config.LoadFile(dst, path)
322         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
323                 log.Printf("Config not specified. Continue with default configuration.")
324                 err = nil
325         }
326         return err
327 }