1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
13 "git.curoverse.com/arvados.git/sdk/go/arvados"
14 "github.com/prometheus/client_golang/prometheus"
15 "github.com/sirupsen/logrus"
18 type typeChooser func(*arvados.Container) (arvados.InstanceType, error)
20 // An APIClient performs Arvados API requests. It is typically an
22 type APIClient interface {
23 RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error
26 // A QueueEnt is an entry in the queue, consisting of a container
27 // record and the instance type that should be used to run it.
28 type QueueEnt struct {
29 // The container to run. Only the UUID, State, Priority, and
30 // RuntimeConstraints fields are populated.
31 Container arvados.Container `json:"container"`
32 InstanceType arvados.InstanceType `json:"instance_type"`
35 // String implements fmt.Stringer by returning the queued container's
37 func (c *QueueEnt) String() string {
38 return c.Container.UUID
41 // A Queue is an interface to an Arvados cluster's container
42 // database. It presents only the containers that are eligible to be
43 // run by, are already being run by, or have recently been run by the
44 // present dispatcher.
46 // The Entries, Get, and Forget methods do not block: they return
47 // immediately, using cached data.
49 // The updating methods (Cancel, Lock, Unlock, Update) do block: they
50 // return only after the operation has completed.
52 // A Queue's Update method should be called periodically to keep the
55 logger logrus.FieldLogger
56 chooseType typeChooser
59 auth *arvados.APIClientAuthorization
60 current map[string]QueueEnt
64 // Methods that modify the Queue (like Lock) add the affected
65 // container UUIDs to dontupdate. When applying a batch of
66 // updates received from the network, anything appearing in
67 // dontupdate is skipped, in case the received update has
68 // already been superseded by the locally initiated change.
69 // When no network update is in progress, this protection is
70 // not needed, and dontupdate is nil.
71 dontupdate map[string]struct{}
73 // active notification subscribers (see Subscribe)
74 subscribers map[<-chan struct{}]chan struct{}
77 // NewQueue returns a new Queue. When a new container appears in the
78 // Arvados cluster's queue during Update, chooseType will be called to
79 // assign an appropriate arvados.InstanceType for the queue entry.
80 func NewQueue(logger logrus.FieldLogger, reg *prometheus.Registry, chooseType typeChooser, client APIClient) *Queue {
83 chooseType: chooseType,
85 current: map[string]QueueEnt{},
86 subscribers: map[<-chan struct{}]chan struct{}{},
94 // Subscribe returns a channel that becomes ready to receive when an
95 // entry in the Queue is updated.
97 // ch := q.Subscribe()
98 // defer q.Unsubscribe(ch)
102 func (cq *Queue) Subscribe() <-chan struct{} {
104 defer cq.mtx.Unlock()
105 ch := make(chan struct{}, 1)
106 cq.subscribers[ch] = ch
110 // Unsubscribe stops sending updates to the given channel. See
112 func (cq *Queue) Unsubscribe(ch <-chan struct{}) {
114 defer cq.mtx.Unlock()
115 delete(cq.subscribers, ch)
118 // Caller must have lock.
119 func (cq *Queue) notify() {
120 for _, ch := range cq.subscribers {
122 case ch <- struct{}{}:
128 // Forget drops the specified container from the cache. It should be
129 // called on finalized containers to avoid leaking memory over
130 // time. It is a no-op if the indicated container is not in a
132 func (cq *Queue) Forget(uuid string) {
134 defer cq.mtx.Unlock()
135 ctr := cq.current[uuid].Container
136 if ctr.State == arvados.ContainerStateComplete || ctr.State == arvados.ContainerStateCancelled {
137 cq.delEnt(uuid, ctr.State)
141 // Get returns the (partial) Container record for the specified
142 // container. Like a map lookup, its second return value is false if
143 // the specified container is not in the Queue.
144 func (cq *Queue) Get(uuid string) (arvados.Container, bool) {
146 defer cq.mtx.Unlock()
147 if ctr, ok := cq.current[uuid]; !ok {
148 return arvados.Container{}, false
150 return ctr.Container, true
154 // Entries returns all cache entries, keyed by container UUID.
156 // The returned threshold indicates the maximum age of any cached data
157 // returned in the map. This makes it possible for a scheduler to
158 // determine correctly the outcome of a remote process that updates
159 // container state. It must first wait for the remote process to exit,
160 // then wait for the Queue to start and finish its next Update --
161 // i.e., it must wait until threshold > timeProcessExited.
162 func (cq *Queue) Entries() (entries map[string]QueueEnt, threshold time.Time) {
164 defer cq.mtx.Unlock()
165 entries = make(map[string]QueueEnt, len(cq.current))
166 for uuid, ctr := range cq.current {
169 threshold = cq.updated
173 // Update refreshes the cache from the Arvados API. It adds newly
174 // queued containers, and updates the state of previously queued
176 func (cq *Queue) Update() error {
178 cq.dontupdate = map[string]struct{}{}
179 updateStarted := time.Now()
182 next, err := cq.poll()
188 defer cq.mtx.Unlock()
189 for uuid, ctr := range next {
190 if _, dontupdate := cq.dontupdate[uuid]; dontupdate {
191 // Don't clobber a local update that happened
192 // after we started polling.
195 if cur, ok := cq.current[uuid]; !ok {
196 cq.addEnt(uuid, *ctr)
199 cq.current[uuid] = cur
202 for uuid, ent := range cq.current {
203 if _, dontupdate := cq.dontupdate[uuid]; dontupdate {
204 // Don't expunge an entry that was
205 // added/updated locally after we started
208 } else if _, stillpresent := next[uuid]; !stillpresent {
209 // Expunge an entry that no longer appears in
210 // the poll response (evidently it's
211 // cancelled, completed, deleted, or taken by
212 // a different dispatcher).
213 cq.delEnt(uuid, ent.Container.State)
217 cq.updated = updateStarted
222 // Caller must have lock.
223 func (cq *Queue) delEnt(uuid string, state arvados.ContainerState) {
224 cq.logger.WithFields(logrus.Fields{
225 "ContainerUUID": uuid,
227 }).Info("dropping container from queue")
228 delete(cq.current, uuid)
231 func (cq *Queue) addEnt(uuid string, ctr arvados.Container) {
232 it, err := cq.chooseType(&ctr)
233 if err != nil && (ctr.State == arvados.ContainerStateQueued || ctr.State == arvados.ContainerStateLocked) {
234 // We assume here that any chooseType error is a hard
235 // error: it wouldn't help to try again, or to leave
236 // it for a different dispatcher process to attempt.
237 errorString := err.Error()
238 logger := cq.logger.WithField("ContainerUUID", ctr.UUID)
239 logger.WithError(err).Warn("cancel container with no suitable instance type")
241 if ctr.State == arvados.ContainerStateQueued {
242 // Can't set runtime error without
243 // locking first. If Lock() is
244 // successful, it will call addEnt()
245 // again itself, and we'll fall
247 // setRuntimeError/Cancel code below.
248 err := cq.Lock(ctr.UUID)
250 logger.WithError(err).Warn("lock failed")
251 // ...and try again on the
252 // next Update, if the problem
262 // On failure, check current container
263 // state, and don't log the error if
264 // the failure came from losing a
266 var latest arvados.Container
267 cq.client.RequestAndDecode(&latest, "GET", "arvados/v1/containers/"+ctr.UUID, nil, map[string][]string{"select": {"state"}})
268 if latest.State == arvados.ContainerStateCancelled {
271 logger.WithError(err).Warn("error while trying to cancel unsatisfiable container")
273 err = cq.setRuntimeError(ctr.UUID, errorString)
277 err = cq.Cancel(ctr.UUID)
284 cq.logger.WithFields(logrus.Fields{
285 "ContainerUUID": ctr.UUID,
287 "Priority": ctr.Priority,
288 "InstanceType": it.Name,
289 }).Info("adding container to queue")
290 cq.current[uuid] = QueueEnt{Container: ctr, InstanceType: it}
293 // Lock acquires the dispatch lock for the given container.
294 func (cq *Queue) Lock(uuid string) error {
295 return cq.apiUpdate(uuid, "lock")
298 // Unlock releases the dispatch lock for the given container.
299 func (cq *Queue) Unlock(uuid string) error {
300 return cq.apiUpdate(uuid, "unlock")
303 // setRuntimeError sets runtime_status["error"] to the given value.
304 // Container should already have state==Locked or Running.
305 func (cq *Queue) setRuntimeError(uuid, errorString string) error {
306 return cq.client.RequestAndDecode(nil, "PUT", "arvados/v1/containers/"+uuid, nil, map[string]map[string]map[string]interface{}{
309 "error": errorString,
315 // Cancel cancels the given container.
316 func (cq *Queue) Cancel(uuid string) error {
317 var resp arvados.Container
318 err := cq.client.RequestAndDecode(&resp, "PUT", "arvados/v1/containers/"+uuid, nil, map[string]map[string]interface{}{
319 "container": {"state": arvados.ContainerStateCancelled},
324 cq.updateWithResp(uuid, resp)
328 func (cq *Queue) apiUpdate(uuid, action string) error {
329 var resp arvados.Container
330 err := cq.client.RequestAndDecode(&resp, "POST", "arvados/v1/containers/"+uuid+"/"+action, nil, nil)
334 cq.updateWithResp(uuid, resp)
338 // Update the local queue with the response received from a
339 // state-changing API request (lock/unlock/cancel).
340 func (cq *Queue) updateWithResp(uuid string, resp arvados.Container) {
342 defer cq.mtx.Unlock()
343 if cq.dontupdate != nil {
344 cq.dontupdate[uuid] = struct{}{}
346 if ent, ok := cq.current[uuid]; !ok {
347 cq.addEnt(uuid, resp)
349 ent.Container.State, ent.Container.Priority, ent.Container.LockedByUUID = resp.State, resp.Priority, resp.LockedByUUID
350 cq.current[uuid] = ent
355 func (cq *Queue) poll() (map[string]*arvados.Container, error) {
357 size := len(cq.current)
362 auth = &arvados.APIClientAuthorization{}
363 err := cq.client.RequestAndDecode(auth, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
372 next := make(map[string]*arvados.Container, size)
373 apply := func(updates []arvados.Container) {
374 for _, upd := range updates {
375 if next[upd.UUID] == nil {
376 next[upd.UUID] = &arvados.Container{}
378 *next[upd.UUID] = upd
381 selectParam := []string{"uuid", "state", "priority", "runtime_constraints"}
384 mine, err := cq.fetchAll(arvados.ResourceListParams{
389 Filters: []arvados.Filter{{"locked_by_uuid", "=", auth.UUID}},
396 avail, err := cq.fetchAll(arvados.ResourceListParams{
401 Filters: []arvados.Filter{{"state", "=", arvados.ContainerStateQueued}, {"priority", ">", "0"}},
408 missing := map[string]bool{}
410 for uuid, ent := range cq.current {
411 if next[uuid] == nil &&
412 ent.Container.State != arvados.ContainerStateCancelled &&
413 ent.Container.State != arvados.ContainerStateComplete {
419 for len(missing) > 0 {
421 for uuid := range missing {
422 batch = append(batch, uuid)
423 if len(batch) == 20 {
427 filters := []arvados.Filter{{"uuid", "in", batch}}
428 ended, err := cq.fetchAll(arvados.ResourceListParams{
439 // This is the only case where we can conclude
440 // a container has been deleted from the
441 // database. A short (but non-zero) page, on
442 // the other hand, can be caused by a response
444 for _, uuid := range batch {
445 cq.logger.WithField("ContainerUUID", uuid).Warn("container not found by controller (deleted?)")
446 delete(missing, uuid)
448 cq.delEnt(uuid, cq.current[uuid].Container.State)
453 for _, ctr := range ended {
454 if _, ok := missing[ctr.UUID]; !ok {
455 msg := "BUG? server response did not match requested filters, erroring out rather than risk deadlock"
456 cq.logger.WithFields(logrus.Fields{
457 "ContainerUUID": ctr.UUID,
460 return nil, errors.New(msg)
462 delete(missing, ctr.UUID)
468 func (cq *Queue) fetchAll(initialParams arvados.ResourceListParams) ([]arvados.Container, error) {
469 var results []arvados.Container
470 params := initialParams
473 // This list variable must be a new one declared
474 // inside the loop: otherwise, items in the API
475 // response would get deep-merged into the items
476 // loaded in previous iterations.
477 var list arvados.ContainerList
479 err := cq.client.RequestAndDecode(&list, "GET", "arvados/v1/containers", nil, params)
483 if len(list.Items) == 0 {
487 results = append(results, list.Items...)
488 if len(params.Order) == 1 && params.Order == "uuid" {
489 params.Filters = append(initialParams.Filters, arvados.Filter{"uuid", ">", list.Items[len(list.Items)-1].UUID})
491 params.Offset += len(list.Items)
497 func (cq *Queue) runMetrics(reg *prometheus.Registry) {
498 mEntries := prometheus.NewGaugeVec(prometheus.GaugeOpts{
499 Namespace: "arvados",
500 Subsystem: "dispatchcloud",
501 Name: "queue_entries",
502 Help: "Number of active container entries in the controller database.",
503 }, []string{"state", "instance_type"})
504 reg.MustRegister(mEntries)
507 state arvados.ContainerState
510 count := map[entKey]int{}
513 defer cq.Unsubscribe(ch)
515 for k := range count {
518 ents, _ := cq.Entries()
519 for _, ent := range ents {
520 count[entKey{ent.Container.State, ent.InstanceType.Name}]++
522 for k, v := range count {
523 mEntries.WithLabelValues(string(k.state), k.inst).Set(float64(v))