10666: Formatting fixes.
[arvados.git] / services / crunch-dispatch-slurm / crunch-dispatch-slurm.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 // Dispatcher service for Crunch that submits containers to the slurm queue.
8
9 import (
10         "bytes"
11         "context"
12         "flag"
13         "fmt"
14         "log"
15         "math"
16         "os"
17         "os/exec"
18         "regexp"
19         "strings"
20         "time"
21
22         "git.curoverse.com/arvados.git/sdk/go/arvados"
23         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
24         "git.curoverse.com/arvados.git/sdk/go/config"
25         "git.curoverse.com/arvados.git/sdk/go/dispatch"
26         "github.com/coreos/go-systemd/daemon"
27 )
28
29 var version = "dev"
30
31 // Config used by crunch-dispatch-slurm
32 type Config struct {
33         Client arvados.Client
34
35         SbatchArguments []string
36         PollPeriod      arvados.Duration
37
38         // crunch-run command to invoke. The container UUID will be
39         // appended. If nil, []string{"crunch-run"} will be used.
40         //
41         // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
42         CrunchRunCommand []string
43
44         // Minimum time between two attempts to run the same container
45         MinRetryPeriod arvados.Duration
46 }
47
48 func main() {
49         err := doMain()
50         if err != nil {
51                 log.Fatal(err)
52         }
53 }
54
55 var (
56         theConfig Config
57         sqCheck   = &SqueueChecker{}
58 )
59
60 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
61
62 func doMain() error {
63         flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
64         flags.Usage = func() { usage(flags) }
65
66         configPath := flags.String(
67                 "config",
68                 defaultConfigPath,
69                 "`path` to JSON or YAML configuration file")
70         dumpConfig := flag.Bool(
71                 "dump-config",
72                 false,
73                 "write current configuration to stdout and exit")
74         getVersion := flags.Bool(
75                 "version",
76                 false,
77                 "Print version information and exit.")
78         // Parse args; omit the first arg which is the command name
79         flags.Parse(os.Args[1:])
80
81         // Print version information if requested
82         if *getVersion {
83                 fmt.Printf("crunch-dispatch-slurm %s\n", version)
84                 return nil
85         }
86
87         log.Printf("crunch-dispatch-slurm %s started", version)
88
89         err := readConfig(&theConfig, *configPath)
90         if err != nil {
91                 return err
92         }
93
94         if theConfig.CrunchRunCommand == nil {
95                 theConfig.CrunchRunCommand = []string{"crunch-run"}
96         }
97
98         if theConfig.PollPeriod == 0 {
99                 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
100         }
101
102         if theConfig.Client.APIHost != "" || theConfig.Client.AuthToken != "" {
103                 // Copy real configs into env vars so [a]
104                 // MakeArvadosClient() uses them, and [b] they get
105                 // propagated to crunch-run via SLURM.
106                 os.Setenv("ARVADOS_API_HOST", theConfig.Client.APIHost)
107                 os.Setenv("ARVADOS_API_TOKEN", theConfig.Client.AuthToken)
108                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
109                 if theConfig.Client.Insecure {
110                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
111                 }
112                 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
113                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
114         } else {
115                 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
116         }
117
118         if *dumpConfig {
119                 log.Fatal(config.DumpAndExit(theConfig))
120         }
121
122         arv, err := arvadosclient.MakeArvadosClient()
123         if err != nil {
124                 log.Printf("Error making Arvados client: %v", err)
125                 return err
126         }
127         arv.Retries = 25
128
129         sqCheck = &SqueueChecker{Period: time.Duration(theConfig.PollPeriod)}
130         defer sqCheck.Stop()
131
132         dispatcher := &dispatch.Dispatcher{
133                 Arv:            arv,
134                 RunContainer:   run,
135                 PollPeriod:     time.Duration(theConfig.PollPeriod),
136                 MinRetryPeriod: time.Duration(theConfig.MinRetryPeriod),
137         }
138
139         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
140                 log.Printf("Error notifying init daemon: %v", err)
141         }
142
143         go checkSqueueForOrphans(dispatcher, sqCheck)
144
145         return dispatcher.Run(context.Background())
146 }
147
148 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
149
150 // Check the next squeue report, and invoke TrackContainer for all the
151 // containers in the report. This gives us a chance to cancel slurm
152 // jobs started by a previous dispatch process that never released
153 // their slurm allocations even though their container states are
154 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
155 func checkSqueueForOrphans(dispatcher *dispatch.Dispatcher, sqCheck *SqueueChecker) {
156         for _, uuid := range sqCheck.All() {
157                 if !containerUuidPattern.MatchString(uuid) {
158                         continue
159                 }
160                 err := dispatcher.TrackContainer(uuid)
161                 if err != nil {
162                         log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
163                 }
164         }
165 }
166
167 // sbatchCmd
168 func sbatchFunc(container arvados.Container) *exec.Cmd {
169         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
170
171         var disk int64
172         for _, m := range container.Mounts {
173                 if m.Kind == "tmp" {
174                         disk += m.Capacity
175                 }
176         }
177         disk = int64(math.Ceil(float64(disk) / float64(1048576)))
178
179         var sbatchArgs []string
180         sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
181         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
182         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
183         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
184         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
185         if len(container.SchedulingParameters.Partitions) > 0 {
186                 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
187         }
188
189         return exec.Command("sbatch", sbatchArgs...)
190 }
191
192 // scancelCmd
193 func scancelFunc(container arvados.Container) *exec.Cmd {
194         return exec.Command("scancel", "--name="+container.UUID)
195 }
196
197 // Wrap these so that they can be overridden by tests
198 var sbatchCmd = sbatchFunc
199 var scancelCmd = scancelFunc
200
201 // Submit job to slurm using sbatch.
202 func submit(dispatcher *dispatch.Dispatcher, container arvados.Container, crunchRunCommand []string) error {
203         cmd := sbatchCmd(container)
204
205         // Send a tiny script on stdin to execute the crunch-run
206         // command (slurm requires this to be a #! script)
207         cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
208
209         var stdout, stderr bytes.Buffer
210         cmd.Stdout = &stdout
211         cmd.Stderr = &stderr
212
213         // Mutex between squeue sync and running sbatch or scancel.
214         sqCheck.L.Lock()
215         defer sqCheck.L.Unlock()
216
217         log.Printf("exec sbatch %+q", cmd.Args)
218         err := cmd.Run()
219
220         switch err.(type) {
221         case nil:
222                 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
223                 return nil
224
225         case *exec.ExitError:
226                 dispatcher.Unlock(container.UUID)
227                 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
228
229         default:
230                 dispatcher.Unlock(container.UUID)
231                 return fmt.Errorf("exec failed: %v", err)
232         }
233 }
234
235 // Submit a container to the slurm queue (or resume monitoring if it's
236 // already in the queue).  Cancel the slurm job if the container's
237 // priority changes to zero or its state indicates it's no longer
238 // running.
239 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
240         ctx, cancel := context.WithCancel(context.Background())
241         defer cancel()
242
243         if ctr.State == dispatch.Locked && !sqCheck.HasUUID(ctr.UUID) {
244                 log.Printf("Submitting container %s to slurm", ctr.UUID)
245                 if err := submit(disp, ctr, theConfig.CrunchRunCommand); err != nil {
246                         text := fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
247                         log.Print(text)
248
249                         lr := arvadosclient.Dict{"log": arvadosclient.Dict{
250                                 "object_uuid": ctr.UUID,
251                                 "event_type":  "dispatch",
252                                 "properties":  map[string]string{"text": text}}}
253                         disp.Arv.Create("logs", lr, nil)
254
255                         disp.Unlock(ctr.UUID)
256                         return
257                 }
258         }
259
260         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
261         defer log.Printf("Done monitoring container %s", ctr.UUID)
262
263         // If the container disappears from the slurm queue, there is
264         // no point in waiting for further dispatch updates: just
265         // clean up and return.
266         go func(uuid string) {
267                 for ctx.Err() == nil && sqCheck.HasUUID(uuid) {
268                 }
269                 cancel()
270         }(ctr.UUID)
271
272         for {
273                 select {
274                 case <-ctx.Done():
275                         // Disappeared from squeue
276                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
277                                 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
278                         }
279                         switch ctr.State {
280                         case dispatch.Running:
281                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
282                         case dispatch.Locked:
283                                 disp.Unlock(ctr.UUID)
284                         }
285                         return
286                 case updated, ok := <-status:
287                         if !ok {
288                                 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
289                                 scancel(ctr)
290                         } else if updated.Priority == 0 {
291                                 log.Printf("Container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
292                                 scancel(ctr)
293                         }
294                 }
295         }
296 }
297
298 func scancel(ctr arvados.Container) {
299         sqCheck.L.Lock()
300         cmd := scancelCmd(ctr)
301         msg, err := cmd.CombinedOutput()
302         sqCheck.L.Unlock()
303
304         if err != nil {
305                 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
306                 time.Sleep(time.Second)
307         } else if sqCheck.HasUUID(ctr.UUID) {
308                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
309                 time.Sleep(time.Second)
310         }
311 }
312
313 func readConfig(dst interface{}, path string) error {
314         err := config.LoadFile(dst, path)
315         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
316                 log.Printf("Config not specified. Continue with default configuration.")
317                 err = nil
318         }
319         return err
320 }