12573: Fix tests.
[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         "os/exec"
18         "regexp"
19         "strings"
20         "time"
21
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 // Config used by crunch-dispatch-slurm
30 type Config struct {
31         Client arvados.Client
32
33         SbatchArguments []string
34         PollPeriod      arvados.Duration
35
36         // crunch-run command to invoke. The container UUID will be
37         // appended. If nil, []string{"crunch-run"} will be used.
38         //
39         // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
40         CrunchRunCommand []string
41
42         // Minimum time between two attempts to run the same container
43         MinRetryPeriod arvados.Duration
44 }
45
46 func main() {
47         err := doMain()
48         if err != nil {
49                 log.Fatal(err)
50         }
51 }
52
53 var (
54         theConfig Config
55         sqCheck   = &SqueueChecker{}
56 )
57
58 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
59
60 func doMain() error {
61         flags := flag.NewFlagSet("crunch-dispatch-slurm", 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
73         // Parse args; omit the first arg which is the command name
74         flags.Parse(os.Args[1:])
75
76         err := readConfig(&theConfig, *configPath)
77         if err != nil {
78                 return err
79         }
80
81         if theConfig.CrunchRunCommand == nil {
82                 theConfig.CrunchRunCommand = []string{"crunch-run"}
83         }
84
85         if theConfig.PollPeriod == 0 {
86                 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
87         }
88
89         if theConfig.Client.APIHost != "" || theConfig.Client.AuthToken != "" {
90                 // Copy real configs into env vars so [a]
91                 // MakeArvadosClient() uses them, and [b] they get
92                 // propagated to crunch-run via SLURM.
93                 os.Setenv("ARVADOS_API_HOST", theConfig.Client.APIHost)
94                 os.Setenv("ARVADOS_API_TOKEN", theConfig.Client.AuthToken)
95                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
96                 if theConfig.Client.Insecure {
97                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
98                 }
99                 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
100                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
101         } else {
102                 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
103         }
104
105         if *dumpConfig {
106                 log.Fatal(config.DumpAndExit(theConfig))
107         }
108
109         arv, err := arvadosclient.MakeArvadosClient()
110         if err != nil {
111                 log.Printf("Error making Arvados client: %v", err)
112                 return err
113         }
114         arv.Retries = 25
115
116         sqCheck = &SqueueChecker{Period: time.Duration(theConfig.PollPeriod)}
117         defer sqCheck.Stop()
118
119         dispatcher := &dispatch.Dispatcher{
120                 Arv:            arv,
121                 RunContainer:   run,
122                 PollPeriod:     time.Duration(theConfig.PollPeriod),
123                 MinRetryPeriod: time.Duration(theConfig.MinRetryPeriod),
124         }
125
126         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
127                 log.Printf("Error notifying init daemon: %v", err)
128         }
129
130         go checkSqueueForOrphans(dispatcher, sqCheck)
131
132         return dispatcher.Run(context.Background())
133 }
134
135 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
136
137 // Check the next squeue report, and invoke TrackContainer for all the
138 // containers in the report. This gives us a chance to cancel slurm
139 // jobs started by a previous dispatch process that never released
140 // their slurm allocations even though their container states are
141 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
142 func checkSqueueForOrphans(dispatcher *dispatch.Dispatcher, sqCheck *SqueueChecker) {
143         for _, uuid := range sqCheck.All() {
144                 if !containerUuidPattern.MatchString(uuid) {
145                         continue
146                 }
147                 err := dispatcher.TrackContainer(uuid)
148                 if err != nil {
149                         log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
150                 }
151         }
152 }
153
154 func niceness(priority int) int {
155         if priority > 1000 {
156                 priority = 1000
157         }
158         if priority < 0 {
159                 priority = 0
160         }
161         // Niceness range 1-10000
162         return (1000 - priority) * 10
163 }
164
165 // sbatchCmd
166 func sbatchFunc(container arvados.Container) *exec.Cmd {
167         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
168
169         var disk int64
170         for _, m := range container.Mounts {
171                 if m.Kind == "tmp" {
172                         disk += m.Capacity
173                 }
174         }
175         disk = int64(math.Ceil(float64(disk) / float64(1048576)))
176
177         var sbatchArgs []string
178         sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
179         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
180         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem=%d", mem))
181         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
182         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--tmp=%d", disk))
183         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--nice=%d", niceness(container.Priority)))
184         if len(container.SchedulingParameters.Partitions) > 0 {
185                 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
186         }
187
188         return exec.Command("sbatch", sbatchArgs...)
189 }
190
191 // scancelCmd
192 func scancelFunc(container arvados.Container) *exec.Cmd {
193         return exec.Command("scancel", "--name="+container.UUID)
194 }
195
196 // scontrolCmd
197 func scontrolFunc(container arvados.Container) *exec.Cmd {
198         return exec.Command("scontrol", "update", "JobName="+container.UUID, fmt.Sprintf("Nice=%d", niceness(container.Priority)))
199 }
200
201 // Wrap these so that they can be overridden by tests
202 var sbatchCmd = sbatchFunc
203 var scancelCmd = scancelFunc
204 var scontrolCmd = scontrolFunc
205
206 // Submit job to slurm using sbatch.
207 func submit(dispatcher *dispatch.Dispatcher, container arvados.Container, crunchRunCommand []string) error {
208         cmd := sbatchCmd(container)
209
210         // Send a tiny script on stdin to execute the crunch-run
211         // command (slurm requires this to be a #! script)
212         cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
213
214         var stdout, stderr bytes.Buffer
215         cmd.Stdout = &stdout
216         cmd.Stderr = &stderr
217
218         // Mutex between squeue sync and running sbatch or scancel.
219         sqCheck.L.Lock()
220         defer sqCheck.L.Unlock()
221
222         log.Printf("exec sbatch %+q", cmd.Args)
223         err := cmd.Run()
224
225         switch err.(type) {
226         case nil:
227                 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
228                 return nil
229
230         case *exec.ExitError:
231                 dispatcher.Unlock(container.UUID)
232                 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
233
234         default:
235                 dispatcher.Unlock(container.UUID)
236                 return fmt.Errorf("exec failed: %v", err)
237         }
238 }
239
240 // Submit a container to the slurm queue (or resume monitoring if it's
241 // already in the queue).  Cancel the slurm job if the container's
242 // priority changes to zero or its state indicates it's no longer
243 // running.
244 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
245         ctx, cancel := context.WithCancel(context.Background())
246         defer cancel()
247
248         if ctr.State == dispatch.Locked && !sqCheck.HasUUID(ctr.UUID) {
249                 log.Printf("Submitting container %s to slurm", ctr.UUID)
250                 if err := submit(disp, ctr, theConfig.CrunchRunCommand); err != nil {
251                         text := fmt.Sprintf("Error submitting container %s to slurm: %s", ctr.UUID, err)
252                         log.Print(text)
253
254                         lr := arvadosclient.Dict{"log": arvadosclient.Dict{
255                                 "object_uuid": ctr.UUID,
256                                 "event_type":  "dispatch",
257                                 "properties":  map[string]string{"text": text}}}
258                         disp.Arv.Create("logs", lr, nil)
259
260                         disp.Unlock(ctr.UUID)
261                         return
262                 }
263         }
264
265         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
266         defer log.Printf("Done monitoring container %s", ctr.UUID)
267
268         // If the container disappears from the slurm queue, there is
269         // no point in waiting for further dispatch updates: just
270         // clean up and return.
271         go func(uuid string) {
272                 for ctx.Err() == nil && sqCheck.HasUUID(uuid) {
273                 }
274                 cancel()
275         }(ctr.UUID)
276
277         for {
278                 select {
279                 case <-ctx.Done():
280                         // Disappeared from squeue
281                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
282                                 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
283                         }
284                         switch ctr.State {
285                         case dispatch.Running:
286                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
287                         case dispatch.Locked:
288                                 disp.Unlock(ctr.UUID)
289                         }
290                         return
291                 case updated, ok := <-status:
292                         if !ok {
293                                 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
294                                 scancel(ctr)
295                         } else if updated.Priority == 0 {
296                                 log.Printf("Container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
297                                 scancel(ctr)
298                         } else if niceness(updated.Priority) != sqCheck.GetNiceness(ctr.UUID) && sqCheck.GetNiceness(ctr.UUID) != -1 {
299                                 // dynamically adjust priority
300                                 log.Printf("Container priority %v != %v", niceness(updated.Priority), sqCheck.GetNiceness(ctr.UUID))
301                                 scontrolUpdate(updated)
302                         }
303                 }
304         }
305 }
306
307 func scancel(ctr arvados.Container) {
308         sqCheck.L.Lock()
309         cmd := scancelCmd(ctr)
310         msg, err := cmd.CombinedOutput()
311         sqCheck.L.Unlock()
312
313         if err != nil {
314                 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
315                 time.Sleep(time.Second)
316         } else if sqCheck.HasUUID(ctr.UUID) {
317                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
318                 time.Sleep(time.Second)
319         }
320 }
321
322 func scontrolUpdate(ctr arvados.Container) {
323         sqCheck.L.Lock()
324         cmd := scontrolCmd(ctr)
325         msg, err := cmd.CombinedOutput()
326         sqCheck.L.Unlock()
327
328         if err != nil {
329                 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
330                 time.Sleep(time.Second)
331         } else if sqCheck.HasUUID(ctr.UUID) {
332                 log.Printf("Container %s priority is now %v, niceness is now %v",
333                         ctr.UUID, ctr.Priority, sqCheck.GetNiceness(ctr.UUID))
334         }
335 }
336
337 func readConfig(dst interface{}, path string) error {
338         err := config.LoadFile(dst, path)
339         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
340                 log.Printf("Config not specified. Continue with default configuration.")
341                 err = nil
342         }
343         return err
344 }