17417: Merge branch 'main' into 17417-add-arm64
[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.arvados.org/arvados.git/lib/cmd"
21         "git.arvados.org/arvados.git/lib/config"
22         "git.arvados.org/arvados.git/lib/dispatchcloud"
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
25         "git.arvados.org/arvados.git/sdk/go/dispatch"
26         "github.com/coreos/go-systemd/daemon"
27         "github.com/ghodss/yaml"
28         "github.com/sirupsen/logrus"
29 )
30
31 type logger interface {
32         dispatch.Logger
33         Fatalf(string, ...interface{})
34 }
35
36 const initialNiceValue int64 = 10000
37
38 var (
39         version = "dev"
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
52 func main() {
53         logger := logrus.StandardLogger()
54         if os.Getenv("DEBUG") != "" {
55                 logger.SetLevel(logrus.DebugLevel)
56         }
57         logger.Formatter = &logrus.JSONFormatter{
58                 TimestampFormat: "2006-01-02T15:04:05.000000000Z07:00",
59         }
60         disp := &Dispatcher{logger: logger}
61         err := disp.Run(os.Args[0], os.Args[1:])
62         if err != nil {
63                 logrus.Fatalf("%s", err)
64         }
65 }
66
67 func (disp *Dispatcher) Run(prog string, args []string) error {
68         if err := disp.configure(prog, args); err != nil {
69                 return err
70         }
71         disp.setup()
72         return disp.run()
73 }
74
75 // configure() loads config files. Tests skip this.
76 func (disp *Dispatcher) configure(prog string, args []string) error {
77         if disp.logger == nil {
78                 disp.logger = logrus.StandardLogger()
79         }
80         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
81         flags.Usage = func() { usage(flags) }
82
83         loader := config.NewLoader(nil, disp.logger)
84         loader.SetupFlags(flags)
85
86         dumpConfig := flag.Bool(
87                 "dump-config",
88                 false,
89                 "write current configuration to stdout and exit")
90         getVersion := flags.Bool(
91                 "version",
92                 false,
93                 "Print version information and exit.")
94
95         args = loader.MungeLegacyConfigArgs(disp.logger, args, "-legacy-crunch-dispatch-slurm-config")
96         if ok, code := cmd.ParseFlags(flags, prog, args, "", os.Stderr); !ok {
97                 os.Exit(code)
98         }
99
100         // Print version information if requested
101         if *getVersion {
102                 fmt.Printf("crunch-dispatch-slurm %s\n", version)
103                 return nil
104         }
105
106         disp.logger.Printf("crunch-dispatch-slurm %s started", version)
107
108         cfg, err := loader.Load()
109         if err != nil {
110                 return err
111         }
112
113         if disp.cluster, err = cfg.GetCluster(""); err != nil {
114                 return fmt.Errorf("config error: %s", err)
115         }
116
117         disp.logger = disp.logger.WithField("ClusterID", disp.cluster.ClusterID)
118
119         disp.Client.APIHost = disp.cluster.Services.Controller.ExternalURL.Host
120         disp.Client.AuthToken = disp.cluster.SystemRootToken
121         disp.Client.Insecure = disp.cluster.TLS.Insecure
122
123         if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
124                 // Copy real configs into env vars so [a]
125                 // MakeArvadosClient() uses them, and [b] they get
126                 // propagated to crunch-run via SLURM.
127                 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
128                 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
129                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
130                 if disp.Client.Insecure {
131                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
132                 }
133                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
134                 for k, v := range disp.cluster.Containers.SLURM.SbatchEnvironmentVariables {
135                         os.Setenv(k, v)
136                 }
137         } else {
138                 disp.logger.Warnf("Client credentials missing from config, so falling back on environment variables (deprecated).")
139         }
140
141         if *dumpConfig {
142                 out, err := yaml.Marshal(cfg)
143                 if err != nil {
144                         return err
145                 }
146                 _, err = os.Stdout.Write(out)
147                 if err != nil {
148                         return err
149                 }
150         }
151
152         return nil
153 }
154
155 // setup() initializes private fields after configure().
156 func (disp *Dispatcher) setup() {
157         arv, err := arvadosclient.MakeArvadosClient()
158         if err != nil {
159                 disp.logger.Fatalf("Error making Arvados client: %v", err)
160         }
161         arv.Retries = 25
162
163         disp.slurm = NewSlurmCLI()
164         disp.sqCheck = &SqueueChecker{
165                 Logger:         disp.logger,
166                 Period:         time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
167                 PrioritySpread: disp.cluster.Containers.SLURM.PrioritySpread,
168                 Slurm:          disp.slurm,
169         }
170         disp.Dispatcher = &dispatch.Dispatcher{
171                 Arv:            arv,
172                 Logger:         disp.logger,
173                 BatchSize:      disp.cluster.API.MaxItemsPerResponse,
174                 RunContainer:   disp.runContainer,
175                 PollPeriod:     time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
176                 MinRetryPeriod: time.Duration(disp.cluster.Containers.MinRetryPeriod),
177         }
178 }
179
180 func (disp *Dispatcher) run() error {
181         defer disp.sqCheck.Stop()
182
183         if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
184                 go SlurmNodeTypeFeatureKludge(disp.cluster)
185         }
186
187         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
188                 log.Printf("Error notifying init daemon: %v", err)
189         }
190         go disp.checkSqueueForOrphans()
191         return disp.Dispatcher.Run(context.Background())
192 }
193
194 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
195
196 // Check the next squeue report, and invoke TrackContainer for all the
197 // containers in the report. This gives us a chance to cancel slurm
198 // jobs started by a previous dispatch process that never released
199 // their slurm allocations even though their container states are
200 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
201 func (disp *Dispatcher) checkSqueueForOrphans() {
202         for _, uuid := range disp.sqCheck.All() {
203                 if !containerUuidPattern.MatchString(uuid) || !strings.HasPrefix(uuid, disp.cluster.ClusterID) {
204                         continue
205                 }
206                 err := disp.TrackContainer(uuid)
207                 if err != nil {
208                         log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
209                 }
210         }
211 }
212
213 func (disp *Dispatcher) slurmConstraintArgs(container arvados.Container) []string {
214         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+
215                 container.RuntimeConstraints.KeepCacheRAM+
216                 int64(disp.cluster.Containers.ReserveExtraRAM)) / float64(1048576)))
217
218         disk := dispatchcloud.EstimateScratchSpace(&container)
219         disk = int64(math.Ceil(float64(disk) / float64(1048576)))
220         return []string{
221                 fmt.Sprintf("--mem=%d", mem),
222                 fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs),
223                 fmt.Sprintf("--tmp=%d", disk),
224         }
225 }
226
227 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
228         var args []string
229         args = append(args, disp.cluster.Containers.SLURM.SbatchArgumentsList...)
230         args = append(args, "--job-name="+container.UUID, fmt.Sprintf("--nice=%d", initialNiceValue), "--no-requeue")
231
232         if disp.cluster == nil {
233                 // no instance types configured
234                 args = append(args, disp.slurmConstraintArgs(container)...)
235         } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
236                 // ditto
237                 args = append(args, disp.slurmConstraintArgs(container)...)
238         } else if err != nil {
239                 return nil, err
240         } else {
241                 // use instancetype constraint instead of slurm mem/cpu/tmp specs
242                 args = append(args, "--constraint=instancetype="+it.Name)
243         }
244
245         if len(container.SchedulingParameters.Partitions) > 0 {
246                 args = append(args, "--partition="+strings.Join(container.SchedulingParameters.Partitions, ","))
247         }
248
249         return args, nil
250 }
251
252 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
253         // append() here avoids modifying crunchRunCommand's
254         // underlying array, which is shared with other goroutines.
255         crArgs := append([]string(nil), crunchRunCommand...)
256         crArgs = append(crArgs, "--runtime-engine="+disp.cluster.Containers.RuntimeEngine)
257         crArgs = append(crArgs, container.UUID)
258         crScript := strings.NewReader(execScript(crArgs))
259
260         sbArgs, err := disp.sbatchArgs(container)
261         if err != nil {
262                 return err
263         }
264         log.Printf("running sbatch %+q", sbArgs)
265         return disp.slurm.Batch(crScript, sbArgs)
266 }
267
268 // Submit a container to the slurm queue (or resume monitoring if it's
269 // already in the queue).  Cancel the slurm job if the container's
270 // priority changes to zero or its state indicates it's no longer
271 // running.
272 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) error {
273         ctx, cancel := context.WithCancel(context.Background())
274         defer cancel()
275
276         if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
277                 log.Printf("Submitting container %s to slurm", ctr.UUID)
278                 cmd := []string{disp.cluster.Containers.CrunchRunCommand}
279                 cmd = append(cmd, disp.cluster.Containers.CrunchRunArgumentsList...)
280                 err := disp.submit(ctr, cmd)
281                 if err != nil {
282                         return err
283                 }
284         }
285
286         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
287         defer log.Printf("Done monitoring container %s", ctr.UUID)
288
289         // If the container disappears from the slurm queue, there is
290         // no point in waiting for further dispatch updates: just
291         // clean up and return.
292         go func(uuid string) {
293                 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
294                 }
295                 cancel()
296         }(ctr.UUID)
297
298         for {
299                 select {
300                 case <-ctx.Done():
301                         // Disappeared from squeue
302                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
303                                 log.Printf("error getting final container state for %s: %s", ctr.UUID, err)
304                         }
305                         switch ctr.State {
306                         case dispatch.Running:
307                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
308                         case dispatch.Locked:
309                                 disp.Unlock(ctr.UUID)
310                         }
311                         return nil
312                 case updated, ok := <-status:
313                         if !ok {
314                                 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
315                                 disp.scancel(ctr)
316                         } else if updated.Priority == 0 {
317                                 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
318                                 disp.scancel(ctr)
319                         } else {
320                                 p := int64(updated.Priority)
321                                 if p <= 1000 {
322                                         // API is providing
323                                         // user-assigned priority. If
324                                         // ctrs have equal priority,
325                                         // run the older one first.
326                                         p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
327                                 }
328                                 disp.sqCheck.SetPriority(ctr.UUID, p)
329                         }
330                 }
331         }
332 }
333 func (disp *Dispatcher) scancel(ctr arvados.Container) {
334         err := disp.slurm.Cancel(ctr.UUID)
335         if err != nil {
336                 log.Printf("scancel: %s", err)
337                 time.Sleep(time.Second)
338         } else if disp.sqCheck.HasUUID(ctr.UUID) {
339                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
340                 time.Sleep(time.Second)
341         }
342 }