Merge branch '20457-careful-near-quota'
[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         totalInstances := 0
23         for _, n := range sch.pool.CountWorkers() {
24                 totalInstances += n
25         }
26
27         unsorted, _ := sch.queue.Entries()
28         sorted := make([]container.QueueEnt, 0, len(unsorted))
29         for _, ent := range unsorted {
30                 sorted = append(sorted, ent)
31         }
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.
41                         return irunning
42                 }
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.
54                         return ilocked
55                 } else if pi, pj := sorted[i].Container.Priority, sorted[j].Container.Priority; pi != pj {
56                         return pi > pj
57                 } else {
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)
64                 }
65         })
66
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.
72                 sch.last503time = t
73                 if newlimit := len(running) - 1; newlimit < 1 {
74                         sch.maxConcurrency = 1
75                 } else {
76                         sch.maxConcurrency = newlimit
77                 }
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.
81                 //
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
90                 }
91         }
92         if sch.last503time.IsZero() {
93                 sch.mLast503Time.Set(0)
94         } else {
95                 sch.mLast503Time.Set(float64(sch.last503time.Unix()))
96         }
97         if sch.maxInstances > 0 && sch.maxConcurrency > sch.maxInstances {
98                 sch.maxConcurrency = sch.maxInstances
99         }
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
104         }
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.
109                 //
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
119                         } else {
120                                 sch.maxConcurrency = totalInstances
121                         }
122                 }
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
128                 // than 1.
129                 //
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
137         }
138         sch.mMaxContainerConcurrency.Set(float64(sch.maxConcurrency))
139
140         maxSupervisors := int(float64(sch.maxConcurrency) * sch.supervisorFraction)
141         if maxSupervisors < 1 && sch.supervisorFraction > 0 && sch.maxConcurrency > 0 {
142                 maxSupervisors = 1
143         }
144
145         sch.logger.WithFields(logrus.Fields{
146                 "Containers":     len(sorted),
147                 "Processes":      len(running),
148                 "maxConcurrency": sch.maxConcurrency,
149         }).Debug("runQueue")
150
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
155
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)
160
161         supervisors := 0
162
163 tryrun:
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,
169                 })
170                 if ctr.SchedulingParameters.Supervisor {
171                         supervisors += 1
172                         if maxSupervisors > 0 && supervisors > maxSupervisors {
173                                 overmaxsuper = append(overmaxsuper, sorted[i])
174                                 continue
175                         }
176                 }
177                 if _, running := running[ctr.UUID]; running || ctr.Priority < 1 {
178                         continue
179                 }
180                 switch ctr.State {
181                 case arvados.ContainerStateQueued:
182                         if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
183                                 logger.Tracef("not locking: already at maxConcurrency %d", sch.maxConcurrency)
184                                 continue
185                         }
186                         trying++
187                         if unalloc[it] < 1 && sch.pool.AtQuota() {
188                                 logger.Trace("not locking: AtQuota and no unalloc workers")
189                                 overquota = sorted[i:]
190                                 break tryrun
191                         }
192                         if sch.pool.KillContainer(ctr.UUID, "about to lock") {
193                                 logger.Info("not locking: crunch-run process from previous attempt has not exited")
194                                 continue
195                         }
196                         go sch.lockContainer(logger, ctr.UUID)
197                         unalloc[it]--
198                 case arvados.ContainerStateLocked:
199                         if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
200                                 logger.Tracef("not starting: already at maxConcurrency %d", sch.maxConcurrency)
201                                 continue
202                         }
203                         trying++
204                         if unalloc[it] > 0 {
205                                 unalloc[it]--
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
210                                 // instance types.
211                                 logger.Trace("overquota")
212                                 overquota = sorted[i:]
213                                 break tryrun
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")
220                         } else {
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
225                                 // fail.
226                                 logger.Trace("pool declined to create new instance")
227                                 continue
228                         }
229
230                         if dontstart[it] {
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")
239                                 // Success.
240                         } else {
241                                 logger.Trace("StartContainer => false")
242                                 containerAllocatedWorkerBootingCount += 1
243                                 dontstart[it] = true
244                         }
245                 }
246         }
247
248         sch.mContainersAllocatedNotStarted.Set(float64(containerAllocatedWorkerBootingCount))
249         sch.mContainersNotAllocatedOverQuota.Set(float64(len(overquota) + len(overmaxsuper)))
250
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.,
255                 // let them run).
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:]...)
268                 } else {
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...)
276                 }
277                 for _, ctr := range unlock {
278                         ctr := ctr.Container
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)
284                                 if err != nil {
285                                         logger.WithError(err).Warn("error unlocking")
286                                 }
287                         }
288                 }
289         }
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 {
294                         if n < 1 {
295                                 continue
296                         }
297                         sch.pool.Shutdown(it)
298                 }
299         }
300 }
301
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") {
305                 return
306         }
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
315                 // update.
316                 logger.WithField("State", ctr.State).Debug("container no longer queued by the time we decided to lock it, doing nothing")
317                 return
318         }
319         err := sch.queue.Lock(uuid)
320         if err != nil {
321                 logger.WithError(err).Warn("error locking container")
322                 return
323         }
324         logger.Debug("lock succeeded")
325         ctr, ok := sch.queue.Get(uuid)
326         if !ok {
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)
330         }
331 }
332
333 // Acquire a non-blocking lock for specified UUID, returning true if
334 // successful.  The op argument is used only for debug logs.
335 //
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).
339 //
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 {
344         sch.mtx.Lock()
345         defer sch.mtx.Unlock()
346         logger := sch.logger.WithFields(logrus.Fields{
347                 "ContainerUUID": uuid,
348                 "Op":            op,
349         })
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)
354                 return false
355         }
356         logger.Debug("uuidLock acquired")
357         sch.uuidOp[uuid] = op
358         return true
359 }
360
361 func (sch *Scheduler) uuidUnlock(uuid string) {
362         sch.mtx.Lock()
363         defer sch.mtx.Unlock()
364         delete(sch.uuidOp, uuid)
365 }