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