Merge branch '20511-aborted-boot'
[arvados.git] / lib / dispatchcloud / scheduler / run_queue.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package scheduler
6
7 import (
8         "sort"
9         "time"
10
11         "git.arvados.org/arvados.git/lib/dispatchcloud/container"
12         "git.arvados.org/arvados.git/sdk/go/arvados"
13         "github.com/sirupsen/logrus"
14 )
15
16 var quietAfter503 = time.Minute
17
18 func (sch *Scheduler) runQueue() {
19         running := sch.pool.Running()
20         unalloc := sch.pool.Unallocated()
21
22         unsorted, _ := sch.queue.Entries()
23         sorted := make([]container.QueueEnt, 0, len(unsorted))
24         for _, ent := range unsorted {
25                 sorted = append(sorted, ent)
26         }
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.
36                         return irunning
37                 }
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.
49                         return ilocked
50                 } else if pi, pj := sorted[i].Container.Priority, sorted[j].Container.Priority; pi != pj {
51                         return pi > pj
52                 } else {
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)
59                 }
60         })
61
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.
67                 sch.last503time = t
68                 if newlimit := len(running) - 1; newlimit < 1 {
69                         sch.maxConcurrency = 1
70                 } else {
71                         sch.maxConcurrency = newlimit
72                 }
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.
76                 //
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
85                 }
86         }
87         if sch.last503time.IsZero() {
88                 sch.mLast503Time.Set(0)
89         } else {
90                 sch.mLast503Time.Set(float64(sch.last503time.Unix()))
91         }
92         sch.mMaxContainerConcurrency.Set(float64(sch.maxConcurrency))
93
94         sch.logger.WithFields(logrus.Fields{
95                 "Containers":     len(sorted),
96                 "Processes":      len(running),
97                 "maxConcurrency": sch.maxConcurrency,
98         }).Debug("runQueue")
99
100         dontstart := map[arvados.InstanceType]bool{}
101         var overquota []container.QueueEnt    // entries that are unmappable because of worker pool quota
102         var overmaxsuper []container.QueueEnt // unmappable because max supervisors (these are not included in overquota)
103         var containerAllocatedWorkerBootingCount int
104
105         // trying is #containers running + #containers we're trying to
106         // start. We stop trying to start more containers if this
107         // reaches the dynamic maxConcurrency limit.
108         trying := len(running)
109
110         supervisors := 0
111
112 tryrun:
113         for i, ent := range sorted {
114                 ctr, it := ent.Container, ent.InstanceType
115                 logger := sch.logger.WithFields(logrus.Fields{
116                         "ContainerUUID": ctr.UUID,
117                         "InstanceType":  it.Name,
118                 })
119                 if ctr.SchedulingParameters.Supervisor {
120                         supervisors += 1
121                         if sch.maxSupervisors > 0 && supervisors > sch.maxSupervisors {
122                                 overmaxsuper = append(overmaxsuper, sorted[i])
123                                 continue
124                         }
125                 }
126                 if _, running := running[ctr.UUID]; running || ctr.Priority < 1 {
127                         continue
128                 }
129                 switch ctr.State {
130                 case arvados.ContainerStateQueued:
131                         if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
132                                 logger.Tracef("not locking: already at maxConcurrency %d", sch.maxConcurrency)
133                                 continue
134                         }
135                         trying++
136                         if unalloc[it] < 1 && sch.pool.AtQuota() {
137                                 logger.Trace("not locking: AtQuota and no unalloc workers")
138                                 overquota = sorted[i:]
139                                 break tryrun
140                         }
141                         if sch.pool.KillContainer(ctr.UUID, "about to lock") {
142                                 logger.Info("not locking: crunch-run process from previous attempt has not exited")
143                                 continue
144                         }
145                         go sch.lockContainer(logger, ctr.UUID)
146                         unalloc[it]--
147                 case arvados.ContainerStateLocked:
148                         if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
149                                 logger.Tracef("not starting: already at maxConcurrency %d", sch.maxConcurrency)
150                                 continue
151                         }
152                         trying++
153                         if unalloc[it] > 0 {
154                                 unalloc[it]--
155                         } else if sch.pool.AtQuota() {
156                                 // Don't let lower-priority containers
157                                 // starve this one by using keeping
158                                 // idle workers alive on different
159                                 // instance types.
160                                 logger.Trace("overquota")
161                                 overquota = sorted[i:]
162                                 break tryrun
163                         } else if sch.pool.Create(it) {
164                                 // Success. (Note pool.Create works
165                                 // asynchronously and does its own
166                                 // logging about the eventual outcome,
167                                 // so we don't need to.)
168                                 logger.Info("creating new instance")
169                         } else {
170                                 // Failed despite not being at quota,
171                                 // e.g., cloud ops throttled.  TODO:
172                                 // avoid getting starved here if
173                                 // instances of a specific type always
174                                 // fail.
175                                 logger.Trace("pool declined to create new instance")
176                                 continue
177                         }
178
179                         if dontstart[it] {
180                                 // We already tried & failed to start
181                                 // a higher-priority container on the
182                                 // same instance type. Don't let this
183                                 // one sneak in ahead of it.
184                         } else if sch.pool.KillContainer(ctr.UUID, "about to start") {
185                                 logger.Info("not restarting yet: crunch-run process from previous attempt has not exited")
186                         } else if sch.pool.StartContainer(it, ctr) {
187                                 logger.Trace("StartContainer => true")
188                                 // Success.
189                         } else {
190                                 logger.Trace("StartContainer => false")
191                                 containerAllocatedWorkerBootingCount += 1
192                                 dontstart[it] = true
193                         }
194                 }
195         }
196
197         sch.mContainersAllocatedNotStarted.Set(float64(containerAllocatedWorkerBootingCount))
198         sch.mContainersNotAllocatedOverQuota.Set(float64(len(overquota) + len(overmaxsuper)))
199
200         if len(overquota)+len(overmaxsuper) > 0 {
201                 // Unlock any containers that are unmappable while
202                 // we're at quota (but if they have already been
203                 // scheduled and they're loading docker images etc.,
204                 // let them run).
205                 for _, ctr := range append(overmaxsuper, overquota...) {
206                         ctr := ctr.Container
207                         _, toolate := running[ctr.UUID]
208                         if ctr.State == arvados.ContainerStateLocked && !toolate {
209                                 logger := sch.logger.WithField("ContainerUUID", ctr.UUID)
210                                 logger.Info("unlock because pool capacity is used by higher priority containers")
211                                 err := sch.queue.Unlock(ctr.UUID)
212                                 if err != nil {
213                                         logger.WithError(err).Warn("error unlocking")
214                                 }
215                         }
216                 }
217         }
218         if len(overquota) > 0 {
219                 // Shut down idle workers that didn't get any
220                 // containers mapped onto them before we hit quota.
221                 for it, n := range unalloc {
222                         if n < 1 {
223                                 continue
224                         }
225                         sch.pool.Shutdown(it)
226                 }
227         }
228 }
229
230 // Lock the given container. Should be called in a new goroutine.
231 func (sch *Scheduler) lockContainer(logger logrus.FieldLogger, uuid string) {
232         if !sch.uuidLock(uuid, "lock") {
233                 return
234         }
235         defer sch.uuidUnlock(uuid)
236         if ctr, ok := sch.queue.Get(uuid); !ok || ctr.State != arvados.ContainerStateQueued {
237                 // This happens if the container has been cancelled or
238                 // locked since runQueue called sch.queue.Entries(),
239                 // possibly by a lockContainer() call from a previous
240                 // runQueue iteration. In any case, we will respond
241                 // appropriately on the next runQueue iteration, which
242                 // will have already been triggered by the queue
243                 // update.
244                 logger.WithField("State", ctr.State).Debug("container no longer queued by the time we decided to lock it, doing nothing")
245                 return
246         }
247         err := sch.queue.Lock(uuid)
248         if err != nil {
249                 logger.WithError(err).Warn("error locking container")
250                 return
251         }
252         logger.Debug("lock succeeded")
253         ctr, ok := sch.queue.Get(uuid)
254         if !ok {
255                 logger.Error("(BUG?) container disappeared from queue after Lock succeeded")
256         } else if ctr.State != arvados.ContainerStateLocked {
257                 logger.Warnf("(race?) container has state=%q after Lock succeeded", ctr.State)
258         }
259 }
260
261 // Acquire a non-blocking lock for specified UUID, returning true if
262 // successful.  The op argument is used only for debug logs.
263 //
264 // If the lock is not available, uuidLock arranges to wake up the
265 // scheduler after a short delay, so it can retry whatever operation
266 // is trying to get the lock (if that operation is still worth doing).
267 //
268 // This mechanism helps avoid spamming the controller/database with
269 // concurrent updates for any single container, even when the
270 // scheduler loop is running frequently.
271 func (sch *Scheduler) uuidLock(uuid, op string) bool {
272         sch.mtx.Lock()
273         defer sch.mtx.Unlock()
274         logger := sch.logger.WithFields(logrus.Fields{
275                 "ContainerUUID": uuid,
276                 "Op":            op,
277         })
278         if op, locked := sch.uuidOp[uuid]; locked {
279                 logger.Debugf("uuidLock not available, Op=%s in progress", op)
280                 // Make sure the scheduler loop wakes up to retry.
281                 sch.wakeup.Reset(time.Second / 4)
282                 return false
283         }
284         logger.Debug("uuidLock acquired")
285         sch.uuidOp[uuid] = op
286         return true
287 }
288
289 func (sch *Scheduler) uuidUnlock(uuid string) {
290         sch.mtx.Lock()
291         defer sch.mtx.Unlock()
292         delete(sch.uuidOp, uuid)
293 }