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.
21 "git.arvados.org/arvados.git/lib/cmd"
22 "git.arvados.org/arvados.git/lib/dispatchcloud"
23 "git.arvados.org/arvados.git/lib/service"
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
26 "git.arvados.org/arvados.git/sdk/go/ctxlog"
27 "git.arvados.org/arvados.git/sdk/go/dispatch"
28 "github.com/coreos/go-systemd/daemon"
29 "github.com/prometheus/client_golang/prometheus"
30 "github.com/sirupsen/logrus"
33 var Command cmd.Handler = service.Command(arvados.ServiceNameDispatchSLURM, newHandler)
35 func newHandler(ctx context.Context, cluster *arvados.Cluster, _ string, _ *prometheus.Registry) service.Handler {
36 logger := ctxlog.FromContext(ctx)
37 disp := &Dispatcher{logger: logger, cluster: cluster}
38 if err := disp.configure(); err != nil {
39 return service.ErrorHandler(ctx, cluster, err)
49 type logger interface {
51 Fatalf(string, ...interface{})
54 const initialNiceValue int64 = 10000
56 type Dispatcher struct {
58 logger logrus.FieldLogger
59 cluster *arvados.Cluster
60 sqCheck *SqueueChecker
69 func (disp *Dispatcher) CheckHealth() error {
73 func (disp *Dispatcher) Done() <-chan struct{} {
77 func (disp *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
81 // configure() loads config files. Some tests skip this (see
83 func (disp *Dispatcher) configure() error {
84 if disp.logger == nil {
85 disp.logger = logrus.StandardLogger()
87 disp.logger = disp.logger.WithField("ClusterID", disp.cluster.ClusterID)
88 disp.logger.Printf("crunch-dispatch-slurm %s started", cmd.Version.String())
90 disp.Client.APIHost = disp.cluster.Services.Controller.ExternalURL.Host
91 disp.Client.AuthToken = disp.cluster.SystemRootToken
92 disp.Client.Insecure = disp.cluster.TLS.Insecure
94 if disp.Client.APIHost != "" || disp.Client.AuthToken != "" {
95 // Copy real configs into env vars so [a]
96 // MakeArvadosClient() uses them, and [b] they get
97 // propagated to crunch-run via SLURM.
98 os.Setenv("ARVADOS_API_HOST", disp.Client.APIHost)
99 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
100 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
101 if disp.Client.Insecure {
102 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
104 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
105 for k, v := range disp.cluster.Containers.SLURM.SbatchEnvironmentVariables {
109 disp.logger.Warnf("Client credentials missing from config, so falling back on environment variables (deprecated).")
114 // setup() initializes private fields after configure().
115 func (disp *Dispatcher) setup() {
116 disp.done = make(chan struct{})
117 arv, err := arvadosclient.MakeArvadosClient()
119 disp.logger.Fatalf("Error making Arvados client: %v", err)
123 disp.slurm = NewSlurmCLI()
124 disp.sqCheck = &SqueueChecker{
126 Period: time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
127 PrioritySpread: disp.cluster.Containers.SLURM.PrioritySpread,
130 disp.Dispatcher = &dispatch.Dispatcher{
133 BatchSize: disp.cluster.API.MaxItemsPerResponse,
134 RunContainer: disp.runContainer,
135 PollPeriod: time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
136 MinRetryPeriod: time.Duration(disp.cluster.Containers.MinRetryPeriod),
140 func (disp *Dispatcher) run() error {
141 defer disp.sqCheck.Stop()
143 if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
144 go SlurmNodeTypeFeatureKludge(disp.cluster)
147 if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
148 log.Printf("Error notifying init daemon: %v", err)
150 go disp.checkSqueueForOrphans()
151 return disp.Dispatcher.Run(context.Background())
154 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
156 // Check the next squeue report, and invoke TrackContainer for all the
157 // containers in the report. This gives us a chance to cancel slurm
158 // jobs started by a previous dispatch process that never released
159 // their slurm allocations even though their container states are
160 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
161 func (disp *Dispatcher) checkSqueueForOrphans() {
162 for _, uuid := range disp.sqCheck.All() {
163 if !containerUuidPattern.MatchString(uuid) || !strings.HasPrefix(uuid, disp.cluster.ClusterID) {
166 err := disp.TrackContainer(uuid)
168 log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
173 func (disp *Dispatcher) slurmConstraintArgs(container arvados.Container) []string {
174 mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+
175 container.RuntimeConstraints.KeepCacheRAM+
176 int64(disp.cluster.Containers.ReserveExtraRAM)) / float64(1048576)))
178 disk := dispatchcloud.EstimateScratchSpace(&container)
179 disk = int64(math.Ceil(float64(disk) / float64(1048576)))
181 fmt.Sprintf("--mem=%d", mem),
182 fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs),
183 fmt.Sprintf("--tmp=%d", disk),
187 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
189 args = append(args, disp.cluster.Containers.SLURM.SbatchArgumentsList...)
190 args = append(args, "--job-name="+container.UUID, fmt.Sprintf("--nice=%d", initialNiceValue), "--no-requeue")
192 if disp.cluster == nil {
193 // no instance types configured
194 args = append(args, disp.slurmConstraintArgs(container)...)
195 } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
197 args = append(args, disp.slurmConstraintArgs(container)...)
198 } else if err != nil {
201 // use instancetype constraint instead of slurm mem/cpu/tmp specs
202 args = append(args, "--constraint=instancetype="+it.Name)
205 if len(container.SchedulingParameters.Partitions) > 0 {
206 args = append(args, "--partition="+strings.Join(container.SchedulingParameters.Partitions, ","))
212 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
213 // append() here avoids modifying crunchRunCommand's
214 // underlying array, which is shared with other goroutines.
215 crArgs := append([]string(nil), crunchRunCommand...)
216 crArgs = append(crArgs, "--runtime-engine="+disp.cluster.Containers.RuntimeEngine)
217 crArgs = append(crArgs, container.UUID)
219 h := hmac.New(sha256.New, []byte(disp.cluster.SystemRootToken))
220 fmt.Fprint(h, container.UUID)
221 authsecret := fmt.Sprintf("%x", h.Sum(nil))
223 crScript := strings.NewReader(execScript(crArgs, map[string]string{"GatewayAuthSecret": authsecret}))
225 sbArgs, err := disp.sbatchArgs(container)
229 log.Printf("running sbatch %+q", sbArgs)
230 return disp.slurm.Batch(crScript, sbArgs)
233 // Submit a container to the slurm queue (or resume monitoring if it's
234 // already in the queue). Cancel the slurm job if the container's
235 // priority changes to zero or its state indicates it's no longer
237 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) error {
238 ctx, cancel := context.WithCancel(context.Background())
241 if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
242 log.Printf("Submitting container %s to slurm", ctr.UUID)
243 cmd := []string{disp.cluster.Containers.CrunchRunCommand}
244 cmd = append(cmd, disp.cluster.Containers.CrunchRunArgumentsList...)
245 err := disp.submit(ctr, cmd)
251 log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
252 defer log.Printf("Done monitoring container %s", ctr.UUID)
254 // If the container disappears from the slurm queue, there is
255 // no point in waiting for further dispatch updates: just
256 // clean up and return.
257 go func(uuid string) {
258 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
266 // Disappeared from squeue
267 if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
268 log.Printf("error getting final container state for %s: %s", ctr.UUID, err)
271 case dispatch.Running:
272 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
273 case dispatch.Locked:
274 disp.Unlock(ctr.UUID)
277 case updated, ok := <-status:
279 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
281 } else if updated.Priority == 0 {
282 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
285 p := int64(updated.Priority)
288 // user-assigned priority. If
289 // ctrs have equal priority,
290 // run the older one first.
291 p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
293 disp.sqCheck.SetPriority(ctr.UUID, p)
298 func (disp *Dispatcher) scancel(ctr arvados.Container) {
299 err := disp.slurm.Cancel(ctr.UUID)
301 log.Printf("scancel: %s", err)
302 time.Sleep(time.Second)
303 } else if disp.sqCheck.HasUUID(ctr.UUID) {
304 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
305 time.Sleep(time.Second)