Merge branch '13933-dispatch-batch-size'
[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         // Batch size for container queries
62         BatchSize int64
63 }
64
65 func main() {
66         disp := &Dispatcher{}
67         err := disp.Run(os.Args[0], os.Args[1:])
68         if err != nil {
69                 log.Fatal(err)
70         }
71 }
72
73 func (disp *Dispatcher) Run(prog string, args []string) error {
74         if err := disp.configure(prog, args); err != nil {
75                 return err
76         }
77         disp.setup()
78         return disp.run()
79 }
80
81 // configure() loads config files. Tests skip this.
82 func (disp *Dispatcher) configure(prog string, args []string) error {
83         flags := flag.NewFlagSet(prog, flag.ExitOnError)
84         flags.Usage = func() { usage(flags) }
85
86         configPath := flags.String(
87                 "config",
88                 defaultConfigPath,
89                 "`path` to JSON or YAML configuration file")
90         dumpConfig := flag.Bool(
91                 "dump-config",
92                 false,
93                 "write current configuration to stdout and exit")
94         getVersion := flags.Bool(
95                 "version",
96                 false,
97                 "Print version information and exit.")
98         // Parse args; omit the first arg which is the command name
99         flags.Parse(args)
100
101         // Print version information if requested
102         if *getVersion {
103                 fmt.Printf("crunch-dispatch-slurm %s\n", version)
104                 return nil
105         }
106
107         log.Printf("crunch-dispatch-slurm %s started", version)
108
109         err := disp.readConfig(*configPath)
110         if err != nil {
111                 return err
112         }
113
114         if disp.CrunchRunCommand == nil {
115                 disp.CrunchRunCommand = []string{"crunch-run"}
116         }
117
118         if disp.PollPeriod == 0 {
119                 disp.PollPeriod = arvados.Duration(10 * time.Second)
120         }
121
122         if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
123                 // Copy real configs into env vars so [a]
124                 // MakeArvadosClient() uses them, and [b] they get
125                 // propagated to crunch-run via SLURM.
126                 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
127                 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
128                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
129                 if disp.Client.Insecure {
130                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
131                 }
132                 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(disp.Client.KeepServiceURIs, " "))
133                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
134         } else {
135                 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
136         }
137
138         if *dumpConfig {
139                 return config.DumpAndExit(disp)
140         }
141
142         siteConfig, err := arvados.GetConfig(arvados.DefaultConfigFile)
143         if os.IsNotExist(err) {
144                 log.Printf("warning: no cluster config (%s), proceeding with no node types defined", err)
145         } else if err != nil {
146                 return fmt.Errorf("error loading config: %s", err)
147         } else if disp.cluster, err = siteConfig.GetCluster(""); err != nil {
148                 return fmt.Errorf("config error: %s", err)
149         }
150
151         return nil
152 }
153
154 // setup() initializes private fields after configure().
155 func (disp *Dispatcher) setup() {
156         arv, err := arvadosclient.MakeArvadosClient()
157         if err != nil {
158                 log.Fatalf("Error making Arvados client: %v", err)
159         }
160         arv.Retries = 25
161
162         disp.slurm = &slurmCLI{}
163         disp.sqCheck = &SqueueChecker{
164                 Period:         time.Duration(disp.PollPeriod),
165                 PrioritySpread: disp.PrioritySpread,
166                 Slurm:          disp.slurm,
167         }
168         disp.Dispatcher = &dispatch.Dispatcher{
169                 Arv:            arv,
170                 BatchSize:      disp.BatchSize,
171                 RunContainer:   disp.runContainer,
172                 PollPeriod:     time.Duration(disp.PollPeriod),
173                 MinRetryPeriod: time.Duration(disp.MinRetryPeriod),
174         }
175 }
176
177 func (disp *Dispatcher) run() error {
178         defer disp.sqCheck.Stop()
179
180         if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
181                 go dispatchcloud.SlurmNodeTypeFeatureKludge(disp.cluster)
182         }
183
184         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
185                 log.Printf("Error notifying init daemon: %v", err)
186         }
187         go disp.checkSqueueForOrphans()
188         return disp.Dispatcher.Run(context.Background())
189 }
190
191 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
192
193 // Check the next squeue report, and invoke TrackContainer for all the
194 // containers in the report. This gives us a chance to cancel slurm
195 // jobs started by a previous dispatch process that never released
196 // their slurm allocations even though their container states are
197 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
198 func (disp *Dispatcher) checkSqueueForOrphans() {
199         for _, uuid := range disp.sqCheck.All() {
200                 if !containerUuidPattern.MatchString(uuid) {
201                         continue
202                 }
203                 err := disp.TrackContainer(uuid)
204                 if err != nil {
205                         log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
206                 }
207         }
208 }
209
210 func (disp *Dispatcher) slurmConstraintArgs(container arvados.Container) []string {
211         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM+disp.ReserveExtraRAM) / float64(1048576)))
212
213         var disk int64
214         for _, m := range container.Mounts {
215                 if m.Kind == "tmp" {
216                         disk += m.Capacity
217                 }
218         }
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.SbatchArguments...)
230         args = append(args, "--job-name="+container.UUID, fmt.Sprintf("--nice=%d", initialNiceValue))
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, container.UUID)
257         crScript := strings.NewReader(execScript(crArgs))
258
259         sbArgs, err := disp.sbatchArgs(container)
260         if err != nil {
261                 return err
262         }
263         log.Printf("running sbatch %+q", sbArgs)
264         return disp.slurm.Batch(crScript, sbArgs)
265 }
266
267 // Submit a container to the slurm queue (or resume monitoring if it's
268 // already in the queue).  Cancel the slurm job if the container's
269 // priority changes to zero or its state indicates it's no longer
270 // running.
271 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
272         ctx, cancel := context.WithCancel(context.Background())
273         defer cancel()
274
275         if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
276                 log.Printf("Submitting container %s to slurm", ctr.UUID)
277                 if err := disp.submit(ctr, disp.CrunchRunCommand); err != nil {
278                         var text string
279                         if err, ok := err.(dispatchcloud.ConstraintsNotSatisfiableError); ok {
280                                 var logBuf bytes.Buffer
281                                 fmt.Fprintf(&logBuf, "cannot run container %s: %s\n", ctr.UUID, err)
282                                 if len(err.AvailableTypes) == 0 {
283                                         fmt.Fprint(&logBuf, "No instance types are configured.\n")
284                                 } else {
285                                         fmt.Fprint(&logBuf, "Available instance types:\n")
286                                         for _, t := range err.AvailableTypes {
287                                                 fmt.Fprintf(&logBuf,
288                                                         "Type %q: %d VCPUs, %d RAM, %d Scratch, %f Price\n",
289                                                         t.Name, t.VCPUs, t.RAM, t.Scratch, t.Price,
290                                                 )
291                                         }
292                                 }
293                                 text = logBuf.String()
294                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
295                         } else {
296                                 text = fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
297                         }
298                         log.Print(text)
299
300                         lr := arvadosclient.Dict{"log": arvadosclient.Dict{
301                                 "object_uuid": ctr.UUID,
302                                 "event_type":  "dispatch",
303                                 "properties":  map[string]string{"text": text}}}
304                         disp.Arv.Create("logs", lr, nil)
305
306                         disp.Unlock(ctr.UUID)
307                         return
308                 }
309         }
310
311         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
312         defer log.Printf("Done monitoring container %s", ctr.UUID)
313
314         // If the container disappears from the slurm queue, there is
315         // no point in waiting for further dispatch updates: just
316         // clean up and return.
317         go func(uuid string) {
318                 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
319                 }
320                 cancel()
321         }(ctr.UUID)
322
323         for {
324                 select {
325                 case <-ctx.Done():
326                         // Disappeared from squeue
327                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
328                                 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
329                         }
330                         switch ctr.State {
331                         case dispatch.Running:
332                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
333                         case dispatch.Locked:
334                                 disp.Unlock(ctr.UUID)
335                         }
336                         return
337                 case updated, ok := <-status:
338                         if !ok {
339                                 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
340                                 disp.scancel(ctr)
341                         } else if updated.Priority == 0 {
342                                 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
343                                 disp.scancel(ctr)
344                         } else {
345                                 p := int64(updated.Priority)
346                                 if p <= 1000 {
347                                         // API is providing
348                                         // user-assigned priority. If
349                                         // ctrs have equal priority,
350                                         // run the older one first.
351                                         p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
352                                 }
353                                 disp.sqCheck.SetPriority(ctr.UUID, p)
354                         }
355                 }
356         }
357 }
358 func (disp *Dispatcher) scancel(ctr arvados.Container) {
359         err := disp.slurm.Cancel(ctr.UUID)
360         if err != nil {
361                 log.Printf("scancel: %s", err)
362                 time.Sleep(time.Second)
363         } else if disp.sqCheck.HasUUID(ctr.UUID) {
364                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
365                 time.Sleep(time.Second)
366         }
367 }
368
369 func (disp *Dispatcher) readConfig(path string) error {
370         err := config.LoadFile(disp, path)
371         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
372                 log.Printf("Config not specified. Continue with default configuration.")
373                 err = nil
374         }
375         return err
376 }