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()
22 unsorted, _ := sch.queue.Entries()
23 sorted := make([]container.QueueEnt, 0, len(unsorted))
24 for _, ent := range unsorted {
25 sorted = append(sorted, ent)
27 sort.Slice(sorted, func(i, j int) bool {
28 _, irunning := running[sorted[i].Container.UUID]
29 _, jrunning := running[sorted[j].Container.UUID]
30 if irunning != jrunning {
31 // Ensure the "tryrun" loop (see below) sees
32 // already-scheduled containers first, to
33 // ensure existing supervisor containers are
34 // properly counted before we decide whether
35 // we have room for new ones.
38 ilocked := sorted[i].Container.State == arvados.ContainerStateLocked
39 jlocked := sorted[j].Container.State == arvados.ContainerStateLocked
40 if ilocked != jlocked {
41 // Give precedence to containers that we have
42 // already locked, even if higher-priority
43 // containers have since arrived in the
44 // queue. This avoids undesirable queue churn
45 // effects including extra lock/unlock cycles
46 // and bringing up new instances and quickly
47 // shutting them down to make room for
48 // different instance sizes.
50 } else if pi, pj := sorted[i].Container.Priority, sorted[j].Container.Priority; pi != pj {
53 // When containers have identical priority,
54 // start them in the order we first noticed
55 // them. This avoids extra lock/unlock cycles
56 // when we unlock the containers that don't
57 // fit in the available pool.
58 return sorted[i].FirstSeenAt.Before(sorted[j].FirstSeenAt)
62 if t := sch.client.Last503(); t.After(sch.last503time) {
63 // API has sent an HTTP 503 response since last time
64 // we checked. Use current #containers - 1 as
65 // maxConcurrency, i.e., try to stay just below the
66 // level where we see 503s.
68 if newlimit := len(running) - 1; newlimit < 1 {
69 sch.maxConcurrency = 1
71 sch.maxConcurrency = newlimit
73 } else if sch.maxConcurrency > 0 && time.Since(sch.last503time) > quietAfter503 {
74 // If we haven't seen any 503 errors lately, raise
75 // limit to ~10% beyond the current workload.
77 // As we use the added 10% to schedule more
78 // containers, len(running) will increase and we'll
79 // push the limit up further. Soon enough,
80 // maxConcurrency will get high enough to schedule the
81 // entire queue, hit pool quota, or get 503s again.
82 max := len(running)*11/10 + 1
83 if sch.maxConcurrency < max {
84 sch.maxConcurrency = max
87 if sch.last503time.IsZero() {
88 sch.mLast503Time.Set(0)
90 sch.mLast503Time.Set(float64(sch.last503time.Unix()))
92 if sch.maxInstances > 0 && sch.maxConcurrency > sch.maxInstances {
93 sch.maxConcurrency = sch.maxInstances
95 sch.mMaxContainerConcurrency.Set(float64(sch.maxConcurrency))
97 maxSupervisors := int(float64(sch.maxConcurrency) * sch.supervisorFraction)
98 if maxSupervisors < 1 && sch.supervisorFraction > 0 && sch.maxConcurrency > 0 {
102 sch.logger.WithFields(logrus.Fields{
103 "Containers": len(sorted),
104 "Processes": len(running),
105 "maxConcurrency": sch.maxConcurrency,
108 dontstart := map[arvados.InstanceType]bool{}
109 var overquota []container.QueueEnt // entries that are unmappable because of worker pool quota
110 var overmaxsuper []container.QueueEnt // unmappable because max supervisors (these are not included in overquota)
111 var containerAllocatedWorkerBootingCount int
113 // trying is #containers running + #containers we're trying to
114 // start. We stop trying to start more containers if this
115 // reaches the dynamic maxConcurrency limit.
116 trying := len(running)
121 for i, ent := range sorted {
122 ctr, it := ent.Container, ent.InstanceType
123 logger := sch.logger.WithFields(logrus.Fields{
124 "ContainerUUID": ctr.UUID,
125 "InstanceType": it.Name,
127 if ctr.SchedulingParameters.Supervisor {
129 if maxSupervisors > 0 && supervisors > maxSupervisors {
130 overmaxsuper = append(overmaxsuper, sorted[i])
134 if _, running := running[ctr.UUID]; running || ctr.Priority < 1 {
138 case arvados.ContainerStateQueued:
139 if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
140 logger.Tracef("not locking: already at maxConcurrency %d", sch.maxConcurrency)
144 if unalloc[it] < 1 && sch.pool.AtQuota() {
145 logger.Trace("not locking: AtQuota and no unalloc workers")
146 overquota = sorted[i:]
149 if sch.pool.KillContainer(ctr.UUID, "about to lock") {
150 logger.Info("not locking: crunch-run process from previous attempt has not exited")
153 go sch.lockContainer(logger, ctr.UUID)
155 case arvados.ContainerStateLocked:
156 if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
157 logger.Tracef("not starting: already at maxConcurrency %d", sch.maxConcurrency)
163 } else if sch.pool.AtQuota() {
164 // Don't let lower-priority containers
165 // starve this one by using keeping
166 // idle workers alive on different
168 logger.Trace("overquota")
169 overquota = sorted[i:]
171 } else if sch.pool.Create(it) {
172 // Success. (Note pool.Create works
173 // asynchronously and does its own
174 // logging about the eventual outcome,
175 // so we don't need to.)
176 logger.Info("creating new instance")
178 // Failed despite not being at quota,
179 // e.g., cloud ops throttled. TODO:
180 // avoid getting starved here if
181 // instances of a specific type always
183 logger.Trace("pool declined to create new instance")
188 // We already tried & failed to start
189 // a higher-priority container on the
190 // same instance type. Don't let this
191 // one sneak in ahead of it.
192 } else if sch.pool.KillContainer(ctr.UUID, "about to start") {
193 logger.Info("not restarting yet: crunch-run process from previous attempt has not exited")
194 } else if sch.pool.StartContainer(it, ctr) {
195 logger.Trace("StartContainer => true")
198 logger.Trace("StartContainer => false")
199 containerAllocatedWorkerBootingCount += 1
205 sch.mContainersAllocatedNotStarted.Set(float64(containerAllocatedWorkerBootingCount))
206 sch.mContainersNotAllocatedOverQuota.Set(float64(len(overquota) + len(overmaxsuper)))
208 if len(overquota)+len(overmaxsuper) > 0 {
209 // Unlock any containers that are unmappable while
210 // we're at quota (but if they have already been
211 // scheduled and they're loading docker images etc.,
213 for _, ctr := range append(overmaxsuper, overquota...) {
215 _, toolate := running[ctr.UUID]
216 if ctr.State == arvados.ContainerStateLocked && !toolate {
217 logger := sch.logger.WithField("ContainerUUID", ctr.UUID)
218 logger.Info("unlock because pool capacity is used by higher priority containers")
219 err := sch.queue.Unlock(ctr.UUID)
221 logger.WithError(err).Warn("error unlocking")
226 if len(overquota) > 0 {
227 // Shut down idle workers that didn't get any
228 // containers mapped onto them before we hit quota.
229 for it, n := range unalloc {
233 sch.pool.Shutdown(it)
238 // Lock the given container. Should be called in a new goroutine.
239 func (sch *Scheduler) lockContainer(logger logrus.FieldLogger, uuid string) {
240 if !sch.uuidLock(uuid, "lock") {
243 defer sch.uuidUnlock(uuid)
244 if ctr, ok := sch.queue.Get(uuid); !ok || ctr.State != arvados.ContainerStateQueued {
245 // This happens if the container has been cancelled or
246 // locked since runQueue called sch.queue.Entries(),
247 // possibly by a lockContainer() call from a previous
248 // runQueue iteration. In any case, we will respond
249 // appropriately on the next runQueue iteration, which
250 // will have already been triggered by the queue
252 logger.WithField("State", ctr.State).Debug("container no longer queued by the time we decided to lock it, doing nothing")
255 err := sch.queue.Lock(uuid)
257 logger.WithError(err).Warn("error locking container")
260 logger.Debug("lock succeeded")
261 ctr, ok := sch.queue.Get(uuid)
263 logger.Error("(BUG?) container disappeared from queue after Lock succeeded")
264 } else if ctr.State != arvados.ContainerStateLocked {
265 logger.Warnf("(race?) container has state=%q after Lock succeeded", ctr.State)
269 // Acquire a non-blocking lock for specified UUID, returning true if
270 // successful. The op argument is used only for debug logs.
272 // If the lock is not available, uuidLock arranges to wake up the
273 // scheduler after a short delay, so it can retry whatever operation
274 // is trying to get the lock (if that operation is still worth doing).
276 // This mechanism helps avoid spamming the controller/database with
277 // concurrent updates for any single container, even when the
278 // scheduler loop is running frequently.
279 func (sch *Scheduler) uuidLock(uuid, op string) bool {
281 defer sch.mtx.Unlock()
282 logger := sch.logger.WithFields(logrus.Fields{
283 "ContainerUUID": uuid,
286 if op, locked := sch.uuidOp[uuid]; locked {
287 logger.Debugf("uuidLock not available, Op=%s in progress", op)
288 // Make sure the scheduler loop wakes up to retry.
289 sch.wakeup.Reset(time.Second / 4)
292 logger.Debug("uuidLock acquired")
293 sch.uuidOp[uuid] = op
297 func (sch *Scheduler) uuidUnlock(uuid string) {
299 defer sch.mtx.Unlock()
300 delete(sch.uuidOp, uuid)