1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 // Dispatcher service for Crunch that submits containers to the slurm queue.
19 "git.arvados.org/arvados.git/lib/cmd"
20 "git.arvados.org/arvados.git/lib/dispatchcloud"
21 "git.arvados.org/arvados.git/lib/service"
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
24 "git.arvados.org/arvados.git/sdk/go/ctxlog"
25 "git.arvados.org/arvados.git/sdk/go/dispatch"
26 "github.com/coreos/go-systemd/daemon"
27 "github.com/prometheus/client_golang/prometheus"
28 "github.com/sirupsen/logrus"
31 var Command cmd.Handler = service.Command(arvados.ServiceNameDispatchSLURM, newHandler)
33 func newHandler(ctx context.Context, cluster *arvados.Cluster, _ string, _ *prometheus.Registry) service.Handler {
34 logger := ctxlog.FromContext(ctx)
35 disp := &Dispatcher{logger: logger, cluster: cluster}
36 if err := disp.configure(); err != nil {
37 return service.ErrorHandler(ctx, cluster, err)
47 type logger interface {
49 Fatalf(string, ...interface{})
52 const initialNiceValue int64 = 10000
54 type Dispatcher struct {
56 logger logrus.FieldLogger
57 cluster *arvados.Cluster
58 sqCheck *SqueueChecker
67 func (disp *Dispatcher) CheckHealth() error {
71 func (disp *Dispatcher) Done() <-chan struct{} {
75 func (disp *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
79 // configure() loads config files. Some tests skip this (see
81 func (disp *Dispatcher) configure() error {
82 if disp.logger == nil {
83 disp.logger = logrus.StandardLogger()
85 disp.logger = disp.logger.WithField("ClusterID", disp.cluster.ClusterID)
86 disp.logger.Printf("crunch-dispatch-slurm %s started", cmd.Version.String())
88 disp.Client.APIHost = disp.cluster.Services.Controller.ExternalURL.Host
89 disp.Client.AuthToken = disp.cluster.SystemRootToken
90 disp.Client.Insecure = disp.cluster.TLS.Insecure
92 if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
93 // Copy real configs into env vars so [a]
94 // MakeArvadosClient() uses them, and [b] they get
95 // propagated to crunch-run via SLURM.
96 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
97 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
98 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
99 if disp.Client.Insecure {
100 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
102 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
103 for k, v := range disp.cluster.Containers.SLURM.SbatchEnvironmentVariables {
107 disp.logger.Warnf("Client credentials missing from config, so falling back on environment variables (deprecated).")
112 // setup() initializes private fields after configure().
113 func (disp *Dispatcher) setup() {
114 disp.done = make(chan struct{})
115 arv, err := arvadosclient.MakeArvadosClient()
117 disp.logger.Fatalf("Error making Arvados client: %v", err)
121 disp.slurm = NewSlurmCLI()
122 disp.sqCheck = &SqueueChecker{
124 Period: time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
125 PrioritySpread: disp.cluster.Containers.SLURM.PrioritySpread,
128 disp.Dispatcher = &dispatch.Dispatcher{
131 BatchSize: disp.cluster.API.MaxItemsPerResponse,
132 RunContainer: disp.runContainer,
133 PollPeriod: time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
134 MinRetryPeriod: time.Duration(disp.cluster.Containers.MinRetryPeriod),
138 func (disp *Dispatcher) run() error {
139 defer disp.sqCheck.Stop()
141 if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
142 go SlurmNodeTypeFeatureKludge(disp.cluster)
145 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
146 log.Printf("Error notifying init daemon: %v", err)
148 go disp.checkSqueueForOrphans()
149 return disp.Dispatcher.Run(context.Background())
152 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
154 // Check the next squeue report, and invoke TrackContainer for all the
155 // containers in the report. This gives us a chance to cancel slurm
156 // jobs started by a previous dispatch process that never released
157 // their slurm allocations even though their container states are
158 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
159 func (disp *Dispatcher) checkSqueueForOrphans() {
160 for _, uuid := range disp.sqCheck.All() {
161 if !containerUuidPattern.MatchString(uuid) || !strings.HasPrefix(uuid, disp.cluster.ClusterID) {
164 err := disp.TrackContainer(uuid)
166 log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
171 func (disp *Dispatcher) slurmConstraintArgs(container arvados.Container) []string {
172 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+
173 container.RuntimeConstraints.KeepCacheRAM+
174 int64(disp.cluster.Containers.ReserveExtraRAM)) / float64(1048576)))
176 disk := dispatchcloud.EstimateScratchSpace(&container)
177 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
179 fmt.Sprintf("--mem=%d", mem),
180 fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs),
181 fmt.Sprintf("--tmp=%d", disk),
185 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
187 args = append(args, disp.cluster.Containers.SLURM.SbatchArgumentsList...)
188 args = append(args, "--job-name="+container.UUID, fmt.Sprintf("--nice=%d", initialNiceValue), "--no-requeue")
190 if disp.cluster == nil {
191 // no instance types configured
192 args = append(args, disp.slurmConstraintArgs(container)...)
193 } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
195 args = append(args, disp.slurmConstraintArgs(container)...)
196 } else if err != nil {
199 // use instancetype constraint instead of slurm mem/cpu/tmp specs
200 args = append(args, "--constraint=instancetype="+it.Name)
203 if len(container.SchedulingParameters.Partitions) > 0 {
204 args = append(args, "--partition="+strings.Join(container.SchedulingParameters.Partitions, ","))
210 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
211 // append() here avoids modifying crunchRunCommand's
212 // underlying array, which is shared with other goroutines.
213 crArgs := append([]string(nil), crunchRunCommand...)
214 crArgs = append(crArgs, "--runtime-engine="+disp.cluster.Containers.RuntimeEngine)
215 crArgs = append(crArgs, container.UUID)
216 crScript := strings.NewReader(execScript(crArgs))
218 sbArgs, err := disp.sbatchArgs(container)
222 log.Printf("running sbatch %+q", sbArgs)
223 return disp.slurm.Batch(crScript, sbArgs)
226 // Submit a container to the slurm queue (or resume monitoring if it's
227 // already in the queue). Cancel the slurm job if the container's
228 // priority changes to zero or its state indicates it's no longer
230 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) error {
231 ctx, cancel := context.WithCancel(context.Background())
234 if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
235 log.Printf("Submitting container %s to slurm", ctr.UUID)
236 cmd := []string{disp.cluster.Containers.CrunchRunCommand}
237 cmd = append(cmd, disp.cluster.Containers.CrunchRunArgumentsList...)
238 err := disp.submit(ctr, cmd)
244 log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
245 defer log.Printf("Done monitoring container %s", ctr.UUID)
247 // If the container disappears from the slurm queue, there is
248 // no point in waiting for further dispatch updates: just
249 // clean up and return.
250 go func(uuid string) {
251 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
259 // Disappeared from squeue
260 if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
261 log.Printf("error getting final container state for %s: %s", ctr.UUID, err)
264 case dispatch.Running:
265 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
266 case dispatch.Locked:
267 disp.Unlock(ctr.UUID)
270 case updated, ok := <-status:
272 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
274 } else if updated.Priority == 0 {
275 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
278 p := int64(updated.Priority)
281 // user-assigned priority. If
282 // ctrs have equal priority,
283 // run the older one first.
284 p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
286 disp.sqCheck.SetPriority(ctr.UUID, p)
291 func (disp *Dispatcher) scancel(ctr arvados.Container) {
292 err := disp.slurm.Cancel(ctr.UUID)
294 log.Printf("scancel: %s", err)
295 time.Sleep(time.Second)
296 } else if disp.sqCheck.HasUUID(ctr.UUID) {
297 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
298 time.Sleep(time.Second)