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