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 return sorted[i].Container.Priority > sorted[j].Container.Priority
26 running := sch.pool.Running()
27 unalloc := sch.pool.Unallocated()
29 sch.logger.WithFields(logrus.Fields{
30 "Containers": len(sorted),
31 "Processes": len(running),
34 dontstart := map[arvados.InstanceType]bool{}
35 var overquota []container.QueueEnt // entries that are unmappable because of worker pool quota
36 var containerAllocatedWorkerBootingCount int
39 for i, ctr := range sorted {
40 ctr, it := ctr.Container, ctr.InstanceType
41 logger := sch.logger.WithFields(logrus.Fields{
42 "ContainerUUID": ctr.UUID,
43 "InstanceType": it.Name,
45 if _, running := running[ctr.UUID]; running || ctr.Priority < 1 {
49 case arvados.ContainerStateQueued:
50 if unalloc[it] < 1 && sch.pool.AtQuota() {
51 logger.Debug("not locking: AtQuota and no unalloc workers")
52 overquota = sorted[i:]
55 if sch.pool.KillContainer(ctr.UUID, "about to lock") {
56 logger.Info("not locking: crunch-run process from previous attempt has not exited")
59 go sch.lockContainer(logger, ctr.UUID)
61 case arvados.ContainerStateLocked:
64 } else if sch.pool.AtQuota() {
65 // Don't let lower-priority containers
66 // starve this one by using keeping
67 // idle workers alive on different
69 logger.Debug("unlocking: AtQuota and no unalloc workers")
70 sch.queue.Unlock(ctr.UUID)
71 overquota = sorted[i:]
73 } else if logger.Info("creating new instance"); sch.pool.Create(it) {
74 // Success. (Note pool.Create works
75 // asynchronously and does its own
76 // logging, so we don't need to.)
78 // Failed despite not being at quota,
79 // e.g., cloud ops throttled. TODO:
80 // avoid getting starved here if
81 // instances of a specific type always
87 // We already tried & failed to start
88 // a higher-priority container on the
89 // same instance type. Don't let this
90 // one sneak in ahead of it.
91 } else if sch.pool.KillContainer(ctr.UUID, "about to start") {
92 logger.Info("not restarting yet: crunch-run process from previous attempt has not exited")
93 } else if sch.pool.StartContainer(it, ctr) {
96 containerAllocatedWorkerBootingCount += 1
102 sch.mContainersAllocatedNotStarted.Set(float64(containerAllocatedWorkerBootingCount))
103 sch.mContainersNotAllocatedOverQuota.Set(float64(len(overquota)))
105 if len(overquota) > 0 {
106 // Unlock any containers that are unmappable while
108 for _, ctr := range overquota {
110 if ctr.State == arvados.ContainerStateLocked {
111 logger := sch.logger.WithField("ContainerUUID", ctr.UUID)
112 logger.Debug("unlock because pool capacity is used by higher priority containers")
113 err := sch.queue.Unlock(ctr.UUID)
115 logger.WithError(err).Warn("error unlocking")
119 // Shut down idle workers that didn't get any
120 // containers mapped onto them before we hit quota.
121 for it, n := range unalloc {
125 sch.pool.Shutdown(it)
130 // Lock the given container. Should be called in a new goroutine.
131 func (sch *Scheduler) lockContainer(logger logrus.FieldLogger, uuid string) {
132 if !sch.uuidLock(uuid, "lock") {
135 defer sch.uuidUnlock(uuid)
136 if ctr, ok := sch.queue.Get(uuid); !ok || ctr.State != arvados.ContainerStateQueued {
137 // This happens if the container has been cancelled or
138 // locked since runQueue called sch.queue.Entries(),
139 // possibly by a lockContainer() call from a previous
140 // runQueue iteration. In any case, we will respond
141 // appropriately on the next runQueue iteration, which
142 // will have already been triggered by the queue
144 logger.WithField("State", ctr.State).Debug("container no longer queued by the time we decided to lock it, doing nothing")
147 err := sch.queue.Lock(uuid)
149 logger.WithError(err).Warn("error locking container")
152 logger.Debug("lock succeeded")
153 ctr, ok := sch.queue.Get(uuid)
155 logger.Error("(BUG?) container disappeared from queue after Lock succeeded")
156 } else if ctr.State != arvados.ContainerStateLocked {
157 logger.Warnf("(race?) container has state=%q after Lock succeeded", ctr.State)
161 // Acquire a non-blocking lock for specified UUID, returning true if
162 // successful. The op argument is used only for debug logs.
164 // If the lock is not available, uuidLock arranges to wake up the
165 // scheduler after a short delay, so it can retry whatever operation
166 // is trying to get the lock (if that operation is still worth doing).
168 // This mechanism helps avoid spamming the controller/database with
169 // concurrent updates for any single container, even when the
170 // scheduler loop is running frequently.
171 func (sch *Scheduler) uuidLock(uuid, op string) bool {
173 defer sch.mtx.Unlock()
174 logger := sch.logger.WithFields(logrus.Fields{
175 "ContainerUUID": uuid,
178 if op, locked := sch.uuidOp[uuid]; locked {
179 logger.Debugf("uuidLock not available, Op=%s in progress", op)
180 // Make sure the scheduler loop wakes up to retry.
181 sch.wakeup.Reset(time.Second / 4)
184 logger.Debug("uuidLock acquired")
185 sch.uuidOp[uuid] = op
189 func (sch *Scheduler) uuidUnlock(uuid string) {
191 defer sch.mtx.Unlock()
192 delete(sch.uuidOp, uuid)