9898: update crunch-dispatch to use lock and unlock apis instead of setting state...
[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.UpdateState(container.UUID, dispatch.Queued)
155                 if err != nil {
156                         log.Printf("Error unlocking container %s: %v", container.UUID, err)
157                 }
158         }()
159
160         // Create the command and attach to stdin/stdout
161         cmd := sbatchCmd(container)
162         stdinWriter, stdinerr := cmd.StdinPipe()
163         if stdinerr != nil {
164                 submitErr = fmt.Errorf("Error creating stdin pipe %v: %q", container.UUID, stdinerr)
165                 return
166         }
167
168         stdoutReader, stdoutErr := cmd.StdoutPipe()
169         if stdoutErr != nil {
170                 submitErr = fmt.Errorf("Error creating stdout pipe %v: %q", container.UUID, stdoutErr)
171                 return
172         }
173
174         stderrReader, stderrErr := cmd.StderrPipe()
175         if stderrErr != nil {
176                 submitErr = fmt.Errorf("Error creating stderr pipe %v: %q", container.UUID, stderrErr)
177                 return
178         }
179
180         // Mutex between squeue sync and running sbatch or scancel.
181         squeueUpdater.SlurmLock.Lock()
182         defer squeueUpdater.SlurmLock.Unlock()
183
184         err := cmd.Start()
185         if err != nil {
186                 submitErr = fmt.Errorf("Error starting %v: %v", cmd.Args, err)
187                 return
188         }
189
190         stdoutChan := make(chan []byte)
191         go func() {
192                 b, _ := ioutil.ReadAll(stdoutReader)
193                 stdoutReader.Close()
194                 stdoutChan <- b
195         }()
196
197         stderrChan := make(chan []byte)
198         go func() {
199                 b, _ := ioutil.ReadAll(stderrReader)
200                 stderrReader.Close()
201                 stderrChan <- b
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         err = cmd.Wait()
210
211         stdoutMsg := <-stdoutChan
212         stderrmsg := <-stderrChan
213
214         close(stdoutChan)
215         close(stderrChan)
216
217         if err != nil {
218                 submitErr = fmt.Errorf("Container submission failed: %v: %v (stderr: %q)", cmd.Args, err, stderrmsg)
219                 return
220         }
221
222         log.Printf("sbatch succeeded: %s", strings.TrimSpace(string(stdoutMsg)))
223         return
224 }
225
226 // If the container is marked as Locked, check if it is already in the slurm
227 // queue.  If not, submit it.
228 //
229 // If the container is marked as Running, check if it is in the slurm queue.
230 // If not, mark it as Cancelled.
231 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
232         submitted := false
233         for !*monitorDone {
234                 if squeueUpdater.CheckSqueue(container.UUID) {
235                         // Found in the queue, so continue monitoring
236                         submitted = true
237                 } else if container.State == dispatch.Locked && !submitted {
238                         // Not in queue but in Locked state and we haven't
239                         // submitted it yet, so submit it.
240
241                         log.Printf("About to submit queued container %v", container.UUID)
242
243                         if err := submit(dispatcher, container, config.CrunchRunCommand); err != nil {
244                                 log.Printf("Error submitting container %s to slurm: %v",
245                                         container.UUID, err)
246                                 // maybe sbatch is broken, put it back to queued
247                                 dispatcher.UpdateState(container.UUID, dispatch.Queued)
248                         }
249                         submitted = true
250                 } else {
251                         // Not in queue and we are not going to submit it.
252                         // Refresh the container state. If it is
253                         // Complete/Cancelled, do nothing, if it is Locked then
254                         // release it back to the Queue, if it is Running then
255                         // clean up the record.
256
257                         var con arvados.Container
258                         err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
259                         if err != nil {
260                                 log.Printf("Error getting final container state: %v", err)
261                         }
262
263                         var st arvados.ContainerState
264                         switch con.State {
265                         case dispatch.Locked:
266                                 st = dispatch.Queued
267                         case dispatch.Running:
268                                 st = dispatch.Cancelled
269                         default:
270                                 // Container state is Queued, Complete or Cancelled so stop monitoring it.
271                                 return
272                         }
273
274                         log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
275                                 container.UUID, con.State, st)
276                         dispatcher.UpdateState(container.UUID, st)
277                 }
278         }
279 }
280
281 // Run or monitor a container.
282 //
283 // Monitor status updates.  If the priority changes to zero, cancel the
284 // container using scancel.
285 func run(dispatcher *dispatch.Dispatcher,
286         container arvados.Container,
287         status chan arvados.Container) {
288
289         log.Printf("Monitoring container %v started", container.UUID)
290         defer log.Printf("Monitoring container %v finished", container.UUID)
291
292         monitorDone := false
293         go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
294
295         for container = range status {
296                 if container.State == dispatch.Locked || container.State == dispatch.Running {
297                         if container.Priority == 0 {
298                                 log.Printf("Canceling container %s", container.UUID)
299
300                                 // Mutex between squeue sync and running sbatch or scancel.
301                                 squeueUpdater.SlurmLock.Lock()
302                                 err := scancelCmd(container).Run()
303                                 squeueUpdater.SlurmLock.Unlock()
304
305                                 if err != nil {
306                                         log.Printf("Error stopping container %s with scancel: %v",
307                                                 container.UUID, err)
308                                         if squeueUpdater.CheckSqueue(container.UUID) {
309                                                 log.Printf("Container %s is still in squeue after scancel.",
310                                                         container.UUID)
311                                                 continue
312                                         }
313                                 }
314
315                                 err = dispatcher.UpdateState(container.UUID, dispatch.Cancelled)
316                         }
317                 }
318         }
319         monitorDone = true
320 }
321
322 func readConfig(dst interface{}, path string) error {
323         if buf, err := ioutil.ReadFile(path); err != nil && os.IsNotExist(err) {
324                 if path == defaultConfigPath {
325                         log.Printf("Config not specified. Continue with default configuration.")
326                 } else {
327                         return fmt.Errorf("Config file not found %q: %v", path, err)
328                 }
329         } else if err != nil {
330                 return fmt.Errorf("Error reading config %q: %v", path, err)
331         } else if err = json.Unmarshal(buf, dst); err != nil {
332                 return fmt.Errorf("Error decoding config %q: %v", path, err)
333         }
334         return nil
335 }