17840: Deduplicate flag-parsing code.
[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.Client.APIHost = disp.cluster.Services.Controller.ExternalURL.Host
118         disp.Client.AuthToken = disp.cluster.SystemRootToken
119         disp.Client.Insecure = disp.cluster.TLS.Insecure
120
121         if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
122                 // Copy real configs into env vars so [a]
123                 // MakeArvadosClient() uses them, and [b] they get
124                 // propagated to crunch-run via SLURM.
125                 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
126                 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
127                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
128                 if disp.Client.Insecure {
129                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
130                 }
131                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
132                 for k, v := range disp.cluster.Containers.SLURM.SbatchEnvironmentVariables {
133                         os.Setenv(k, v)
134                 }
135         } else {
136                 disp.logger.Warnf("Client credentials missing from config, so falling back on environment variables (deprecated).")
137         }
138
139         if *dumpConfig {
140                 out, err := yaml.Marshal(cfg)
141                 if err != nil {
142                         return err
143                 }
144                 _, err = os.Stdout.Write(out)
145                 if err != nil {
146                         return err
147                 }
148         }
149
150         return nil
151 }
152
153 // setup() initializes private fields after configure().
154 func (disp *Dispatcher) setup() {
155         arv, err := arvadosclient.MakeArvadosClient()
156         if err != nil {
157                 disp.logger.Fatalf("Error making Arvados client: %v", err)
158         }
159         arv.Retries = 25
160
161         disp.slurm = NewSlurmCLI()
162         disp.sqCheck = &SqueueChecker{
163                 Logger:         disp.logger,
164                 Period:         time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
165                 PrioritySpread: disp.cluster.Containers.SLURM.PrioritySpread,
166                 Slurm:          disp.slurm,
167         }
168         disp.Dispatcher = &dispatch.Dispatcher{
169                 Arv:            arv,
170                 Logger:         disp.logger,
171                 BatchSize:      disp.cluster.API.MaxItemsPerResponse,
172                 RunContainer:   disp.runContainer,
173                 PollPeriod:     time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
174                 MinRetryPeriod: time.Duration(disp.cluster.Containers.MinRetryPeriod),
175         }
176 }
177
178 func (disp *Dispatcher) run() error {
179         defer disp.sqCheck.Stop()
180
181         if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
182                 go SlurmNodeTypeFeatureKludge(disp.cluster)
183         }
184
185         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
186                 log.Printf("Error notifying init daemon: %v", err)
187         }
188         go disp.checkSqueueForOrphans()
189         return disp.Dispatcher.Run(context.Background())
190 }
191
192 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
193
194 // Check the next squeue report, and invoke TrackContainer for all the
195 // containers in the report. This gives us a chance to cancel slurm
196 // jobs started by a previous dispatch process that never released
197 // their slurm allocations even though their container states are
198 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
199 func (disp *Dispatcher) checkSqueueForOrphans() {
200         for _, uuid := range disp.sqCheck.All() {
201                 if !containerUuidPattern.MatchString(uuid) || !strings.HasPrefix(uuid, disp.cluster.ClusterID) {
202                         continue
203                 }
204                 err := disp.TrackContainer(uuid)
205                 if err != nil {
206                         log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
207                 }
208         }
209 }
210
211 func (disp *Dispatcher) slurmConstraintArgs(container arvados.Container) []string {
212         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+
213                 container.RuntimeConstraints.KeepCacheRAM+
214                 int64(disp.cluster.Containers.ReserveExtraRAM)) / float64(1048576)))
215
216         disk := dispatchcloud.EstimateScratchSpace(&container)
217         disk = int64(math.Ceil(float64(disk) / float64(1048576)))
218         return []string{
219                 fmt.Sprintf("--mem=%d", mem),
220                 fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs),
221                 fmt.Sprintf("--tmp=%d", disk),
222         }
223 }
224
225 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
226         var args []string
227         args = append(args, disp.cluster.Containers.SLURM.SbatchArgumentsList...)
228         args = append(args, "--job-name="+container.UUID, fmt.Sprintf("--nice=%d", initialNiceValue), "--no-requeue")
229
230         if disp.cluster == nil {
231                 // no instance types configured
232                 args = append(args, disp.slurmConstraintArgs(container)...)
233         } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
234                 // ditto
235                 args = append(args, disp.slurmConstraintArgs(container)...)
236         } else if err != nil {
237                 return nil, err
238         } else {
239                 // use instancetype constraint instead of slurm mem/cpu/tmp specs
240                 args = append(args, "--constraint=instancetype="+it.Name)
241         }
242
243         if len(container.SchedulingParameters.Partitions) > 0 {
244                 args = append(args, "--partition="+strings.Join(container.SchedulingParameters.Partitions, ","))
245         }
246
247         return args, nil
248 }
249
250 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
251         // append() here avoids modifying crunchRunCommand's
252         // underlying array, which is shared with other goroutines.
253         crArgs := append([]string(nil), crunchRunCommand...)
254         crArgs = append(crArgs, "--runtime-engine="+disp.cluster.Containers.RuntimeEngine)
255         crArgs = append(crArgs, container.UUID)
256         crScript := strings.NewReader(execScript(crArgs))
257
258         sbArgs, err := disp.sbatchArgs(container)
259         if err != nil {
260                 return err
261         }
262         log.Printf("running sbatch %+q", sbArgs)
263         return disp.slurm.Batch(crScript, sbArgs)
264 }
265
266 // Submit a container to the slurm queue (or resume monitoring if it's
267 // already in the queue).  Cancel the slurm job if the container's
268 // priority changes to zero or its state indicates it's no longer
269 // running.
270 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) error {
271         ctx, cancel := context.WithCancel(context.Background())
272         defer cancel()
273
274         if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
275                 log.Printf("Submitting container %s to slurm", ctr.UUID)
276                 cmd := []string{disp.cluster.Containers.CrunchRunCommand}
277                 cmd = append(cmd, disp.cluster.Containers.CrunchRunArgumentsList...)
278                 err := disp.submit(ctr, cmd)
279                 if err != nil {
280                         return err
281                 }
282         }
283
284         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
285         defer log.Printf("Done monitoring container %s", ctr.UUID)
286
287         // If the container disappears from the slurm queue, there is
288         // no point in waiting for further dispatch updates: just
289         // clean up and return.
290         go func(uuid string) {
291                 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
292                 }
293                 cancel()
294         }(ctr.UUID)
295
296         for {
297                 select {
298                 case <-ctx.Done():
299                         // Disappeared from squeue
300                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
301                                 log.Printf("error getting final container state for %s: %s", ctr.UUID, err)
302                         }
303                         switch ctr.State {
304                         case dispatch.Running:
305                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
306                         case dispatch.Locked:
307                                 disp.Unlock(ctr.UUID)
308                         }
309                         return nil
310                 case updated, ok := <-status:
311                         if !ok {
312                                 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
313                                 disp.scancel(ctr)
314                         } else if updated.Priority == 0 {
315                                 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
316                                 disp.scancel(ctr)
317                         } else {
318                                 p := int64(updated.Priority)
319                                 if p <= 1000 {
320                                         // API is providing
321                                         // user-assigned priority. If
322                                         // ctrs have equal priority,
323                                         // run the older one first.
324                                         p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
325                                 }
326                                 disp.sqCheck.SetPriority(ctr.UUID, p)
327                         }
328                 }
329         }
330 }
331 func (disp *Dispatcher) scancel(ctr arvados.Container) {
332         err := disp.slurm.Cancel(ctr.UUID)
333         if err != nil {
334                 log.Printf("scancel: %s", err)
335                 time.Sleep(time.Second)
336         } else if disp.sqCheck.HasUUID(ctr.UUID) {
337                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
338                 time.Sleep(time.Second)
339         }
340 }