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