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