Merge branch 'wtsi/14110-c-d-s-limit-slurm-concurrency' refs #14110
[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         "regexp"
18         "strings"
19         "time"
20
21         "git.curoverse.com/arvados.git/lib/dispatchcloud"
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/Sirupsen/logrus"
27         "github.com/coreos/go-systemd/daemon"
28 )
29
30 type logger interface {
31         dispatch.Logger
32         Fatalf(string, ...interface{})
33 }
34
35 const initialNiceValue int64 = 10000
36
37 var (
38         version           = "dev"
39         defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
40 )
41
42 type Dispatcher struct {
43         *dispatch.Dispatcher
44         logger  logrus.FieldLogger
45         cluster *arvados.Cluster
46         sqCheck *SqueueChecker
47         slurm   Slurm
48
49         Client arvados.Client
50
51         SbatchArguments []string
52         PollPeriod      arvados.Duration
53         PrioritySpread  int64
54
55         // crunch-run command to invoke. The container UUID will be
56         // appended. If nil, []string{"crunch-run"} will be used.
57         //
58         // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
59         CrunchRunCommand []string
60
61         // Extra RAM to reserve (in Bytes) for SLURM job, in addition
62         // to the amount specified in the container's RuntimeConstraints
63         ReserveExtraRAM int64
64
65         // Minimum time between two attempts to run the same container
66         MinRetryPeriod arvados.Duration
67
68         // Batch size for container queries
69         BatchSize int64
70 }
71
72 func main() {
73         logger := logrus.StandardLogger()
74         if os.Getenv("DEBUG") != "" {
75                 logger.SetLevel(logrus.DebugLevel)
76         }
77         logger.Formatter = &logrus.JSONFormatter{
78                 TimestampFormat: "2006-01-02T15:04:05.000000000Z07:00",
79         }
80         disp := &Dispatcher{logger: logger}
81         err := disp.Run(os.Args[0], os.Args[1:])
82         if err != nil {
83                 logrus.Fatalf("%s", err)
84         }
85 }
86
87 func (disp *Dispatcher) Run(prog string, args []string) error {
88         if err := disp.configure(prog, args); err != nil {
89                 return err
90         }
91         disp.setup()
92         return disp.run()
93 }
94
95 // configure() loads config files. Tests skip this.
96 func (disp *Dispatcher) configure(prog string, args []string) error {
97         flags := flag.NewFlagSet(prog, flag.ExitOnError)
98         flags.Usage = func() { usage(flags) }
99
100         configPath := flags.String(
101                 "config",
102                 defaultConfigPath,
103                 "`path` to JSON or YAML configuration file")
104         dumpConfig := flag.Bool(
105                 "dump-config",
106                 false,
107                 "write current configuration to stdout and exit")
108         getVersion := flags.Bool(
109                 "version",
110                 false,
111                 "Print version information and exit.")
112         // Parse args; omit the first arg which is the command name
113         flags.Parse(args)
114
115         // Print version information if requested
116         if *getVersion {
117                 fmt.Printf("crunch-dispatch-slurm %s\n", version)
118                 return nil
119         }
120
121         disp.logger.Printf("crunch-dispatch-slurm %s started", version)
122
123         err := disp.readConfig(*configPath)
124         if err != nil {
125                 return err
126         }
127
128         if disp.CrunchRunCommand == nil {
129                 disp.CrunchRunCommand = []string{"crunch-run"}
130         }
131
132         if disp.PollPeriod == 0 {
133                 disp.PollPeriod = arvados.Duration(10 * time.Second)
134         }
135
136         if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
137                 // Copy real configs into env vars so [a]
138                 // MakeArvadosClient() uses them, and [b] they get
139                 // propagated to crunch-run via SLURM.
140                 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
141                 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
142                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
143                 if disp.Client.Insecure {
144                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
145                 }
146                 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(disp.Client.KeepServiceURIs, " "))
147                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
148         } else {
149                 disp.logger.Warnf("Client credentials missing from config, so falling back on environment variables (deprecated).")
150         }
151
152         if *dumpConfig {
153                 return config.DumpAndExit(disp)
154         }
155
156         siteConfig, err := arvados.GetConfig(arvados.DefaultConfigFile)
157         if os.IsNotExist(err) {
158                 disp.logger.Warnf("no cluster config (%s), proceeding with no node types defined", err)
159         } else if err != nil {
160                 return fmt.Errorf("error loading config: %s", err)
161         } else if disp.cluster, err = siteConfig.GetCluster(""); err != nil {
162                 return fmt.Errorf("config error: %s", err)
163         }
164
165         return nil
166 }
167
168 // setup() initializes private fields after configure().
169 func (disp *Dispatcher) setup() {
170         if disp.logger == nil {
171                 disp.logger = logrus.StandardLogger()
172         }
173         arv, err := arvadosclient.MakeArvadosClient()
174         if err != nil {
175                 disp.logger.Fatalf("Error making Arvados client: %v", err)
176         }
177         arv.Retries = 25
178
179         disp.slurm = NewSlurmCLI()
180         disp.sqCheck = &SqueueChecker{
181                 Logger:         disp.logger,
182                 Period:         time.Duration(disp.PollPeriod),
183                 PrioritySpread: disp.PrioritySpread,
184                 Slurm:          disp.slurm,
185         }
186         disp.Dispatcher = &dispatch.Dispatcher{
187                 Arv:            arv,
188                 Logger:         disp.logger,
189                 BatchSize:      disp.BatchSize,
190                 RunContainer:   disp.runContainer,
191                 PollPeriod:     time.Duration(disp.PollPeriod),
192                 MinRetryPeriod: time.Duration(disp.MinRetryPeriod),
193         }
194 }
195
196 func (disp *Dispatcher) run() error {
197         defer disp.sqCheck.Stop()
198
199         if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
200                 go dispatchcloud.SlurmNodeTypeFeatureKludge(disp.cluster)
201         }
202
203         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
204                 log.Printf("Error notifying init daemon: %v", err)
205         }
206         go disp.checkSqueueForOrphans()
207         return disp.Dispatcher.Run(context.Background())
208 }
209
210 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
211
212 // Check the next squeue report, and invoke TrackContainer for all the
213 // containers in the report. This gives us a chance to cancel slurm
214 // jobs started by a previous dispatch process that never released
215 // their slurm allocations even though their container states are
216 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
217 func (disp *Dispatcher) checkSqueueForOrphans() {
218         for _, uuid := range disp.sqCheck.All() {
219                 if !containerUuidPattern.MatchString(uuid) {
220                         continue
221                 }
222                 err := disp.TrackContainer(uuid)
223                 if err != nil {
224                         log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
225                 }
226         }
227 }
228
229 func (disp *Dispatcher) slurmConstraintArgs(container arvados.Container) []string {
230         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM+disp.ReserveExtraRAM) / float64(1048576)))
231
232         var disk int64
233         for _, m := range container.Mounts {
234                 if m.Kind == "tmp" {
235                         disk += m.Capacity
236                 }
237         }
238         disk = int64(math.Ceil(float64(disk) / float64(1048576)))
239         return []string{
240                 fmt.Sprintf("--mem=%d", mem),
241                 fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs),
242                 fmt.Sprintf("--tmp=%d", disk),
243         }
244 }
245
246 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
247         var args []string
248         args = append(args, disp.SbatchArguments...)
249         args = append(args, "--job-name="+container.UUID, fmt.Sprintf("--nice=%d", initialNiceValue))
250
251         if disp.cluster == nil {
252                 // no instance types configured
253                 args = append(args, disp.slurmConstraintArgs(container)...)
254         } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
255                 // ditto
256                 args = append(args, disp.slurmConstraintArgs(container)...)
257         } else if err != nil {
258                 return nil, err
259         } else {
260                 // use instancetype constraint instead of slurm mem/cpu/tmp specs
261                 args = append(args, "--constraint=instancetype="+it.Name)
262         }
263
264         if len(container.SchedulingParameters.Partitions) > 0 {
265                 args = append(args, "--partition="+strings.Join(container.SchedulingParameters.Partitions, ","))
266         }
267
268         return args, nil
269 }
270
271 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
272         // append() here avoids modifying crunchRunCommand's
273         // underlying array, which is shared with other goroutines.
274         crArgs := append([]string(nil), crunchRunCommand...)
275         crArgs = append(crArgs, container.UUID)
276         crScript := strings.NewReader(execScript(crArgs))
277
278         sbArgs, err := disp.sbatchArgs(container)
279         if err != nil {
280                 return err
281         }
282         log.Printf("running sbatch %+q", sbArgs)
283         return disp.slurm.Batch(crScript, sbArgs)
284 }
285
286 // Submit a container to the slurm queue (or resume monitoring if it's
287 // already in the queue).  Cancel the slurm job if the container's
288 // priority changes to zero or its state indicates it's no longer
289 // running.
290 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
291         ctx, cancel := context.WithCancel(context.Background())
292         defer cancel()
293
294         if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
295                 log.Printf("Submitting container %s to slurm", ctr.UUID)
296                 if err := disp.submit(ctr, disp.CrunchRunCommand); err != nil {
297                         var text string
298                         if err, ok := err.(dispatchcloud.ConstraintsNotSatisfiableError); ok {
299                                 var logBuf bytes.Buffer
300                                 fmt.Fprintf(&logBuf, "cannot run container %s: %s\n", ctr.UUID, err)
301                                 if len(err.AvailableTypes) == 0 {
302                                         fmt.Fprint(&logBuf, "No instance types are configured.\n")
303                                 } else {
304                                         fmt.Fprint(&logBuf, "Available instance types:\n")
305                                         for _, t := range err.AvailableTypes {
306                                                 fmt.Fprintf(&logBuf,
307                                                         "Type %q: %d VCPUs, %d RAM, %d Scratch, %f Price\n",
308                                                         t.Name, t.VCPUs, t.RAM, t.Scratch, t.Price,
309                                                 )
310                                         }
311                                 }
312                                 text = logBuf.String()
313                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
314                         } else {
315                                 text = fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
316                         }
317                         log.Print(text)
318
319                         lr := arvadosclient.Dict{"log": arvadosclient.Dict{
320                                 "object_uuid": ctr.UUID,
321                                 "event_type":  "dispatch",
322                                 "properties":  map[string]string{"text": text}}}
323                         disp.Arv.Create("logs", lr, nil)
324
325                         disp.Unlock(ctr.UUID)
326                         return
327                 }
328         }
329
330         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
331         defer log.Printf("Done monitoring container %s", ctr.UUID)
332
333         // If the container disappears from the slurm queue, there is
334         // no point in waiting for further dispatch updates: just
335         // clean up and return.
336         go func(uuid string) {
337                 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
338                 }
339                 cancel()
340         }(ctr.UUID)
341
342         for {
343                 select {
344                 case <-ctx.Done():
345                         // Disappeared from squeue
346                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
347                                 log.Printf("error getting final container state for %s: %s", ctr.UUID, err)
348                         }
349                         switch ctr.State {
350                         case dispatch.Running:
351                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
352                         case dispatch.Locked:
353                                 disp.Unlock(ctr.UUID)
354                         }
355                         return
356                 case updated, ok := <-status:
357                         if !ok {
358                                 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
359                                 disp.scancel(ctr)
360                         } else if updated.Priority == 0 {
361                                 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
362                                 disp.scancel(ctr)
363                         } else {
364                                 p := int64(updated.Priority)
365                                 if p <= 1000 {
366                                         // API is providing
367                                         // user-assigned priority. If
368                                         // ctrs have equal priority,
369                                         // run the older one first.
370                                         p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
371                                 }
372                                 disp.sqCheck.SetPriority(ctr.UUID, p)
373                         }
374                 }
375         }
376 }
377 func (disp *Dispatcher) scancel(ctr arvados.Container) {
378         err := disp.slurm.Cancel(ctr.UUID)
379         if err != nil {
380                 log.Printf("scancel: %s", err)
381                 time.Sleep(time.Second)
382         } else if disp.sqCheck.HasUUID(ctr.UUID) {
383                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
384                 time.Sleep(time.Second)
385         }
386 }
387
388 func (disp *Dispatcher) readConfig(path string) error {
389         err := config.LoadFile(disp, path)
390         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
391                 log.Printf("Config not specified. Continue with default configuration.")
392                 err = nil
393         }
394         return err
395 }