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