Merge branch '9857-cwl-acceptlist-re' refs #9857
[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_INSECURE", "")
83                 if theConfig.Client.Insecure {
84                         os.Setenv("ARVADOS_API_INSECURE", "1")
85                 }
86                 os.Setenv("ARVADOS_KEEP_SERVICES", "")
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                 DoneProcessing: make(chan struct{})}
107
108         if _, err := daemon.SdNotify("READY=1"); err != nil {
109                 log.Printf("Error notifying init daemon: %v", err)
110         }
111
112         err = dispatcher.RunDispatcher()
113         if err != nil {
114                 return err
115         }
116
117         return nil
118 }
119
120 // sbatchCmd
121 func sbatchFunc(container arvados.Container) *exec.Cmd {
122         memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
123
124         var sbatchArgs []string
125         sbatchArgs = append(sbatchArgs, "--share")
126         sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
127         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
128         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
129         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
130
131         return exec.Command("sbatch", sbatchArgs...)
132 }
133
134 // scancelCmd
135 func scancelFunc(container arvados.Container) *exec.Cmd {
136         return exec.Command("scancel", "--name="+container.UUID)
137 }
138
139 // Wrap these so that they can be overridden by tests
140 var sbatchCmd = sbatchFunc
141 var scancelCmd = scancelFunc
142
143 // Submit job to slurm using sbatch.
144 func submit(dispatcher *dispatch.Dispatcher,
145         container arvados.Container, crunchRunCommand []string) (submitErr error) {
146         defer func() {
147                 // If we didn't get as far as submitting a slurm job,
148                 // unlock the container and return it to the queue.
149                 if submitErr == nil {
150                         // OK, no cleanup needed
151                         return
152                 }
153                 err := dispatcher.Unlock(container.UUID)
154                 if err != nil {
155                         log.Printf("Error unlocking container %s: %v", container.UUID, err)
156                 }
157         }()
158
159         // Create the command and attach to stdin/stdout
160         cmd := sbatchCmd(container)
161         stdinWriter, stdinerr := cmd.StdinPipe()
162         if stdinerr != nil {
163                 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
164                 return
165         }
166
167         stdoutReader, stdoutErr := cmd.StdoutPipe()
168         if stdoutErr != nil {
169                 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
170                 return
171         }
172
173         stderrReader, stderrErr := cmd.StderrPipe()
174         if stderrErr != nil {
175                 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
176                 return
177         }
178
179         // Mutex between squeue sync and running sbatch or scancel.
180         squeueUpdater.SlurmLock.Lock()
181         defer squeueUpdater.SlurmLock.Unlock()
182
183         err := cmd.Start()
184         if err != nil {
185                 submitErr = fmt.Errorf("Error starting %v: %v", cmd.Args, err)
186                 return
187         }
188
189         stdoutChan := make(chan []byte)
190         go func() {
191                 b, _ := ioutil.ReadAll(stdoutReader)
192                 stdoutReader.Close()
193                 stdoutChan <- b
194         }()
195
196         stderrChan := make(chan []byte)
197         go func() {
198                 b, _ := ioutil.ReadAll(stderrReader)
199                 stderrReader.Close()
200                 stderrChan <- b
201         }()
202
203         // Send a tiny script on stdin to execute the crunch-run command
204         // slurm actually enforces that this must be a #! script
205         io.WriteString(stdinWriter, execScript(append(crunchRunCommand, container.UUID)))
206         stdinWriter.Close()
207
208         err = cmd.Wait()
209
210         stdoutMsg := <-stdoutChan
211         stderrmsg := <-stderrChan
212
213         close(stdoutChan)
214         close(stderrChan)
215
216         if err != nil {
217                 submitErr = fmt.Errorf("Container submission failed: %v: %v (stderr: %q)", cmd.Args, err, stderrmsg)
218                 return
219         }
220
221         log.Printf("sbatch succeeded: %s", strings.TrimSpace(string(stdoutMsg)))
222         return
223 }
224
225 // If the container is marked as Locked, check if it is already in the slurm
226 // queue.  If not, submit it.
227 //
228 // If the container is marked as Running, check if it is in the slurm queue.
229 // If not, mark it as Cancelled.
230 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
231         submitted := false
232         for !*monitorDone {
233                 if squeueUpdater.CheckSqueue(container.UUID) {
234                         // Found in the queue, so continue monitoring
235                         submitted = true
236                 } else if container.State == dispatch.Locked && !submitted {
237                         // Not in queue but in Locked state and we haven't
238                         // submitted it yet, so submit it.
239
240                         log.Printf("About to submit queued container %v", container.UUID)
241
242                         if err := submit(dispatcher, container, theConfig.CrunchRunCommand); err != nil {
243                                 log.Printf("Error submitting container %s to slurm: %v",
244                                         container.UUID, err)
245                                 // maybe sbatch is broken, put it back to queued
246                                 dispatcher.Unlock(container.UUID)
247                         }
248                         submitted = true
249                 } else {
250                         // Not in queue and we are not going to submit it.
251                         // Refresh the container state. If it is
252                         // Complete/Cancelled, do nothing, if it is Locked then
253                         // release it back to the Queue, if it is Running then
254                         // clean up the record.
255
256                         var con arvados.Container
257                         err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
258                         if err != nil {
259                                 log.Printf("Error getting final container state: %v", err)
260                         }
261
262                         switch con.State {
263                         case dispatch.Locked:
264                                 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
265                                         container.UUID, con.State, dispatch.Queued)
266                                 dispatcher.Unlock(container.UUID)
267                         case dispatch.Running:
268                                 st := dispatch.Cancelled
269                                 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
270                                         container.UUID, con.State, st)
271                                 dispatcher.UpdateState(container.UUID, st)
272                         default:
273                                 // Container state is Queued, Complete or Cancelled so stop monitoring it.
274                                 return
275                         }
276                 }
277         }
278 }
279
280 // Run or monitor a container.
281 //
282 // Monitor status updates.  If the priority changes to zero, cancel the
283 // container using scancel.
284 func run(dispatcher *dispatch.Dispatcher,
285         container arvados.Container,
286         status chan arvados.Container) {
287
288         log.Printf("Monitoring container %v started", container.UUID)
289         defer log.Printf("Monitoring container %v finished", container.UUID)
290
291         monitorDone := false
292         go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
293
294         for container = range status {
295                 if container.State == dispatch.Locked || container.State == dispatch.Running {
296                         if container.Priority == 0 {
297                                 log.Printf("Canceling container %s", container.UUID)
298
299                                 // Mutex between squeue sync and running sbatch or scancel.
300                                 squeueUpdater.SlurmLock.Lock()
301                                 err := scancelCmd(container).Run()
302                                 squeueUpdater.SlurmLock.Unlock()
303
304                                 if err != nil {
305                                         log.Printf("Error stopping container %s with scancel: %v",
306                                                 container.UUID, err)
307                                         if squeueUpdater.CheckSqueue(container.UUID) {
308                                                 log.Printf("Container %s is still in squeue after scancel.",
309                                                         container.UUID)
310                                                 continue
311                                         }
312                                 }
313
314                                 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)
315                         }
316                 }
317         }
318         monitorDone = true
319 }
320
321 func readConfig(dst interface{}, path string) error {
322         err := config.LoadFile(dst, path)
323         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
324                 log.Printf("Config not specified. Continue with default configuration.")
325                 err = nil
326         }
327         return err
328 }