10701: Refactor dispatch library.
[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         "context"
8         "flag"
9         "fmt"
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         // Minimum time between two attempts to run the same container
38         MinRetryPeriod arvados.Duration
39 }
40
41 func main() {
42         err := doMain()
43         if err != nil {
44                 log.Fatal(err)
45         }
46 }
47
48 var (
49         theConfig Config
50         sqCheck   = &SqueueChecker{}
51 )
52
53 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
54
55 func doMain() error {
56         flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
57         flags.Usage = func() { usage(flags) }
58
59         configPath := flags.String(
60                 "config",
61                 defaultConfigPath,
62                 "`path` to JSON or YAML configuration file")
63         dumpConfig := flag.Bool(
64                 "dump-config",
65                 false,
66                 "write current configuration to stdout and exit")
67
68         // Parse args; omit the first arg which is the command name
69         flags.Parse(os.Args[1:])
70
71         err := readConfig(&theConfig, *configPath)
72         if err != nil {
73                 return err
74         }
75
76         if theConfig.CrunchRunCommand == nil {
77                 theConfig.CrunchRunCommand = []string{"crunch-run"}
78         }
79
80         if theConfig.PollPeriod == 0 {
81                 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
82         }
83
84         if theConfig.Client.APIHost != "" || theConfig.Client.AuthToken != "" {
85                 // Copy real configs into env vars so [a]
86                 // MakeArvadosClient() uses them, and [b] they get
87                 // propagated to crunch-run via SLURM.
88                 os.Setenv("ARVADOS_API_HOST", theConfig.Client.APIHost)
89                 os.Setenv("ARVADOS_API_TOKEN", theConfig.Client.AuthToken)
90                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
91                 if theConfig.Client.Insecure {
92                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
93                 }
94                 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
95                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
96         } else {
97                 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
98         }
99
100         if *dumpConfig {
101                 log.Fatal(config.DumpAndExit(theConfig))
102         }
103
104         arv, err := arvadosclient.MakeArvadosClient()
105         if err != nil {
106                 log.Printf("Error making Arvados client: %v", err)
107                 return err
108         }
109         arv.Retries = 25
110
111         sqCheck = &SqueueChecker{Period: time.Duration(theConfig.PollPeriod)}
112         defer sqCheck.Stop()
113
114         dispatcher := &dispatch.Dispatcher{
115                 Arv:            arv,
116                 RunContainer:   run,
117                 PollPeriod:     time.Duration(theConfig.PollPeriod),
118                 MinRetryPeriod: time.Duration(theConfig.MinRetryPeriod),
119         }
120
121         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
122                 log.Printf("Error notifying init daemon: %v", err)
123         }
124
125         return dispatcher.Run(context.Background())
126 }
127
128 // sbatchCmd
129 func sbatchFunc(container arvados.Container) *exec.Cmd {
130         memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
131
132         var sbatchArgs []string
133         sbatchArgs = append(sbatchArgs, "--share")
134         sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
135         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
136         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
137         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
138         if len(container.SchedulingParameters.Partitions) > 0 {
139                 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
140         }
141
142         return exec.Command("sbatch", sbatchArgs...)
143 }
144
145 // scancelCmd
146 func scancelFunc(container arvados.Container) *exec.Cmd {
147         return exec.Command("scancel", "--name="+container.UUID)
148 }
149
150 // Wrap these so that they can be overridden by tests
151 var sbatchCmd = sbatchFunc
152 var scancelCmd = scancelFunc
153
154 // Submit job to slurm using sbatch.
155 func submit(dispatcher *dispatch.Dispatcher, container arvados.Container, crunchRunCommand []string) error {
156         cmd := sbatchCmd(container)
157
158         // Send a tiny script on stdin to execute the crunch-run
159         // command (slurm requires this to be a #! script)
160         cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
161
162         var stdout, stderr bytes.Buffer
163         cmd.Stdout = &stdout
164         cmd.Stderr = &stderr
165
166         // Mutex between squeue sync and running sbatch or scancel.
167         sqCheck.L.Lock()
168         defer sqCheck.L.Unlock()
169
170         log.Printf("exec sbatch %+q", cmd.Args)
171         err := cmd.Run()
172
173         switch err.(type) {
174         case nil:
175                 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
176                 return nil
177
178         case *exec.ExitError:
179                 dispatcher.Unlock(container.UUID)
180                 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
181
182         default:
183                 dispatcher.Unlock(container.UUID)
184                 return fmt.Errorf("exec failed: %v", err)
185         }
186 }
187
188 // Submit a container to the slurm queue (or resume monitoring if it's
189 // already in the queue).  Cancel the slurm job if the container's
190 // priority changes to zero or its state indicates it's no longer
191 // running.
192 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
193         ctx, cancel := context.WithCancel(context.Background())
194         defer cancel()
195
196         if ctr.State == dispatch.Locked && !sqCheck.HasUUID(ctr.UUID) {
197                 log.Printf("Submitting container %s to slurm", ctr.UUID)
198                 if err := submit(disp, ctr, theConfig.CrunchRunCommand); err != nil {
199                         log.Printf("Error submitting container %s to slurm: %s", ctr.UUID, err)
200                         disp.Unlock(ctr.UUID)
201                         return
202                 }
203         }
204
205         log.Printf("Start monitoring container %s", ctr.UUID)
206         defer log.Printf("Done monitoring container %s", ctr.UUID)
207
208         // If the container disappears from the slurm queue, there is
209         // no point in waiting for further dispatch updates: just
210         // clean up and return.
211         go func(uuid string) {
212                 for ctx.Err() == nil && sqCheck.HasUUID(uuid) {
213                 }
214                 cancel()
215         }(ctr.UUID)
216
217         for {
218                 select {
219                 case <-ctx.Done():
220                         // Disappeared from squeue
221                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
222                                 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
223                         }
224                         switch ctr.State {
225                         case dispatch.Running:
226                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
227                         case dispatch.Locked:
228                                 disp.Unlock(ctr.UUID)
229                         }
230                         return
231                 case updated, ok := <-status:
232                         if !ok {
233                                 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
234                                 scancel(ctr)
235                         } else if updated.Priority == 0 {
236                                 log.Printf("Container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
237                                 scancel(ctr)
238                         }
239                 }
240         }
241 }
242
243 func scancel(ctr arvados.Container) {
244         sqCheck.L.Lock()
245         cmd := scancelCmd(ctr)
246         msg, err := cmd.CombinedOutput()
247         sqCheck.L.Unlock()
248
249         if err != nil {
250                 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
251                 time.Sleep(time.Second)
252         } else if sqCheck.HasUUID(ctr.UUID) {
253                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
254                 time.Sleep(time.Second)
255         }
256 }
257
258 func readConfig(dst interface{}, path string) error {
259         err := config.LoadFile(dst, path)
260         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
261                 log.Printf("Config not specified. Continue with default configuration.")
262                 err = nil
263         }
264         return err
265 }