11308: Eliminate old_div().
[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         memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
153
154         var sbatchArgs []string
155         sbatchArgs = append(sbatchArgs, "--share")
156         sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
157         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
158         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
159         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
160         if len(container.SchedulingParameters.Partitions) > 0 {
161                 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
162         }
163
164         return exec.Command("sbatch", sbatchArgs...)
165 }
166
167 // scancelCmd
168 func scancelFunc(container arvados.Container) *exec.Cmd {
169         return exec.Command("scancel", "--name="+container.UUID)
170 }
171
172 // Wrap these so that they can be overridden by tests
173 var sbatchCmd = sbatchFunc
174 var scancelCmd = scancelFunc
175
176 // Submit job to slurm using sbatch.
177 func submit(dispatcher *dispatch.Dispatcher, container arvados.Container, crunchRunCommand []string) error {
178         cmd := sbatchCmd(container)
179
180         // Send a tiny script on stdin to execute the crunch-run
181         // command (slurm requires this to be a #! script)
182         cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
183
184         var stdout, stderr bytes.Buffer
185         cmd.Stdout = &stdout
186         cmd.Stderr = &stderr
187
188         // Mutex between squeue sync and running sbatch or scancel.
189         sqCheck.L.Lock()
190         defer sqCheck.L.Unlock()
191
192         log.Printf("exec sbatch %+q", cmd.Args)
193         err := cmd.Run()
194
195         switch err.(type) {
196         case nil:
197                 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
198                 return nil
199
200         case *exec.ExitError:
201                 dispatcher.Unlock(container.UUID)
202                 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
203
204         default:
205                 dispatcher.Unlock(container.UUID)
206                 return fmt.Errorf("exec failed: %v", err)
207         }
208 }
209
210 // Submit a container to the slurm queue (or resume monitoring if it's
211 // already in the queue).  Cancel the slurm job if the container's
212 // priority changes to zero or its state indicates it's no longer
213 // running.
214 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
215         ctx, cancel := context.WithCancel(context.Background())
216         defer cancel()
217
218         if ctr.State == dispatch.Locked && !sqCheck.HasUUID(ctr.UUID) {
219                 log.Printf("Submitting container %s to slurm", ctr.UUID)
220                 if err := submit(disp, ctr, theConfig.CrunchRunCommand); err != nil {
221                         log.Printf("Error submitting container %s to slurm: %s", ctr.UUID, err)
222                         disp.Unlock(ctr.UUID)
223                         return
224                 }
225         }
226
227         log.Printf("Start monitoring container %s", ctr.UUID)
228         defer log.Printf("Done monitoring container %s", ctr.UUID)
229
230         // If the container disappears from the slurm queue, there is
231         // no point in waiting for further dispatch updates: just
232         // clean up and return.
233         go func(uuid string) {
234                 for ctx.Err() == nil && sqCheck.HasUUID(uuid) {
235                 }
236                 cancel()
237         }(ctr.UUID)
238
239         for {
240                 select {
241                 case <-ctx.Done():
242                         // Disappeared from squeue
243                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
244                                 log.Printf("Error getting final container state for %s: %s", ctr.UUID, err)
245                         }
246                         switch ctr.State {
247                         case dispatch.Running:
248                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
249                         case dispatch.Locked:
250                                 disp.Unlock(ctr.UUID)
251                         }
252                         return
253                 case updated, ok := <-status:
254                         if !ok {
255                                 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
256                                 scancel(ctr)
257                         } else if updated.Priority == 0 {
258                                 log.Printf("Container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
259                                 scancel(ctr)
260                         }
261                 }
262         }
263 }
264
265 func scancel(ctr arvados.Container) {
266         sqCheck.L.Lock()
267         cmd := scancelCmd(ctr)
268         msg, err := cmd.CombinedOutput()
269         sqCheck.L.Unlock()
270
271         if err != nil {
272                 log.Printf("%q %q: %s %q", cmd.Path, cmd.Args, err, msg)
273                 time.Sleep(time.Second)
274         } else if sqCheck.HasUUID(ctr.UUID) {
275                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
276                 time.Sleep(time.Second)
277         }
278 }
279
280 func readConfig(dst interface{}, path string) error {
281         err := config.LoadFile(dst, path)
282         if err != nil && os.IsNotExist(err) && path == defaultConfigPath {
283                 log.Printf("Config not specified. Continue with default configuration.")
284                 err = nil
285         }
286         return err
287 }