3 // Dispatcher service for Crunch that submits containers to the slurm queue.
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"
25 // Config used by crunch-dispatch-slurm
29 SbatchArguments []string
30 PollPeriod arvados.Duration
32 // crunch-run command to invoke. The container UUID will be
33 // appended. If nil, []string{"crunch-run"} will be used.
35 // Example: []string{"crunch-run", "--cgroup-parent-subsystem=memory"}
36 CrunchRunCommand []string
38 // Minimum time between two attempts to run the same container
39 MinRetryPeriod arvados.Duration
51 sqCheck = &SqueueChecker{}
54 const defaultConfigPath = "/etc/arvados/crunch-dispatch-slurm/crunch-dispatch-slurm.yml"
57 flags := flag.NewFlagSet("crunch-dispatch-slurm", flag.ExitOnError)
58 flags.Usage = func() { usage(flags) }
60 configPath := flags.String(
63 "`path` to JSON or YAML configuration file")
64 dumpConfig := flag.Bool(
67 "write current configuration to stdout and exit")
69 // Parse args; omit the first arg which is the command name
70 flags.Parse(os.Args[1:])
72 err := readConfig(&theConfig, *configPath)
77 if theConfig.CrunchRunCommand == nil {
78 theConfig.CrunchRunCommand = []string{"crunch-run"}
81 if theConfig.PollPeriod == 0 {
82 theConfig.PollPeriod = arvados.Duration(10 * time.Second)
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")
95 os.Setenv("ARVADOS_KEEP_SERVICES", strings.Join(theConfig.Client.KeepServiceURIs, " "))
96 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
98 log.Printf("warning: Client credentials missing from config, so falling back on environment variables (deprecated).")
102 log.Fatal(config.DumpAndExit(theConfig))
105 arv, err := arvadosclient.MakeArvadosClient()
107 log.Printf("Error making Arvados client: %v", err)
112 sqCheck = &SqueueChecker{Period: time.Duration(theConfig.PollPeriod)}
115 dispatcher := &dispatch.Dispatcher{
118 PollPeriod: time.Duration(theConfig.PollPeriod),
119 MinRetryPeriod: time.Duration(theConfig.MinRetryPeriod),
122 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
123 log.Printf("Error notifying init daemon: %v", err)
126 go checkSqueueForOrphans(dispatcher, sqCheck)
128 return dispatcher.Run(context.Background())
131 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
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) {
143 err := dispatcher.TrackContainer(uuid)
145 log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
151 func sbatchFunc(container arvados.Container) *exec.Cmd {
152 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+container.RuntimeConstraints.KeepCacheRAM) / float64(1048576)))
155 for _, m := range container.Mounts {
160 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
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, ",")))
172 return exec.Command("sbatch", sbatchArgs...)
176 func scancelFunc(container arvados.Container) *exec.Cmd {
177 return exec.Command("scancel", "--name="+container.UUID)
180 // Wrap these so that they can be overridden by tests
181 var sbatchCmd = sbatchFunc
182 var scancelCmd = scancelFunc
184 // Submit job to slurm using sbatch.
185 func submit(dispatcher *dispatch.Dispatcher, container arvados.Container, crunchRunCommand []string) error {
186 cmd := sbatchCmd(container)
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)))
192 var stdout, stderr bytes.Buffer
196 // Mutex between squeue sync and running sbatch or scancel.
198 defer sqCheck.L.Unlock()
200 log.Printf("exec sbatch %+q", cmd.Args)
205 log.Printf("sbatch succeeded: %q", strings.TrimSpace(stdout.String()))
208 case *exec.ExitError:
209 dispatcher.Unlock(container.UUID)
210 return fmt.Errorf("sbatch %+q failed: %v (stderr: %q)", cmd.Args, err, stderr.Bytes())
213 dispatcher.Unlock(container.UUID)
214 return fmt.Errorf("exec failed: %v", err)
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
222 func run(disp *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) {
223 ctx, cancel := context.WithCancel(context.Background())
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)
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)
238 disp.Unlock(ctr.UUID)
243 log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
244 defer log.Printf("Done monitoring container %s", ctr.UUID)
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) {
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)
263 case dispatch.Running:
264 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
265 case dispatch.Locked:
266 disp.Unlock(ctr.UUID)
269 case updated, ok := <-status:
271 log.Printf("Dispatcher says container %s is done: cancel slurm job", ctr.UUID)
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)
281 func scancel(ctr arvados.Container) {
283 cmd := scancelCmd(ctr)
284 msg, err := cmd.CombinedOutput()
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)
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.")