1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
11 "git.arvados.org/arvados.git/lib/dispatchcloud/container"
12 "git.arvados.org/arvados.git/sdk/go/arvados"
13 "github.com/sirupsen/logrus"
16 var quietAfter503 = time.Minute
18 func (sch *Scheduler) runQueue() {
19 running := sch.pool.Running()
20 unalloc := sch.pool.Unallocated()
23 for _, n := range sch.pool.CountWorkers() {
27 unsorted, _ := sch.queue.Entries()
28 sorted := make([]container.QueueEnt, 0, len(unsorted))
29 for _, ent := range unsorted {
30 sorted = append(sorted, ent)
32 sort.Slice(sorted, func(i, j int) bool {
33 _, irunning := running[sorted[i].Container.UUID]
34 _, jrunning := running[sorted[j].Container.UUID]
35 if irunning != jrunning {
36 // Ensure the "tryrun" loop (see below) sees
37 // already-scheduled containers first, to
38 // ensure existing supervisor containers are
39 // properly counted before we decide whether
40 // we have room for new ones.
43 ilocked := sorted[i].Container.State == arvados.ContainerStateLocked
44 jlocked := sorted[j].Container.State == arvados.ContainerStateLocked
45 if ilocked != jlocked {
46 // Give precedence to containers that we have
47 // already locked, even if higher-priority
48 // containers have since arrived in the
49 // queue. This avoids undesirable queue churn
50 // effects including extra lock/unlock cycles
51 // and bringing up new instances and quickly
52 // shutting them down to make room for
53 // different instance sizes.
55 } else if pi, pj := sorted[i].Container.Priority, sorted[j].Container.Priority; pi != pj {
58 // When containers have identical priority,
59 // start them in the order we first noticed
60 // them. This avoids extra lock/unlock cycles
61 // when we unlock the containers that don't
62 // fit in the available pool.
63 return sorted[i].FirstSeenAt.Before(sorted[j].FirstSeenAt)
67 if t := sch.client.Last503(); t.After(sch.last503time) {
68 // API has sent an HTTP 503 response since last time
69 // we checked. Use current #containers - 1 as
70 // maxConcurrency, i.e., try to stay just below the
71 // level where we see 503s.
73 if newlimit := len(running) - 1; newlimit < 1 {
74 sch.maxConcurrency = 1
76 sch.maxConcurrency = newlimit
78 } else if sch.maxConcurrency > 0 && time.Since(sch.last503time) > quietAfter503 {
79 // If we haven't seen any 503 errors lately, raise
80 // limit to ~10% beyond the current workload.
82 // As we use the added 10% to schedule more
83 // containers, len(running) will increase and we'll
84 // push the limit up further. Soon enough,
85 // maxConcurrency will get high enough to schedule the
86 // entire queue, hit pool quota, or get 503s again.
87 max := len(running)*11/10 + 1
88 if sch.maxConcurrency < max {
89 sch.maxConcurrency = max
92 if sch.last503time.IsZero() {
93 sch.mLast503Time.Set(0)
95 sch.mLast503Time.Set(float64(sch.last503time.Unix()))
97 if sch.maxInstances > 0 && sch.maxConcurrency > sch.maxInstances {
98 sch.maxConcurrency = sch.maxInstances
100 if sch.instancesWithinQuota > 0 && sch.instancesWithinQuota < totalInstances {
101 // Evidently it is possible to run this many
102 // instances, so raise our estimate.
103 sch.instancesWithinQuota = totalInstances
105 if sch.pool.AtQuota() {
106 // Consider current workload to be the maximum
107 // allowed, for the sake of reporting metrics and
108 // calculating max supervisors.
110 // Now that sch.maxConcurrency is set, we will only
111 // raise it past len(running) by 10%. This helps
112 // avoid running an inappropriate number of
113 // supervisors when we reach the cloud-imposed quota
114 // (which may be based on # CPUs etc) long before the
115 // configured MaxInstances.
116 if sch.maxConcurrency == 0 || sch.maxConcurrency > totalInstances {
117 if totalInstances == 0 {
118 sch.maxConcurrency = 1
120 sch.maxConcurrency = totalInstances
123 sch.instancesWithinQuota = totalInstances
124 } else if sch.instancesWithinQuota > 0 && sch.maxConcurrency > sch.instancesWithinQuota+1 {
125 // Once we've hit a quota error and started tracking
126 // instancesWithinQuota (i.e., it's not zero), we
127 // avoid exceeding that known-working level by more
130 // If we don't do this, we risk entering a pattern of
131 // repeatedly locking several containers, hitting
132 // quota again, and unlocking them again each time the
133 // driver stops reporting AtQuota, which tends to use
134 // up the max lock/unlock cycles on the next few
135 // containers in the queue, and cause them to fail.
136 sch.maxConcurrency = sch.instancesWithinQuota + 1
138 sch.mMaxContainerConcurrency.Set(float64(sch.maxConcurrency))
140 maxSupervisors := int(float64(sch.maxConcurrency) * sch.supervisorFraction)
141 if maxSupervisors < 1 && sch.supervisorFraction > 0 && sch.maxConcurrency > 0 {
145 sch.logger.WithFields(logrus.Fields{
146 "Containers": len(sorted),
147 "Processes": len(running),
148 "maxConcurrency": sch.maxConcurrency,
151 dontstart := map[arvados.InstanceType]bool{}
152 var overquota []container.QueueEnt // entries that are unmappable because of worker pool quota
153 var overmaxsuper []container.QueueEnt // unmappable because max supervisors (these are not included in overquota)
154 var containerAllocatedWorkerBootingCount int
156 // trying is #containers running + #containers we're trying to
157 // start. We stop trying to start more containers if this
158 // reaches the dynamic maxConcurrency limit.
159 trying := len(running)
164 for i, ent := range sorted {
165 ctr, it := ent.Container, ent.InstanceType
166 logger := sch.logger.WithFields(logrus.Fields{
167 "ContainerUUID": ctr.UUID,
168 "InstanceType": it.Name,
170 if ctr.SchedulingParameters.Supervisor {
172 if maxSupervisors > 0 && supervisors > maxSupervisors {
173 overmaxsuper = append(overmaxsuper, sorted[i])
177 if _, running := running[ctr.UUID]; running || ctr.Priority < 1 {
181 case arvados.ContainerStateQueued:
182 if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
183 logger.Tracef("not locking: already at maxConcurrency %d", sch.maxConcurrency)
187 if unalloc[it] < 1 && sch.pool.AtQuota() {
188 logger.Trace("not locking: AtQuota and no unalloc workers")
189 overquota = sorted[i:]
192 if sch.pool.KillContainer(ctr.UUID, "about to lock") {
193 logger.Info("not locking: crunch-run process from previous attempt has not exited")
196 go sch.lockContainer(logger, ctr.UUID)
198 case arvados.ContainerStateLocked:
199 if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
200 logger.Tracef("not starting: already at maxConcurrency %d", sch.maxConcurrency)
206 } else if sch.pool.AtQuota() {
207 // Don't let lower-priority containers
208 // starve this one by using keeping
209 // idle workers alive on different
211 logger.Trace("overquota")
212 overquota = sorted[i:]
214 } else if sch.pool.Create(it) {
215 // Success. (Note pool.Create works
216 // asynchronously and does its own
217 // logging about the eventual outcome,
218 // so we don't need to.)
219 logger.Info("creating new instance")
221 // Failed despite not being at quota,
222 // e.g., cloud ops throttled. TODO:
223 // avoid getting starved here if
224 // instances of a specific type always
226 logger.Trace("pool declined to create new instance")
231 // We already tried & failed to start
232 // a higher-priority container on the
233 // same instance type. Don't let this
234 // one sneak in ahead of it.
235 } else if sch.pool.KillContainer(ctr.UUID, "about to start") {
236 logger.Info("not restarting yet: crunch-run process from previous attempt has not exited")
237 } else if sch.pool.StartContainer(it, ctr) {
238 logger.Trace("StartContainer => true")
241 logger.Trace("StartContainer => false")
242 containerAllocatedWorkerBootingCount += 1
248 sch.mContainersAllocatedNotStarted.Set(float64(containerAllocatedWorkerBootingCount))
249 sch.mContainersNotAllocatedOverQuota.Set(float64(len(overquota) + len(overmaxsuper)))
251 if len(overquota)+len(overmaxsuper) > 0 {
252 // Unlock any containers that are unmappable while
253 // we're at quota (but if they have already been
254 // scheduled and they're loading docker images etc.,
256 var unlock []container.QueueEnt
257 unlock = append(unlock, overmaxsuper...)
258 if totalInstances > 0 && len(overquota) > 1 {
259 // We don't unlock the next-in-line container
260 // when at quota. This avoids a situation
261 // where our "at quota" state expires, we lock
262 // the next container and try to create an
263 // instance, the cloud provider still returns
264 // a quota error, we unlock the container, and
265 // we repeat this until the container reaches
266 // its limit of lock/unlock cycles.
267 unlock = append(unlock, overquota[1:]...)
269 // However, if totalInstances is 0 and we're
270 // still getting quota errors, then the
271 // next-in-line container is evidently not
272 // possible to run, so we should let it
273 // exhaust its lock/unlock cycles and
274 // eventually cancel, to avoid starvation.
275 unlock = append(unlock, overquota...)
277 for _, ctr := range unlock {
279 _, toolate := running[ctr.UUID]
280 if ctr.State == arvados.ContainerStateLocked && !toolate {
281 logger := sch.logger.WithField("ContainerUUID", ctr.UUID)
282 logger.Info("unlock because pool capacity is used by higher priority containers")
283 err := sch.queue.Unlock(ctr.UUID)
285 logger.WithError(err).Warn("error unlocking")
290 if len(overquota) > 0 {
291 // Shut down idle workers that didn't get any
292 // containers mapped onto them before we hit quota.
293 for it, n := range unalloc {
297 sch.pool.Shutdown(it)
302 // Lock the given container. Should be called in a new goroutine.
303 func (sch *Scheduler) lockContainer(logger logrus.FieldLogger, uuid string) {
304 if !sch.uuidLock(uuid, "lock") {
307 defer sch.uuidUnlock(uuid)
308 if ctr, ok := sch.queue.Get(uuid); !ok || ctr.State != arvados.ContainerStateQueued {
309 // This happens if the container has been cancelled or
310 // locked since runQueue called sch.queue.Entries(),
311 // possibly by a lockContainer() call from a previous
312 // runQueue iteration. In any case, we will respond
313 // appropriately on the next runQueue iteration, which
314 // will have already been triggered by the queue
316 logger.WithField("State", ctr.State).Debug("container no longer queued by the time we decided to lock it, doing nothing")
319 err := sch.queue.Lock(uuid)
321 logger.WithError(err).Warn("error locking container")
324 logger.Debug("lock succeeded")
325 ctr, ok := sch.queue.Get(uuid)
327 logger.Error("(BUG?) container disappeared from queue after Lock succeeded")
328 } else if ctr.State != arvados.ContainerStateLocked {
329 logger.Warnf("(race?) container has state=%q after Lock succeeded", ctr.State)
333 // Acquire a non-blocking lock for specified UUID, returning true if
334 // successful. The op argument is used only for debug logs.
336 // If the lock is not available, uuidLock arranges to wake up the
337 // scheduler after a short delay, so it can retry whatever operation
338 // is trying to get the lock (if that operation is still worth doing).
340 // This mechanism helps avoid spamming the controller/database with
341 // concurrent updates for any single container, even when the
342 // scheduler loop is running frequently.
343 func (sch *Scheduler) uuidLock(uuid, op string) bool {
345 defer sch.mtx.Unlock()
346 logger := sch.logger.WithFields(logrus.Fields{
347 "ContainerUUID": uuid,
350 if op, locked := sch.uuidOp[uuid]; locked {
351 logger.Debugf("uuidLock not available, Op=%s in progress", op)
352 // Make sure the scheduler loop wakes up to retry.
353 sch.wakeup.Reset(time.Second / 4)
356 logger.Debug("uuidLock acquired")
357 sch.uuidOp[uuid] = op
361 func (sch *Scheduler) uuidUnlock(uuid string) {
363 defer sch.mtx.Unlock()
364 delete(sch.uuidOp, uuid)