12199: Refactor to eliminate evil globals.
[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         "context"
11         "flag"
12         "fmt"
13         "log"
14         "math"
15         "os"
16         "regexp"
17         "strings"
18         "time"
19
20         "git.curoverse.com/arvados.git/sdk/go/arvados"
21         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
22         "git.curoverse.com/arvados.git/sdk/go/config"
23         "git.curoverse.com/arvados.git/sdk/go/dispatch"
24         "git.curoverse.com/arvados.git/services/dispatchcloud"
25         "github.com/coreos/go-systemd/daemon"
26 )
27
28 var version = "dev"
29
30 type command struct {
31         dispatcher *dispatch.Dispatcher
32         cluster    *arvados.Cluster
33         sqCheck    *SqueueChecker
34         slurm      Slurm
35
36         Client arvados.Client
37
38         SbatchArguments []string
39         PollPeriod      arvados.Duration
40
41         // crunch-run command to invoke. The container UUID will be
42         // appended. If nil, []string{"crunch-run"} will be used.
43         //
44         // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
45         CrunchRunCommand []string
46
47         // Minimum time between two attempts to run the same container
48         MinRetryPeriod arvados.Duration
49 }
50
51 func main() {
52         err := (&command{}).Run(os.Args[0], os.Args[1:])
53         if err != nil {
54                 log.Fatal(err)
55         }
56 }
57
58 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
59
60 func (cmd *command) Run(prog string, args []string) error {
61         flags := flag.NewFlagSet(prog, flag.ExitOnError)
62         flags.Usage = func() { usage(flags) }
63
64         configPath := flags.String(
65                 "config",
66                 defaultConfigPath,
67                 "`path` to JSON or YAML configuration file")
68         dumpConfig := flag.Bool(
69                 "dump-config",
70                 false,
71                 "write current configuration to stdout and exit")
72         getVersion := flags.Bool(
73                 "version",
74                 false,
75                 "Print version information and exit.")
76         // Parse args; omit the first arg which is the command name
77         flags.Parse(args)
78
79         // Print version information if requested
80         if *getVersion {
81                 fmt.Printf("crunch-dispatch-slurm %s\n", version)
82                 return nil
83         }
84
85         log.Printf("crunch-dispatch-slurm %s started", version)
86
87         err := cmd.readConfig(*configPath)
88         if err != nil {
89                 return err
90         }
91
92         if cmd.CrunchRunCommand == nil {
93                 cmd.CrunchRunCommand = []string{"crunch-run"}
94         }
95
96         if cmd.PollPeriod == 0 {
97                 cmd.PollPeriod = arvados.Duration(10 * time.Second)
98         }
99
100         if cmd.Client.APIHost != "" || cmd.Client.AuthToken != "" {
101                 // Copy real configs into env vars so [a]
102                 // MakeArvadosClient() uses them, and [b] they get
103                 // propagated to crunch-run via SLURM.
104                 os.Setenv("ARVADOS_API_HOST", cmd.Client.APIHost)
105                 os.Setenv("ARVADOS_API_TOKEN", cmd.Client.AuthToken)
106                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
107                 if cmd.Client.Insecure {
108                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
109                 }
110                 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(cmd.Client.KeepServiceURIs, " "))
111                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
112         } else {
113                 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
114         }
115
116         if *dumpConfig {
117                 log.Fatal(config.DumpAndExit(cmd))
118         }
119
120         arv, err := arvadosclient.MakeArvadosClient()
121         if err != nil {
122                 log.Printf("Error making Arvados client: %v", err)
123                 return err
124         }
125         arv.Retries = 25
126
127         siteConfig, err := arvados.GetConfig(arvados.DefaultConfigFile)
128         if os.IsNotExist(err) {
129                 log.Printf("warning: no cluster config file %q (%s), proceeding with no node types defined", arvados.DefaultConfigFile, err)
130         } else if err != nil {
131                 log.Fatalf("error loading config: %s", err)
132         } else if cmd.cluster, err = siteConfig.GetCluster(""); err != nil {
133                 log.Fatalf("config error: %s", err)
134         }
135
136         if cmd.slurm == nil {
137                 cmd.slurm = &slurmCLI{}
138         }
139
140         cmd.sqCheck = &SqueueChecker{
141                 Period: time.Duration(cmd.PollPeriod),
142                 Slurm:  cmd.slurm,
143         }
144         defer cmd.sqCheck.Stop()
145
146         cmd.dispatcher = &dispatch.Dispatcher{
147                 Arv:            arv,
148                 RunContainer:   cmd.run,
149                 PollPeriod:     time.Duration(cmd.PollPeriod),
150                 MinRetryPeriod: time.Duration(cmd.MinRetryPeriod),
151         }
152
153         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
154                 log.Printf("Error notifying init daemon: %v", err)
155         }
156
157         go cmd.checkSqueueForOrphans()
158
159         return cmd.dispatcher.Run(context.Background())
160 }
161
162 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
163
164 // Check the next squeue report, and invoke TrackContainer for all the
165 // containers in the report. This gives us a chance to cancel slurm
166 // jobs started by a previous dispatch process that never released
167 // their slurm allocations even though their container states are
168 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
169 func (cmd *command) checkSqueueForOrphans() {
170         for _, uuid := range cmd.sqCheck.All() {
171                 if !containerUuidPattern.MatchString(uuid) {
172                         continue
173                 }
174                 err := cmd.dispatcher.TrackContainer(uuid)
175                 if err != nil {
176                         log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
177                 }
178         }
179 }
180
181 func (cmd *command) niceness(priority int) int {
182         if priority > 1000 {
183                 priority = 1000
184         }
185         if priority < 0 {
186                 priority = 0
187         }
188         // Niceness range 1-10000
189         return (1000 - priority) * 10
190 }
191
192 func (cmd *command) sbatchArgs(container arvados.Container) ([]string, error) {
193         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
194
195         var disk int64
196         for _, m := range container.Mounts {
197                 if m.Kind == "tmp" {
198                         disk += m.Capacity
199                 }
200         }
201         disk = int64(math.Ceil(float64(disk) / float64(1048576)))
202
203         var sbatchArgs []string
204         sbatchArgs = append(sbatchArgs, cmd.SbatchArguments...)
205         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
206         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
207         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
208         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
209         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--nice=%d", cmd.niceness(container.Priority)))
210         if len(container.SchedulingParameters.Partitions) > 0 {
211                 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
212         }
213
214         return sbatchArgs, nil
215 }
216
217 func (cmd *command) submit(container arvados.Container, crunchRunCommand []string) error {
218         // append() here avoids modifying crunchRunCommand's
219         // underlying array, which is shared with other goroutines.
220         crArgs := append([]string(nil), crunchRunCommand...)
221         crArgs = append(crArgs, container.UUID)
222         crScript := strings.NewReader(execScript(crArgs))
223
224         cmd.sqCheck.L.Lock()
225         defer cmd.sqCheck.L.Unlock()
226
227         sbArgs, err := cmd.sbatchArgs(container)
228         if err != nil {
229                 return err
230         }
231         log.Printf("running sbatch %+q", sbArgs)
232         return cmd.slurm.Batch(crScript, sbArgs)
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 (cmd *command) run(_ *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 && !cmd.sqCheck.HasUUID(ctr.UUID) {
244                 log.Printf("Submitting container %s to slurm", ctr.UUID)
245                 if err := cmd.submit(ctr, cmd.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                         cmd.dispatcher.Arv.Create("logs", lr, nil)
254
255                         cmd.dispatcher.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 && cmd.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 := cmd.dispatcher.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                                 cmd.dispatcher.UpdateState(ctr.UUID, dispatch.Cancelled)
282                         case dispatch.Locked:
283                                 cmd.dispatcher.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                                 cmd.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                                 cmd.scancel(ctr)
293                         } else {
294                                 cmd.renice(updated)
295                         }
296                 }
297         }
298 }
299
300 func (cmd *command) scancel(ctr arvados.Container) {
301         cmd.sqCheck.L.Lock()
302         err := cmd.slurm.Cancel(ctr.UUID)
303         cmd.sqCheck.L.Unlock()
304
305         if err != nil {
306                 log.Printf("scancel: %s", err)
307                 time.Sleep(time.Second)
308         } else if cmd.sqCheck.HasUUID(ctr.UUID) {
309                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
310                 time.Sleep(time.Second)
311         }
312 }
313
314 func (cmd *command) renice(ctr arvados.Container) {
315         nice := cmd.niceness(ctr.Priority)
316         oldnice := cmd.sqCheck.GetNiceness(ctr.UUID)
317         if nice == oldnice || oldnice == -1 {
318                 return
319         }
320         log.Printf("updating slurm nice value to %d (was %d)", nice, oldnice)
321         cmd.sqCheck.L.Lock()
322         err := cmd.slurm.Renice(ctr.UUID, nice)
323         cmd.sqCheck.L.Unlock()
324
325         if err != nil {
326                 log.Printf("renice: %s", err)
327                 time.Sleep(time.Second)
328                 return
329         }
330         if cmd.sqCheck.HasUUID(ctr.UUID) {
331                 log.Printf("container %s has arvados priority %d, slurm nice %d",
332                         ctr.UUID, ctr.Priority, cmd.sqCheck.GetNiceness(ctr.UUID))
333         }
334 }
335
336 func (cmd *command) readConfig(path string) error {
337         err := config.LoadFile(cmd, path)
338         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
339                 log.Printf("Config not specified. Continue with default configuration.")
340                 err = nil
341         }
342         return err
343 }