Merge branch '12573-crunch2-slurm-priority' closes #12573
[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         cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
226
227         var stdout, stderr bytes.Buffer
228         cmd.Stdout = &stdout
229         cmd.Stderr = &stderr
230
231         // Mutex between squeue sync and running sbatch or scancel.
232         sqCheck.L.Lock()
233         defer sqCheck.L.Unlock()
234
235         log.Printf("exec sbatch %+q", cmd.Args)
236         err := cmd.Run()
237
238         switch err.(type) {
239         case nil:
240                 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
241                 return nil
242
243         case *exec.ExitError:
244                 dispatcher.Unlock(container.UUID)
245                 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
246
247         default:
248                 dispatcher.Unlock(container.UUID)
249                 return fmt.Errorf("exec failed: %v", err)
250         }
251 }
252
253 // Submit a container to the slurm queue (or resume monitoring if it's
254 // already in the queue).  Cancel the slurm job if the container's
255 // priority changes to zero or its state indicates it's no longer
256 // running.
257 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
258         ctx, cancel := context.WithCancel(context.Background())
259         defer cancel()
260
261         if ctr.State == dispatch.Locked && !sqCheck.HasUUID(ctr.UUID) {
262                 log.Printf("Submitting container %s to slurm", ctr.UUID)
263                 if err := submit(disp, ctr, theConfig.CrunchRunCommand); err != nil {
264                         text := fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
265                         log.Print(text)
266
267                         lr := arvadosclient.Dict{"log": arvadosclient.Dict{
268                                 "object_uuid": ctr.UUID,
269                                 "event_type":  "dispatch",
270                                 "properties":  map[string]string{"text": text}}}
271                         disp.Arv.Create("logs", lr, nil)
272
273                         disp.Unlock(ctr.UUID)
274                         return
275                 }
276         }
277
278         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
279         defer log.Printf("Done monitoring container %s", ctr.UUID)
280
281         // If the container disappears from the slurm queue, there is
282         // no point in waiting for further dispatch updates: just
283         // clean up and return.
284         go func(uuid string) {
285                 for ctx.Err() == nil && sqCheck.HasUUID(uuid) {
286                 }
287                 cancel()
288         }(ctr.UUID)
289
290         for {
291                 select {
292                 case <-ctx.Done():
293                         // Disappeared from squeue
294                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
295                                 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
296                         }
297                         switch ctr.State {
298                         case dispatch.Running:
299                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
300                         case dispatch.Locked:
301                                 disp.Unlock(ctr.UUID)
302                         }
303                         return
304                 case updated, ok := <-status:
305                         if !ok {
306                                 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
307                                 scancel(ctr)
308                         } else if updated.Priority == 0 {
309                                 log.Printf("Container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
310                                 scancel(ctr)
311                         } else if niceness(updated.Priority) != sqCheck.GetNiceness(ctr.UUID) && sqCheck.GetNiceness(ctr.UUID) != -1 {
312                                 // dynamically adjust priority
313                                 log.Printf("Container priority %v != %v", niceness(updated.Priority), sqCheck.GetNiceness(ctr.UUID))
314                                 scontrolUpdate(updated)
315                         }
316                 }
317         }
318 }
319
320 func scancel(ctr arvados.Container) {
321         sqCheck.L.Lock()
322         cmd := scancelCmd(ctr)
323         msg, err := cmd.CombinedOutput()
324         sqCheck.L.Unlock()
325
326         if err != nil {
327                 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
328                 time.Sleep(time.Second)
329         } else if sqCheck.HasUUID(ctr.UUID) {
330                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
331                 time.Sleep(time.Second)
332         }
333 }
334
335 func scontrolUpdate(ctr arvados.Container) {
336         sqCheck.L.Lock()
337         cmd := scontrolCmd(ctr)
338         msg, err := cmd.CombinedOutput()
339         sqCheck.L.Unlock()
340
341         if err != nil {
342                 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
343                 time.Sleep(time.Second)
344         } else if sqCheck.HasUUID(ctr.UUID) {
345                 log.Printf("Container %s priority is now %v, niceness is now %v",
346                         ctr.UUID, ctr.Priority, sqCheck.GetNiceness(ctr.UUID))
347         }
348 }
349
350 func readConfig(dst interface{}, path string) error {
351         err := config.LoadFile(dst, path)
352         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
353                 log.Printf("Config not specified. Continue with default configuration.")
354                 err = nil
355         }
356         return err
357 }