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 func (sch *Scheduler) runQueue() {
17 unsorted, _ := sch.queue.Entries()
18 sorted := make([]container.QueueEnt, 0, len(unsorted))
19 for _, ent := range unsorted {
20 sorted = append(sorted, ent)
22 sort.Slice(sorted, func(i, j int) bool {
23 if pi, pj := sorted[i].Container.Priority, sorted[j].Container.Priority; pi != pj {
26 // When containers have identical priority,
27 // start them in the order we first noticed
28 // them. This avoids extra lock/unlock cycles
29 // when we unlock the containers that don't
30 // fit in the available pool.
31 return sorted[i].FirstSeenAt.Before(sorted[j].FirstSeenAt)
35 running := sch.pool.Running()
36 unalloc := sch.pool.Unallocated()
38 sch.logger.WithFields(logrus.Fields{
39 "Containers": len(sorted),
40 "Processes": len(running),
43 dontstart := map[arvados.InstanceType]bool{}
44 var overquota []container.QueueEnt // entries that are unmappable because of worker pool quota
45 var containerAllocatedWorkerBootingCount int
48 for i, ctr := range sorted {
49 ctr, it := ctr.Container, ctr.InstanceType
50 logger := sch.logger.WithFields(logrus.Fields{
51 "ContainerUUID": ctr.UUID,
52 "InstanceType": it.Name,
54 if _, running := running[ctr.UUID]; running || ctr.Priority < 1 {
58 case arvados.ContainerStateQueued:
59 if unalloc[it] < 1 && sch.pool.AtQuota() {
60 logger.Debug("not locking: AtQuota and no unalloc workers")
61 overquota = sorted[i:]
64 if sch.pool.KillContainer(ctr.UUID, "about to lock") {
65 logger.Info("not locking: crunch-run process from previous attempt has not exited")
68 go sch.lockContainer(logger, ctr.UUID)
70 case arvados.ContainerStateLocked:
73 } else if sch.pool.AtQuota() {
74 // Don't let lower-priority containers
75 // starve this one by using keeping
76 // idle workers alive on different
78 logger.Debug("overquota")
79 overquota = sorted[i:]
81 } else if logger.Info("creating new instance"); sch.pool.Create(it) {
82 // Success. (Note pool.Create works
83 // asynchronously and does its own
84 // logging, so we don't need to.)
86 // Failed despite not being at quota,
87 // e.g., cloud ops throttled. TODO:
88 // avoid getting starved here if
89 // instances of a specific type always
95 // We already tried & failed to start
96 // a higher-priority container on the
97 // same instance type. Don't let this
98 // one sneak in ahead of it.
99 } else if sch.pool.KillContainer(ctr.UUID, "about to start") {
100 logger.Info("not restarting yet: crunch-run process from previous attempt has not exited")
101 } else if sch.pool.StartContainer(it, ctr) {
104 containerAllocatedWorkerBootingCount += 1
110 sch.mContainersAllocatedNotStarted.Set(float64(containerAllocatedWorkerBootingCount))
111 sch.mContainersNotAllocatedOverQuota.Set(float64(len(overquota)))
113 if len(overquota) > 0 {
114 // Unlock any containers that are unmappable while
116 for _, ctr := range overquota {
118 if ctr.State == arvados.ContainerStateLocked {
119 logger := sch.logger.WithField("ContainerUUID", ctr.UUID)
120 logger.Debug("unlock because pool capacity is used by higher priority containers")
121 err := sch.queue.Unlock(ctr.UUID)
123 logger.WithError(err).Warn("error unlocking")
127 // Shut down idle workers that didn't get any
128 // containers mapped onto them before we hit quota.
129 for it, n := range unalloc {
133 sch.pool.Shutdown(it)
138 // Lock the given container. Should be called in a new goroutine.
139 func (sch *Scheduler) lockContainer(logger logrus.FieldLogger, uuid string) {
140 if !sch.uuidLock(uuid, "lock") {
143 defer sch.uuidUnlock(uuid)
144 if ctr, ok := sch.queue.Get(uuid); !ok || ctr.State != arvados.ContainerStateQueued {
145 // This happens if the container has been cancelled or
146 // locked since runQueue called sch.queue.Entries(),
147 // possibly by a lockContainer() call from a previous
148 // runQueue iteration. In any case, we will respond
149 // appropriately on the next runQueue iteration, which
150 // will have already been triggered by the queue
152 logger.WithField("State", ctr.State).Debug("container no longer queued by the time we decided to lock it, doing nothing")
155 err := sch.queue.Lock(uuid)
157 logger.WithError(err).Warn("error locking container")
160 logger.Debug("lock succeeded")
161 ctr, ok := sch.queue.Get(uuid)
163 logger.Error("(BUG?) container disappeared from queue after Lock succeeded")
164 } else if ctr.State != arvados.ContainerStateLocked {
165 logger.Warnf("(race?) container has state=%q after Lock succeeded", ctr.State)
169 // Acquire a non-blocking lock for specified UUID, returning true if
170 // successful. The op argument is used only for debug logs.
172 // If the lock is not available, uuidLock arranges to wake up the
173 // scheduler after a short delay, so it can retry whatever operation
174 // is trying to get the lock (if that operation is still worth doing).
176 // This mechanism helps avoid spamming the controller/database with
177 // concurrent updates for any single container, even when the
178 // scheduler loop is running frequently.
179 func (sch *Scheduler) uuidLock(uuid, op string) bool {
181 defer sch.mtx.Unlock()
182 logger := sch.logger.WithFields(logrus.Fields{
183 "ContainerUUID": uuid,
186 if op, locked := sch.uuidOp[uuid]; locked {
187 logger.Debugf("uuidLock not available, Op=%s in progress", op)
188 // Make sure the scheduler loop wakes up to retry.
189 sch.wakeup.Reset(time.Second / 4)
192 logger.Debug("uuidLock acquired")
193 sch.uuidOp[uuid] = op
197 func (sch *Scheduler) uuidUnlock(uuid string) {
199 defer sch.mtx.Unlock()
200 delete(sch.uuidOp, uuid)