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