Merge branch '13453-r-sdk-incorrect-rest-call-fix'
[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 const initialNiceValue int64 = 10000
29
30 var (
31         version           = "dev"
32         defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
33 )
34
35 type Dispatcher struct {
36         *dispatch.Dispatcher
37         cluster *arvados.Cluster
38         sqCheck *SqueueChecker
39         slurm   Slurm
40
41         Client arvados.Client
42
43         SbatchArguments []string
44         PollPeriod      arvados.Duration
45         PrioritySpread  int64
46
47         // crunch-run command to invoke. The container UUID will be
48         // appended. If nil, []string{"crunch-run"} will be used.
49         //
50         // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
51         CrunchRunCommand []string
52
53         // Extra RAM to reserve (in Bytes) for SLURM job, in addition
54         // to the amount specified in the container's RuntimeConstraints
55         ReserveExtraRAM int64
56
57         // Minimum time between two attempts to run the same container
58         MinRetryPeriod arvados.Duration
59 }
60
61 func main() {
62         disp := &Dispatcher{}
63         err := disp.Run(os.Args[0], os.Args[1:])
64         if err != nil {
65                 log.Fatal(err)
66         }
67 }
68
69 func (disp *Dispatcher) Run(prog string, args []string) error {
70         if err := disp.configure(prog, args); err != nil {
71                 return err
72         }
73         disp.setup()
74         return disp.run()
75 }
76
77 // configure() loads config files. Tests skip this.
78 func (disp *Dispatcher) configure(prog string, args []string) error {
79         flags := flag.NewFlagSet(prog, flag.ExitOnError)
80         flags.Usage = func() { usage(flags) }
81
82         configPath := flags.String(
83                 "config",
84                 defaultConfigPath,
85                 "`path` to JSON or YAML configuration file")
86         dumpConfig := flag.Bool(
87                 "dump-config",
88                 false,
89                 "write current configuration to stdout and exit")
90         getVersion := flags.Bool(
91                 "version",
92                 false,
93                 "Print version information and exit.")
94         // Parse args; omit the first arg which is the command name
95         flags.Parse(args)
96
97         // Print version information if requested
98         if *getVersion {
99                 fmt.Printf("crunch-dispatch-slurm %s\n", version)
100                 return nil
101         }
102
103         log.Printf("crunch-dispatch-slurm %s started", version)
104
105         err := disp.readConfig(*configPath)
106         if err != nil {
107                 return err
108         }
109
110         if disp.CrunchRunCommand == nil {
111                 disp.CrunchRunCommand = []string{"crunch-run"}
112         }
113
114         if disp.PollPeriod == 0 {
115                 disp.PollPeriod = arvados.Duration(10 * time.Second)
116         }
117
118         if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
119                 // Copy real configs into env vars so [a]
120                 // MakeArvadosClient() uses them, and [b] they get
121                 // propagated to crunch-run via SLURM.
122                 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
123                 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
124                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
125                 if disp.Client.Insecure {
126                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
127                 }
128                 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(disp.Client.KeepServiceURIs, " "))
129                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
130         } else {
131                 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
132         }
133
134         if *dumpConfig {
135                 return config.DumpAndExit(disp)
136         }
137
138         siteConfig, err := arvados.GetConfig(arvados.DefaultConfigFile)
139         if os.IsNotExist(err) {
140                 log.Printf("warning: no cluster config (%s), proceeding with no node types defined", err)
141         } else if err != nil {
142                 return fmt.Errorf("error loading config: %s", err)
143         } else if disp.cluster, err = siteConfig.GetCluster(""); err != nil {
144                 return fmt.Errorf("config error: %s", err)
145         }
146
147         return nil
148 }
149
150 // setup() initializes private fields after configure().
151 func (disp *Dispatcher) setup() {
152         arv, err := arvadosclient.MakeArvadosClient()
153         if err != nil {
154                 log.Fatalf("Error making Arvados client: %v", err)
155         }
156         arv.Retries = 25
157
158         disp.slurm = &slurmCLI{}
159         disp.sqCheck = &SqueueChecker{
160                 Period:         time.Duration(disp.PollPeriod),
161                 PrioritySpread: disp.PrioritySpread,
162                 Slurm:          disp.slurm,
163         }
164         disp.Dispatcher = &dispatch.Dispatcher{
165                 Arv:            arv,
166                 RunContainer:   disp.runContainer,
167                 PollPeriod:     time.Duration(disp.PollPeriod),
168                 MinRetryPeriod: time.Duration(disp.MinRetryPeriod),
169         }
170 }
171
172 func (disp *Dispatcher) run() error {
173         defer disp.sqCheck.Stop()
174
175         if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
176                 go dispatchcloud.SlurmNodeTypeFeatureKludge(disp.cluster)
177         }
178
179         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
180                 log.Printf("Error notifying init daemon: %v", err)
181         }
182         go disp.checkSqueueForOrphans()
183         return disp.Dispatcher.Run(context.Background())
184 }
185
186 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
187
188 // Check the next squeue report, and invoke TrackContainer for all the
189 // containers in the report. This gives us a chance to cancel slurm
190 // jobs started by a previous dispatch process that never released
191 // their slurm allocations even though their container states are
192 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
193 func (disp *Dispatcher) checkSqueueForOrphans() {
194         for _, uuid := range disp.sqCheck.All() {
195                 if !containerUuidPattern.MatchString(uuid) {
196                         continue
197                 }
198                 err := disp.TrackContainer(uuid)
199                 if err != nil {
200                         log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
201                 }
202         }
203 }
204
205 func (disp *Dispatcher) slurmConstraintArgs(container arvados.Container) []string {
206         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM+disp.ReserveExtraRAM) / float64(1048576)))
207
208         var disk int64
209         for _, m := range container.Mounts {
210                 if m.Kind == "tmp" {
211                         disk += m.Capacity
212                 }
213         }
214         disk = int64(math.Ceil(float64(disk) / float64(1048576)))
215         return []string{
216                 fmt.Sprintf("--mem=%d", mem),
217                 fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs),
218                 fmt.Sprintf("--tmp=%d", disk),
219         }
220 }
221
222 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
223         var args []string
224         args = append(args, disp.SbatchArguments...)
225         args = append(args, "--job-name="+container.UUID, fmt.Sprintf("--nice=%d", initialNiceValue))
226
227         if disp.cluster == nil {
228                 // no instance types configured
229                 args = append(args, disp.slurmConstraintArgs(container)...)
230         } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
231                 // ditto
232                 args = append(args, disp.slurmConstraintArgs(container)...)
233         } else if err != nil {
234                 return nil, err
235         } else {
236                 // use instancetype constraint instead of slurm mem/cpu/tmp specs
237                 args = append(args, "--constraint=instancetype="+it.Name)
238         }
239
240         if len(container.SchedulingParameters.Partitions) > 0 {
241                 args = append(args, "--partition="+strings.Join(container.SchedulingParameters.Partitions, ","))
242         }
243
244         return args, 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                                 p := int64(updated.Priority)
331                                 if p <= 1000 {
332                                         // API is providing
333                                         // user-assigned priority. If
334                                         // ctrs have equal priority,
335                                         // run the older one first.
336                                         p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
337                                 }
338                                 disp.sqCheck.SetPriority(ctr.UUID, p)
339                         }
340                 }
341         }
342 }
343 func (disp *Dispatcher) scancel(ctr arvados.Container) {
344         disp.sqCheck.L.Lock()
345         err := disp.slurm.Cancel(ctr.UUID)
346         disp.sqCheck.L.Unlock()
347
348         if err != nil {
349                 log.Printf("scancel: %s", err)
350                 time.Sleep(time.Second)
351         } else if disp.sqCheck.HasUUID(ctr.UUID) {
352                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
353                 time.Sleep(time.Second)
354         }
355 }
356
357 func (disp *Dispatcher) readConfig(path string) error {
358         err := config.LoadFile(disp, path)
359         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
360                 log.Printf("Config not specified. Continue with default configuration.")
361                 err = nil
362         }
363         return err
364 }