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