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