19973: Add metrics for automatic container concurrency limit.
[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         unsorted, _ := sch.queue.Entries()
20         sorted := make([]container.QueueEnt, 0, len(unsorted))
21         for _, ent := range unsorted {
22                 sorted = append(sorted, ent)
23         }
24         sort.Slice(sorted, func(i, j int) bool {
25                 if pi, pj := sorted[i].Container.Priority, sorted[j].Container.Priority; pi != pj {
26                         return pi > pj
27                 } else {
28                         // When containers have identical priority,
29                         // start them in the order we first noticed
30                         // them. This avoids extra lock/unlock cycles
31                         // when we unlock the containers that don't
32                         // fit in the available pool.
33                         return sorted[i].FirstSeenAt.Before(sorted[j].FirstSeenAt)
34                 }
35         })
36
37         running := sch.pool.Running()
38         unalloc := sch.pool.Unallocated()
39
40         if t := sch.client.Last503(); t.After(sch.last503time) {
41                 // API has sent an HTTP 503 response since last time
42                 // we checked. Use current #containers - 1 as
43                 // maxConcurrency, i.e., try to stay just below the
44                 // level where we see 503s.
45                 sch.last503time = t
46                 if newlimit := len(running) - 1; newlimit < 1 {
47                         sch.maxConcurrency = 1
48                 } else {
49                         sch.maxConcurrency = newlimit
50                 }
51         } else if sch.maxConcurrency > 0 && time.Since(sch.last503time) > quietAfter503 {
52                 // If we haven't seen any 503 errors lately, raise
53                 // limit to ~10% beyond the current workload.
54                 //
55                 // As we use the added 10% to schedule more
56                 // containers, len(running) will increase and we'll
57                 // push the limit up further. Soon enough,
58                 // maxConcurrency will get high enough to schedule the
59                 // entire queue, hit pool quota, or get 503s again.
60                 max := len(running)*11/10 + 1
61                 if sch.maxConcurrency < max {
62                         sch.maxConcurrency = max
63                 }
64         }
65         sch.mLast503Time.Set(float64(sch.last503time.Unix()))
66         sch.mMaxContainerConcurrency.Set(float64(sch.maxConcurrency))
67
68         sch.logger.WithFields(logrus.Fields{
69                 "Containers":     len(sorted),
70                 "Processes":      len(running),
71                 "maxConcurrency": sch.maxConcurrency,
72         }).Debug("runQueue")
73
74         dontstart := map[arvados.InstanceType]bool{}
75         var overquota []container.QueueEnt // entries that are unmappable because of worker pool quota
76         var containerAllocatedWorkerBootingCount int
77
78         // trying is #containers running + #containers we're trying to
79         // start. We stop trying to start more containers if this
80         // reaches the dynamic maxConcurrency limit.
81         trying := len(running)
82
83 tryrun:
84         for i, ctr := range sorted {
85                 ctr, it := ctr.Container, ctr.InstanceType
86                 logger := sch.logger.WithFields(logrus.Fields{
87                         "ContainerUUID": ctr.UUID,
88                         "InstanceType":  it.Name,
89                 })
90                 if _, running := running[ctr.UUID]; running || ctr.Priority < 1 {
91                         continue
92                 }
93                 switch ctr.State {
94                 case arvados.ContainerStateQueued:
95                         if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
96                                 logger.Tracef("not locking: already at maxConcurrency %d", sch.maxConcurrency)
97                                 overquota = sorted[i:]
98                                 break tryrun
99                         }
100                         trying++
101                         if unalloc[it] < 1 && sch.pool.AtQuota() {
102                                 logger.Trace("not locking: AtQuota and no unalloc workers")
103                                 overquota = sorted[i:]
104                                 break tryrun
105                         }
106                         if sch.pool.KillContainer(ctr.UUID, "about to lock") {
107                                 logger.Info("not locking: crunch-run process from previous attempt has not exited")
108                                 continue
109                         }
110                         go sch.lockContainer(logger, ctr.UUID)
111                         unalloc[it]--
112                 case arvados.ContainerStateLocked:
113                         if sch.maxConcurrency > 0 && trying >= sch.maxConcurrency {
114                                 logger.Debugf("not starting: already at maxConcurrency %d", sch.maxConcurrency)
115                                 overquota = sorted[i:]
116                                 break tryrun
117                         }
118                         trying++
119                         if unalloc[it] > 0 {
120                                 unalloc[it]--
121                         } else if sch.pool.AtQuota() {
122                                 // Don't let lower-priority containers
123                                 // starve this one by using keeping
124                                 // idle workers alive on different
125                                 // instance types.
126                                 logger.Trace("overquota")
127                                 overquota = sorted[i:]
128                                 break tryrun
129                         } else if sch.pool.Create(it) {
130                                 // Success. (Note pool.Create works
131                                 // asynchronously and does its own
132                                 // logging about the eventual outcome,
133                                 // so we don't need to.)
134                                 logger.Info("creating new instance")
135                         } else {
136                                 // Failed despite not being at quota,
137                                 // e.g., cloud ops throttled.  TODO:
138                                 // avoid getting starved here if
139                                 // instances of a specific type always
140                                 // fail.
141                                 logger.Trace("pool declined to create new instance")
142                                 continue
143                         }
144
145                         if dontstart[it] {
146                                 // We already tried & failed to start
147                                 // a higher-priority container on the
148                                 // same instance type. Don't let this
149                                 // one sneak in ahead of it.
150                         } else if sch.pool.KillContainer(ctr.UUID, "about to start") {
151                                 logger.Info("not restarting yet: crunch-run process from previous attempt has not exited")
152                         } else if sch.pool.StartContainer(it, ctr) {
153                                 // Success.
154                         } else {
155                                 containerAllocatedWorkerBootingCount += 1
156                                 dontstart[it] = true
157                         }
158                 }
159         }
160
161         sch.mContainersAllocatedNotStarted.Set(float64(containerAllocatedWorkerBootingCount))
162         sch.mContainersNotAllocatedOverQuota.Set(float64(len(overquota)))
163
164         if len(overquota) > 0 {
165                 // Unlock any containers that are unmappable while
166                 // we're at quota (but if they have already been
167                 // scheduled and they're loading docker images etc.,
168                 // let them run).
169                 for _, ctr := range overquota {
170                         ctr := ctr.Container
171                         _, toolate := running[ctr.UUID]
172                         if ctr.State == arvados.ContainerStateLocked && !toolate {
173                                 logger := sch.logger.WithField("ContainerUUID", ctr.UUID)
174                                 logger.Debug("unlock because pool capacity is used by higher priority containers")
175                                 err := sch.queue.Unlock(ctr.UUID)
176                                 if err != nil {
177                                         logger.WithError(err).Warn("error unlocking")
178                                 }
179                         }
180                 }
181                 // Shut down idle workers that didn't get any
182                 // containers mapped onto them before we hit quota.
183                 for it, n := range unalloc {
184                         if n < 1 {
185                                 continue
186                         }
187                         sch.pool.Shutdown(it)
188                 }
189         }
190 }
191
192 // Lock the given container. Should be called in a new goroutine.
193 func (sch *Scheduler) lockContainer(logger logrus.FieldLogger, uuid string) {
194         if !sch.uuidLock(uuid, "lock") {
195                 return
196         }
197         defer sch.uuidUnlock(uuid)
198         if ctr, ok := sch.queue.Get(uuid); !ok || ctr.State != arvados.ContainerStateQueued {
199                 // This happens if the container has been cancelled or
200                 // locked since runQueue called sch.queue.Entries(),
201                 // possibly by a lockContainer() call from a previous
202                 // runQueue iteration. In any case, we will respond
203                 // appropriately on the next runQueue iteration, which
204                 // will have already been triggered by the queue
205                 // update.
206                 logger.WithField("State", ctr.State).Debug("container no longer queued by the time we decided to lock it, doing nothing")
207                 return
208         }
209         err := sch.queue.Lock(uuid)
210         if err != nil {
211                 logger.WithError(err).Warn("error locking container")
212                 return
213         }
214         logger.Debug("lock succeeded")
215         ctr, ok := sch.queue.Get(uuid)
216         if !ok {
217                 logger.Error("(BUG?) container disappeared from queue after Lock succeeded")
218         } else if ctr.State != arvados.ContainerStateLocked {
219                 logger.Warnf("(race?) container has state=%q after Lock succeeded", ctr.State)
220         }
221 }
222
223 // Acquire a non-blocking lock for specified UUID, returning true if
224 // successful.  The op argument is used only for debug logs.
225 //
226 // If the lock is not available, uuidLock arranges to wake up the
227 // scheduler after a short delay, so it can retry whatever operation
228 // is trying to get the lock (if that operation is still worth doing).
229 //
230 // This mechanism helps avoid spamming the controller/database with
231 // concurrent updates for any single container, even when the
232 // scheduler loop is running frequently.
233 func (sch *Scheduler) uuidLock(uuid, op string) bool {
234         sch.mtx.Lock()
235         defer sch.mtx.Unlock()
236         logger := sch.logger.WithFields(logrus.Fields{
237                 "ContainerUUID": uuid,
238                 "Op":            op,
239         })
240         if op, locked := sch.uuidOp[uuid]; locked {
241                 logger.Debugf("uuidLock not available, Op=%s in progress", op)
242                 // Make sure the scheduler loop wakes up to retry.
243                 sch.wakeup.Reset(time.Second / 4)
244                 return false
245         }
246         logger.Debug("uuidLock acquired")
247         sch.uuidOp[uuid] = op
248         return true
249 }
250
251 func (sch *Scheduler) uuidUnlock(uuid string) {
252         sch.mtx.Lock()
253         defer sch.mtx.Unlock()
254         delete(sch.uuidOp, uuid)
255 }