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