Merge branch 'master' into 12479-wb-structured-vocabulary
[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 func niceness(priority int) int {
168         if priority > 1000 {
169                 priority = 1000
170         }
171         if priority < 0 {
172                 priority = 0
173         }
174         // Niceness range 1-10000
175         return (1000 - priority) * 10
176 }
177
178 // sbatchCmd
179 func sbatchFunc(container arvados.Container) *exec.Cmd {
180         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
181
182         var disk int64
183         for _, m := range container.Mounts {
184                 if m.Kind == "tmp" {
185                         disk += m.Capacity
186                 }
187         }
188         disk = int64(math.Ceil(float64(disk) / float64(1048576)))
189
190         var sbatchArgs []string
191         sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
192         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
193         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
194         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
195         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
196         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--nice=%d", niceness(container.Priority)))
197         if len(container.SchedulingParameters.Partitions) > 0 {
198                 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
199         }
200
201         return exec.Command("sbatch", sbatchArgs...)
202 }
203
204 // scancelCmd
205 func scancelFunc(container arvados.Container) *exec.Cmd {
206         return exec.Command("scancel", "--name="+container.UUID)
207 }
208
209 // scontrolCmd
210 func scontrolFunc(container arvados.Container) *exec.Cmd {
211         return exec.Command("scontrol", "update", "JobName="+container.UUID, fmt.Sprintf("Nice=%d", niceness(container.Priority)))
212 }
213
214 // Wrap these so that they can be overridden by tests
215 var sbatchCmd = sbatchFunc
216 var scancelCmd = scancelFunc
217 var scontrolCmd = scontrolFunc
218
219 // Submit job to slurm using sbatch.
220 func submit(dispatcher *dispatch.Dispatcher, container arvados.Container, crunchRunCommand []string) error {
221         cmd := sbatchCmd(container)
222
223         // Send a tiny script on stdin to execute the crunch-run
224         // command (slurm requires this to be a #! script)
225
226         // append() here avoids modifying crunchRunCommand's
227         // underlying array, which is shared with other goroutines.
228         args := append([]string(nil), crunchRunCommand...)
229         args = append(args, container.UUID)
230         cmd.Stdin = strings.NewReader(execScript(args))
231
232         var stdout, stderr bytes.Buffer
233         cmd.Stdout = &stdout
234         cmd.Stderr = &stderr
235
236         // Mutex between squeue sync and running sbatch or scancel.
237         sqCheck.L.Lock()
238         defer sqCheck.L.Unlock()
239
240         log.Printf("exec sbatch %+q", cmd.Args)
241         err := cmd.Run()
242
243         switch err.(type) {
244         case nil:
245                 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
246                 return nil
247
248         case *exec.ExitError:
249                 dispatcher.Unlock(container.UUID)
250                 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
251
252         default:
253                 dispatcher.Unlock(container.UUID)
254                 return fmt.Errorf("exec failed: %v", err)
255         }
256 }
257
258 // Submit a container to the slurm queue (or resume monitoring if it's
259 // already in the queue).  Cancel the slurm job if the container's
260 // priority changes to zero or its state indicates it's no longer
261 // running.
262 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
263         ctx, cancel := context.WithCancel(context.Background())
264         defer cancel()
265
266         if ctr.State == dispatch.Locked && !sqCheck.HasUUID(ctr.UUID) {
267                 log.Printf("Submitting container %s to slurm", ctr.UUID)
268                 if err := submit(disp, ctr, theConfig.CrunchRunCommand); err != nil {
269                         text := fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
270                         log.Print(text)
271
272                         lr := arvadosclient.Dict{"log": arvadosclient.Dict{
273                                 "object_uuid": ctr.UUID,
274                                 "event_type":  "dispatch",
275                                 "properties":  map[string]string{"text": text}}}
276                         disp.Arv.Create("logs", lr, nil)
277
278                         disp.Unlock(ctr.UUID)
279                         return
280                 }
281         }
282
283         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
284         defer log.Printf("Done monitoring container %s", ctr.UUID)
285
286         // If the container disappears from the slurm queue, there is
287         // no point in waiting for further dispatch updates: just
288         // clean up and return.
289         go func(uuid string) {
290                 for ctx.Err() == nil && sqCheck.HasUUID(uuid) {
291                 }
292                 cancel()
293         }(ctr.UUID)
294
295         for {
296                 select {
297                 case <-ctx.Done():
298                         // Disappeared from squeue
299                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
300                                 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
301                         }
302                         switch ctr.State {
303                         case dispatch.Running:
304                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
305                         case dispatch.Locked:
306                                 disp.Unlock(ctr.UUID)
307                         }
308                         return
309                 case updated, ok := <-status:
310                         if !ok {
311                                 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
312                                 scancel(ctr)
313                         } else if updated.Priority == 0 {
314                                 log.Printf("Container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
315                                 scancel(ctr)
316                         } else if niceness(updated.Priority) != sqCheck.GetNiceness(ctr.UUID) && sqCheck.GetNiceness(ctr.UUID) != -1 {
317                                 // dynamically adjust priority
318                                 log.Printf("Container priority %v != %v", niceness(updated.Priority), sqCheck.GetNiceness(ctr.UUID))
319                                 scontrolUpdate(updated)
320                         }
321                 }
322         }
323 }
324
325 func scancel(ctr arvados.Container) {
326         sqCheck.L.Lock()
327         cmd := scancelCmd(ctr)
328         msg, err := cmd.CombinedOutput()
329         sqCheck.L.Unlock()
330
331         if err != nil {
332                 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
333                 time.Sleep(time.Second)
334         } else if sqCheck.HasUUID(ctr.UUID) {
335                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
336                 time.Sleep(time.Second)
337         }
338 }
339
340 func scontrolUpdate(ctr arvados.Container) {
341         sqCheck.L.Lock()
342         cmd := scontrolCmd(ctr)
343         msg, err := cmd.CombinedOutput()
344         sqCheck.L.Unlock()
345
346         if err != nil {
347                 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
348                 time.Sleep(time.Second)
349         } else if sqCheck.HasUUID(ctr.UUID) {
350                 log.Printf("Container %s priority is now %v, niceness is now %v",
351                         ctr.UUID, ctr.Priority, sqCheck.GetNiceness(ctr.UUID))
352         }
353 }
354
355 func readConfig(dst interface{}, path string) error {
356         err := config.LoadFile(dst, path)
357         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
358                 log.Printf("Config not specified. Continue with default configuration.")
359                 err = nil
360         }
361         return err
362 }