13933: Fix formatting.
[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         disp.sqCheck.L.Lock()
260         defer disp.sqCheck.L.Unlock()
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) {
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                 if err := disp.submit(ctr, disp.CrunchRunCommand); err != nil {
281                         var text string
282                         if err, ok := err.(dispatchcloud.ConstraintsNotSatisfiableError); ok {
283                                 var logBuf bytes.Buffer
284                                 fmt.Fprintf(&logBuf, "cannot run container %s: %s\n", ctr.UUID, err)
285                                 if len(err.AvailableTypes) == 0 {
286                                         fmt.Fprint(&logBuf, "No instance types are configured.\n")
287                                 } else {
288                                         fmt.Fprint(&logBuf, "Available instance types:\n")
289                                         for _, t := range err.AvailableTypes {
290                                                 fmt.Fprintf(&logBuf,
291                                                         "Type %q: %d VCPUs, %d RAM, %d Scratch, %f Price\n",
292                                                         t.Name, t.VCPUs, t.RAM, t.Scratch, t.Price,
293                                                 )
294                                         }
295                                 }
296                                 text = logBuf.String()
297                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
298                         } else {
299                                 text = fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
300                         }
301                         log.Print(text)
302
303                         lr := arvadosclient.Dict{"log": arvadosclient.Dict{
304                                 "object_uuid": ctr.UUID,
305                                 "event_type":  "dispatch",
306                                 "properties":  map[string]string{"text": text}}}
307                         disp.Arv.Create("logs", lr, nil)
308
309                         disp.Unlock(ctr.UUID)
310                         return
311                 }
312         }
313
314         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
315         defer log.Printf("Done monitoring container %s", ctr.UUID)
316
317         // If the container disappears from the slurm queue, there is
318         // no point in waiting for further dispatch updates: just
319         // clean up and return.
320         go func(uuid string) {
321                 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
322                 }
323                 cancel()
324         }(ctr.UUID)
325
326         for {
327                 select {
328                 case <-ctx.Done():
329                         // Disappeared from squeue
330                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
331                                 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
332                         }
333                         switch ctr.State {
334                         case dispatch.Running:
335                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
336                         case dispatch.Locked:
337                                 disp.Unlock(ctr.UUID)
338                         }
339                         return
340                 case updated, ok := <-status:
341                         if !ok {
342                                 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
343                                 disp.scancel(ctr)
344                         } else if updated.Priority == 0 {
345                                 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
346                                 disp.scancel(ctr)
347                         } else {
348                                 p := int64(updated.Priority)
349                                 if p <= 1000 {
350                                         // API is providing
351                                         // user-assigned priority. If
352                                         // ctrs have equal priority,
353                                         // run the older one first.
354                                         p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
355                                 }
356                                 disp.sqCheck.SetPriority(ctr.UUID, p)
357                         }
358                 }
359         }
360 }
361 func (disp *Dispatcher) scancel(ctr arvados.Container) {
362         disp.sqCheck.L.Lock()
363         err := disp.slurm.Cancel(ctr.UUID)
364         disp.sqCheck.L.Unlock()
365
366         if err != nil {
367                 log.Printf("scancel: %s", err)
368                 time.Sleep(time.Second)
369         } else if disp.sqCheck.HasUUID(ctr.UUID) {
370                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
371                 time.Sleep(time.Second)
372         }
373 }
374
375 func (disp *Dispatcher) readConfig(path string) error {
376         err := config.LoadFile(disp, path)
377         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
378                 log.Printf("Config not specified. Continue with default configuration.")
379                 err = nil
380         }
381         return err
382 }