10700: Rephrase "should cancel" condition to be less unclear.
[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         "flag"
8         "fmt"
9         "git.curoverse.com/arvados.git/sdk/go/arvados"
10         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
11         "git.curoverse.com/arvados.git/sdk/go/config"
12         "git.curoverse.com/arvados.git/sdk/go/dispatch"
13         "github.com/coreos/go-systemd/daemon"
14         "log"
15         "math"
16         "os"
17         "os/exec"
18         "strings"
19         "time"
20 )
21
22 // Config used by crunch-dispatch-slurm
23 type Config struct {
24         Client arvados.Client
25
26         SbatchArguments []string
27         PollPeriod      arvados.Duration
28
29         // crunch-run command to invoke. The container UUID will be
30         // appended. If nil, []string{"crunch-run"} will be used.
31         //
32         // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
33         CrunchRunCommand []string
34
35         // Minimum time between two attempts to run the same container
36         MinRetryPeriod arvados.Duration
37 }
38
39 func main() {
40         err := doMain()
41         if err != nil {
42                 log.Fatal(err)
43         }
44 }
45
46 var (
47         theConfig     Config
48         squeueUpdater Squeue
49 )
50
51 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
52
53 func doMain() error {
54         flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
55         flags.Usage = func() { usage(flags) }
56
57         configPath := flags.String(
58                 "config",
59                 defaultConfigPath,
60                 "`path` to JSON or YAML configuration file")
61
62         // Parse args; omit the first arg which is the command name
63         flags.Parse(os.Args[1:])
64
65         err := readConfig(&theConfig, *configPath)
66         if err != nil {
67                 return err
68         }
69
70         if theConfig.CrunchRunCommand == nil {
71                 theConfig.CrunchRunCommand = []string{"crunch-run"}
72         }
73
74         if theConfig.PollPeriod == 0 {
75                 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
76         }
77
78         if theConfig.Client.APIHost != "" || theConfig.Client.AuthToken != "" {
79                 // Copy real configs into env vars so [a]
80                 // MakeArvadosClient() uses them, and [b] they get
81                 // propagated to crunch-run via SLURM.
82                 os.Setenv("ARVADOS_API_HOST", theConfig.Client.APIHost)
83                 os.Setenv("ARVADOS_API_TOKEN", theConfig.Client.AuthToken)
84                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
85                 if theConfig.Client.Insecure {
86                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
87                 }
88                 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
89                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
90         } else {
91                 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
92         }
93
94         arv, err := arvadosclient.MakeArvadosClient()
95         if err != nil {
96                 log.Printf("Error making Arvados client: %v", err)
97                 return err
98         }
99         arv.Retries = 25
100
101         squeueUpdater.StartMonitor(time.Duration(theConfig.PollPeriod))
102         defer squeueUpdater.Done()
103
104         dispatcher := dispatch.Dispatcher{
105                 Arv:            arv,
106                 RunContainer:   run,
107                 PollPeriod:     time.Duration(theConfig.PollPeriod),
108                 MinRetryPeriod: time.Duration(theConfig.MinRetryPeriod),
109         }
110
111         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
112                 log.Printf("Error notifying init daemon: %v", err)
113         }
114
115         return dispatcher.Run()
116 }
117
118 // sbatchCmd
119 func sbatchFunc(container arvados.Container) *exec.Cmd {
120         memPerCPU := math.Ceil(float64(container.RuntimeConstraints.RAM) / (float64(container.RuntimeConstraints.VCPUs) * 1048576))
121
122         var sbatchArgs []string
123         sbatchArgs = append(sbatchArgs, "--share")
124         sbatchArgs = append(sbatchArgs, theConfig.SbatchArguments...)
125         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--job-name=%s", container.UUID))
126         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--mem-per-cpu=%d", int(memPerCPU)))
127         sbatchArgs = append(sbatchArgs, fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs))
128         if container.SchedulingParameters.Partitions != nil {
129                 sbatchArgs = append(sbatchArgs, fmt.Sprintf("--partition=%s", strings.Join(container.SchedulingParameters.Partitions, ",")))
130         }
131
132         return exec.Command("sbatch", sbatchArgs...)
133 }
134
135 // scancelCmd
136 func scancelFunc(container arvados.Container) *exec.Cmd {
137         return exec.Command("scancel", "--name="+container.UUID)
138 }
139
140 // Wrap these so that they can be overridden by tests
141 var sbatchCmd = sbatchFunc
142 var scancelCmd = scancelFunc
143
144 // Submit job to slurm using sbatch.
145 func submit(dispatcher *dispatch.Dispatcher,
146         container arvados.Container, crunchRunCommand []string) (submitErr error) {
147         defer func() {
148                 // If we didn't get as far as submitting a slurm job,
149                 // unlock the container and return it to the queue.
150                 if submitErr == nil {
151                         // OK, no cleanup needed
152                         return
153                 }
154                 err := dispatcher.Unlock(container.UUID)
155                 if err != nil {
156                         log.Printf("Error unlocking container %s: %v", container.UUID, err)
157                 }
158         }()
159
160         cmd := sbatchCmd(container)
161
162         // Send a tiny script on stdin to execute the crunch-run
163         // command (slurm requires this to be a #! script)
164         cmd.Stdin = strings.NewReader(execScript(append(crunchRunCommand, container.UUID)))
165
166         var stdout, stderr bytes.Buffer
167         cmd.Stdout = &stdout
168         cmd.Stderr = &stderr
169
170         // Mutex between squeue sync and running sbatch or scancel.
171         squeueUpdater.SlurmLock.Lock()
172         defer squeueUpdater.SlurmLock.Unlock()
173
174         log.Printf("exec sbatch %+q", cmd.Args)
175         err := cmd.Run()
176         switch err.(type) {
177         case nil:
178                 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
179                 return nil
180         case *exec.ExitError:
181                 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr)
182         default:
183                 return fmt.Errorf("exec failed: %v", err)
184         }
185 }
186
187 // If the container is marked as Locked, check if it is already in the slurm
188 // queue.  If not, submit it.
189 //
190 // If the container is marked as Running, check if it is in the slurm queue.
191 // If not, mark it as Cancelled.
192 func monitorSubmitOrCancel(dispatcher *dispatch.Dispatcher, container arvados.Container, monitorDone *bool) {
193         submitted := false
194         for !*monitorDone {
195                 if squeueUpdater.CheckSqueue(container.UUID) {
196                         // Found in the queue, so continue monitoring
197                         submitted = true
198                 } else if container.State == dispatch.Locked && !submitted {
199                         // Not in queue but in Locked state and we haven't
200                         // submitted it yet, so submit it.
201
202                         log.Printf("About to submit queued container %v", container.UUID)
203
204                         if err := submit(dispatcher, container, theConfig.CrunchRunCommand); err != nil {
205                                 log.Printf("Error submitting container %s to slurm: %v",
206                                         container.UUID, err)
207                                 // maybe sbatch is broken, put it back to queued
208                                 dispatcher.Unlock(container.UUID)
209                         }
210                         submitted = true
211                 } else {
212                         // Not in queue and we are not going to submit it.
213                         // Refresh the container state. If it is
214                         // Complete/Cancelled, do nothing, if it is Locked then
215                         // release it back to the Queue, if it is Running then
216                         // clean up the record.
217
218                         var con arvados.Container
219                         err := dispatcher.Arv.Get("containers", container.UUID, nil, &con)
220                         if err != nil {
221                                 log.Printf("Error getting final container state: %v", err)
222                         }
223
224                         switch con.State {
225                         case dispatch.Locked:
226                                 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
227                                         container.UUID, con.State, dispatch.Queued)
228                                 dispatcher.Unlock(container.UUID)
229                         case dispatch.Running:
230                                 st := dispatch.Cancelled
231                                 log.Printf("Container %s in state %v but missing from slurm queue, changing to %v.",
232                                         container.UUID, con.State, st)
233                                 dispatcher.UpdateState(container.UUID, st)
234                         default:
235                                 // Container state is Queued, Complete or Cancelled so stop monitoring it.
236                                 return
237                         }
238                 }
239         }
240 }
241
242 // Run or monitor a container.
243 //
244 // Monitor status updates.  If the priority changes to zero, cancel the
245 // container using scancel.
246 func run(dispatcher *dispatch.Dispatcher,
247         container arvados.Container,
248         status chan arvados.Container) {
249
250         log.Printf("Monitoring container %v started", container.UUID)
251         defer log.Printf("Monitoring container %v finished", container.UUID)
252
253         monitorDone := false
254         go monitorSubmitOrCancel(dispatcher, container, &monitorDone)
255
256         for container = range status {
257                 if container.Priority == 0 && (container.State == dispatch.Locked || container.State == dispatch.Running) {
258                         log.Printf("Canceling container %s", container.UUID)
259                         // Mutex between squeue sync and running sbatch or scancel.
260                         squeueUpdater.SlurmLock.Lock()
261                         cmd := scancelCmd(container)
262                         msg, err := cmd.CombinedOutput()
263                         squeueUpdater.SlurmLock.Unlock()
264
265                         if err != nil {
266                                 log.Printf("Error stopping container %s with %v %v: %v %v", container.UUID, cmd.Path, cmd.Args, err, string(msg))
267                                 if squeueUpdater.CheckSqueue(container.UUID) {
268                                         log.Printf("Container %s is still in squeue after scancel.", container.UUID)
269                                         continue
270                                 }
271                         }
272
273                         // Ignore errors; if necessary, we'll try again next time
274                         dispatcher.UpdateState(container.UUID, dispatch.Cancelled)
275                 }
276         }
277         monitorDone = true
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 }