Merge branch 'master' into 13937-keepstore-prometheus
[arvados.git] / lib / dispatchcloud / container / queue.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package container
6
7 import (
8         "io"
9         "sync"
10         "time"
11
12         "git.curoverse.com/arvados.git/sdk/go/arvados"
13         "github.com/prometheus/client_golang/prometheus"
14         "github.com/sirupsen/logrus"
15 )
16
17 type typeChooser func(*arvados.Container) (arvados.InstanceType, error)
18
19 // An APIClient performs Arvados API requests. It is typically an
20 // *arvados.Client.
21 type APIClient interface {
22         RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error
23 }
24
25 // A QueueEnt is an entry in the queue, consisting of a container
26 // record and the instance type that should be used to run it.
27 type QueueEnt struct {
28         // The container to run. Only the UUID, State, Priority, and
29         // RuntimeConstraints fields are populated.
30         Container    arvados.Container    `json:"container"`
31         InstanceType arvados.InstanceType `json:"instance_type"`
32 }
33
34 // String implements fmt.Stringer by returning the queued container's
35 // UUID.
36 func (c *QueueEnt) String() string {
37         return c.Container.UUID
38 }
39
40 // A Queue is an interface to an Arvados cluster's container
41 // database. It presents only the containers that are eligible to be
42 // run by, are already being run by, or have recently been run by the
43 // present dispatcher.
44 //
45 // The Entries, Get, and Forget methods do not block: they return
46 // immediately, using cached data.
47 //
48 // The updating methods (Cancel, Lock, Unlock, Update) do block: they
49 // return only after the operation has completed.
50 //
51 // A Queue's Update method should be called periodically to keep the
52 // cache up to date.
53 type Queue struct {
54         logger     logrus.FieldLogger
55         reg        *prometheus.Registry
56         chooseType typeChooser
57         client     APIClient
58
59         auth    *arvados.APIClientAuthorization
60         current map[string]QueueEnt
61         updated time.Time
62         mtx     sync.Mutex
63
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{}
72
73         // active notification subscribers (see Subscribe)
74         subscribers map[<-chan struct{}]chan struct{}
75 }
76
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 {
81         return &Queue{
82                 logger:      logger,
83                 reg:         reg,
84                 chooseType:  chooseType,
85                 client:      client,
86                 current:     map[string]QueueEnt{},
87                 subscribers: map[<-chan struct{}]chan struct{}{},
88         }
89 }
90
91 // Subscribe returns a channel that becomes ready to receive when an
92 // entry in the Queue is updated.
93 //
94 //      ch := q.Subscribe()
95 //      defer q.Unsubscribe(ch)
96 //      for range ch {
97 //              // ...
98 //      }
99 func (cq *Queue) Subscribe() <-chan struct{} {
100         cq.mtx.Lock()
101         defer cq.mtx.Unlock()
102         ch := make(chan struct{}, 1)
103         cq.subscribers[ch] = ch
104         return ch
105 }
106
107 // Unsubscribe stops sending updates to the given channel. See
108 // Subscribe.
109 func (cq *Queue) Unsubscribe(ch <-chan struct{}) {
110         cq.mtx.Lock()
111         defer cq.mtx.Unlock()
112         delete(cq.subscribers, ch)
113 }
114
115 // Caller must have lock.
116 func (cq *Queue) notify() {
117         for _, ch := range cq.subscribers {
118                 select {
119                 case ch <- struct{}{}:
120                 default:
121                 }
122         }
123 }
124
125 // Forget drops the specified container from the cache. It should be
126 // called on finalized containers to avoid leaking memory over
127 // time. It is a no-op if the indicated container is not in a
128 // finalized state.
129 func (cq *Queue) Forget(uuid string) {
130         cq.mtx.Lock()
131         defer cq.mtx.Unlock()
132         ctr := cq.current[uuid].Container
133         if ctr.State == arvados.ContainerStateComplete || ctr.State == arvados.ContainerStateCancelled {
134                 delete(cq.current, uuid)
135         }
136 }
137
138 // Get returns the (partial) Container record for the specified
139 // container. Like a map lookup, its second return value is false if
140 // the specified container is not in the Queue.
141 func (cq *Queue) Get(uuid string) (arvados.Container, bool) {
142         cq.mtx.Lock()
143         defer cq.mtx.Unlock()
144         if ctr, ok := cq.current[uuid]; !ok {
145                 return arvados.Container{}, false
146         } else {
147                 return ctr.Container, true
148         }
149 }
150
151 // Entries returns all cache entries, keyed by container UUID.
152 //
153 // The returned threshold indicates the maximum age of any cached data
154 // returned in the map. This makes it possible for a scheduler to
155 // determine correctly the outcome of a remote process that updates
156 // container state. It must first wait for the remote process to exit,
157 // then wait for the Queue to start and finish its next Update --
158 // i.e., it must wait until threshold > timeProcessExited.
159 func (cq *Queue) Entries() (entries map[string]QueueEnt, threshold time.Time) {
160         cq.mtx.Lock()
161         defer cq.mtx.Unlock()
162         entries = make(map[string]QueueEnt, len(cq.current))
163         for uuid, ctr := range cq.current {
164                 entries[uuid] = ctr
165         }
166         threshold = cq.updated
167         return
168 }
169
170 // Update refreshes the cache from the Arvados API. It adds newly
171 // queued containers, and updates the state of previously queued
172 // containers.
173 func (cq *Queue) Update() error {
174         cq.mtx.Lock()
175         cq.dontupdate = map[string]struct{}{}
176         updateStarted := time.Now()
177         cq.mtx.Unlock()
178
179         next, err := cq.poll()
180         if err != nil {
181                 return err
182         }
183
184         cq.mtx.Lock()
185         defer cq.mtx.Unlock()
186         for uuid, ctr := range next {
187                 if _, dontupdate := cq.dontupdate[uuid]; dontupdate {
188                         // Don't clobber a local update that happened
189                         // after we started polling.
190                         continue
191                 }
192                 if cur, ok := cq.current[uuid]; !ok {
193                         cq.addEnt(uuid, *ctr)
194                 } else {
195                         cur.Container = *ctr
196                         cq.current[uuid] = cur
197                 }
198         }
199         for uuid := range cq.current {
200                 if _, dontupdate := cq.dontupdate[uuid]; dontupdate {
201                         // Don't expunge an entry that was
202                         // added/updated locally after we started
203                         // polling.
204                         continue
205                 } else if _, stillpresent := next[uuid]; !stillpresent {
206                         // Expunge an entry that no longer appears in
207                         // the poll response (evidently it's
208                         // cancelled, completed, deleted, or taken by
209                         // a different dispatcher).
210                         delete(cq.current, uuid)
211                 }
212         }
213         cq.dontupdate = nil
214         cq.updated = updateStarted
215         cq.notify()
216         return nil
217 }
218
219 func (cq *Queue) addEnt(uuid string, ctr arvados.Container) {
220         it, err := cq.chooseType(&ctr)
221         if err != nil && (ctr.State == arvados.ContainerStateQueued || ctr.State == arvados.ContainerStateLocked) {
222                 // We assume here that any chooseType error is a hard
223                 // error: it wouldn't help to try again, or to leave
224                 // it for a different dispatcher process to attempt.
225                 errorString := err.Error()
226                 logger := cq.logger.WithField("ContainerUUID", ctr.UUID)
227                 logger.WithError(err).Warn("cancel container with no suitable instance type")
228                 go func() {
229                         if ctr.State == arvados.ContainerStateQueued {
230                                 // Can't set runtime error without
231                                 // locking first. If Lock() is
232                                 // successful, it will call addEnt()
233                                 // again itself, and we'll fall
234                                 // through to the
235                                 // setRuntimeError/Cancel code below.
236                                 err := cq.Lock(ctr.UUID)
237                                 if err != nil {
238                                         logger.WithError(err).Warn("lock failed")
239                                         // ...and try again on the
240                                         // next Update, if the problem
241                                         // still exists.
242                                 }
243                                 return
244                         }
245                         var err error
246                         defer func() {
247                                 if err == nil {
248                                         return
249                                 }
250                                 // On failure, check current container
251                                 // state, and don't log the error if
252                                 // the failure came from losing a
253                                 // race.
254                                 var latest arvados.Container
255                                 cq.client.RequestAndDecode(&latest, "GET", "arvados/v1/containers/"+ctr.UUID, nil, map[string][]string{"select": {"state"}})
256                                 if latest.State == arvados.ContainerStateCancelled {
257                                         return
258                                 }
259                                 logger.WithError(err).Warn("error while trying to cancel unsatisfiable container")
260                         }()
261                         err = cq.setRuntimeError(ctr.UUID, errorString)
262                         if err != nil {
263                                 return
264                         }
265                         err = cq.Cancel(ctr.UUID)
266                         if err != nil {
267                                 return
268                         }
269                 }()
270                 return
271         }
272         cq.current[uuid] = QueueEnt{Container: ctr, InstanceType: it}
273 }
274
275 // Lock acquires the dispatch lock for the given container.
276 func (cq *Queue) Lock(uuid string) error {
277         return cq.apiUpdate(uuid, "lock")
278 }
279
280 // Unlock releases the dispatch lock for the given container.
281 func (cq *Queue) Unlock(uuid string) error {
282         return cq.apiUpdate(uuid, "unlock")
283 }
284
285 // setRuntimeError sets runtime_status["error"] to the given value.
286 // Container should already have state==Locked or Running.
287 func (cq *Queue) setRuntimeError(uuid, errorString string) error {
288         return cq.client.RequestAndDecode(nil, "PUT", "arvados/v1/containers/"+uuid, nil, map[string]map[string]map[string]interface{}{
289                 "container": {
290                         "runtime_status": {
291                                 "error": errorString,
292                         },
293                 },
294         })
295 }
296
297 // Cancel cancels the given container.
298 func (cq *Queue) Cancel(uuid string) error {
299         err := cq.client.RequestAndDecode(nil, "PUT", "arvados/v1/containers/"+uuid, nil, map[string]map[string]interface{}{
300                 "container": {"state": arvados.ContainerStateCancelled},
301         })
302         if err != nil {
303                 return err
304         }
305         cq.mtx.Lock()
306         defer cq.mtx.Unlock()
307         cq.notify()
308         return nil
309 }
310
311 func (cq *Queue) apiUpdate(uuid, action string) error {
312         var resp arvados.Container
313         err := cq.client.RequestAndDecode(&resp, "POST", "arvados/v1/containers/"+uuid+"/"+action, nil, nil)
314         if err != nil {
315                 return err
316         }
317
318         cq.mtx.Lock()
319         defer cq.mtx.Unlock()
320         if cq.dontupdate != nil {
321                 cq.dontupdate[uuid] = struct{}{}
322         }
323         if ent, ok := cq.current[uuid]; !ok {
324                 cq.addEnt(uuid, resp)
325         } else {
326                 ent.Container.State, ent.Container.Priority, ent.Container.LockedByUUID = resp.State, resp.Priority, resp.LockedByUUID
327                 cq.current[uuid] = ent
328         }
329         cq.notify()
330         return nil
331 }
332
333 func (cq *Queue) poll() (map[string]*arvados.Container, error) {
334         cq.mtx.Lock()
335         size := len(cq.current)
336         auth := cq.auth
337         cq.mtx.Unlock()
338
339         if auth == nil {
340                 auth = &arvados.APIClientAuthorization{}
341                 err := cq.client.RequestAndDecode(auth, "GET", "arvados/v1/api_client_authorizations/current", nil, nil)
342                 if err != nil {
343                         return nil, err
344                 }
345                 cq.mtx.Lock()
346                 cq.auth = auth
347                 cq.mtx.Unlock()
348         }
349
350         next := make(map[string]*arvados.Container, size)
351         apply := func(updates []arvados.Container) {
352                 for _, upd := range updates {
353                         if next[upd.UUID] == nil {
354                                 next[upd.UUID] = &arvados.Container{}
355                         }
356                         *next[upd.UUID] = upd
357                 }
358         }
359         selectParam := []string{"uuid", "state", "priority", "runtime_constraints"}
360         limitParam := 1000
361
362         mine, err := cq.fetchAll(arvados.ResourceListParams{
363                 Select:  selectParam,
364                 Order:   "uuid",
365                 Limit:   &limitParam,
366                 Count:   "none",
367                 Filters: []arvados.Filter{{"locked_by_uuid", "=", auth.UUID}},
368         })
369         if err != nil {
370                 return nil, err
371         }
372         apply(mine)
373
374         avail, err := cq.fetchAll(arvados.ResourceListParams{
375                 Select:  selectParam,
376                 Order:   "uuid",
377                 Limit:   &limitParam,
378                 Count:   "none",
379                 Filters: []arvados.Filter{{"state", "=", arvados.ContainerStateQueued}, {"priority", ">", "0"}},
380         })
381         if err != nil {
382                 return nil, err
383         }
384         apply(avail)
385
386         var missing []string
387         cq.mtx.Lock()
388         for uuid, ent := range cq.current {
389                 if next[uuid] == nil &&
390                         ent.Container.State != arvados.ContainerStateCancelled &&
391                         ent.Container.State != arvados.ContainerStateComplete {
392                         missing = append(missing, uuid)
393                 }
394         }
395         cq.mtx.Unlock()
396
397         for i, page := 0, 20; i < len(missing); i += page {
398                 batch := missing[i:]
399                 if len(batch) > page {
400                         batch = batch[:page]
401                 }
402                 ended, err := cq.fetchAll(arvados.ResourceListParams{
403                         Select:  selectParam,
404                         Order:   "uuid",
405                         Count:   "none",
406                         Filters: []arvados.Filter{{"uuid", "in", batch}},
407                 })
408                 if err != nil {
409                         return nil, err
410                 }
411                 apply(ended)
412         }
413         return next, nil
414 }
415
416 func (cq *Queue) fetchAll(initialParams arvados.ResourceListParams) ([]arvados.Container, error) {
417         var results []arvados.Container
418         params := initialParams
419         params.Offset = 0
420         for {
421                 // This list variable must be a new one declared
422                 // inside the loop: otherwise, items in the API
423                 // response would get deep-merged into the items
424                 // loaded in previous iterations.
425                 var list arvados.ContainerList
426
427                 err := cq.client.RequestAndDecode(&list, "GET", "arvados/v1/containers", nil, params)
428                 if err != nil {
429                         return nil, err
430                 }
431                 if len(list.Items) == 0 {
432                         break
433                 }
434
435                 results = append(results, list.Items...)
436                 if len(params.Order) == 1 && params.Order == "uuid" {
437                         params.Filters = append(initialParams.Filters, arvados.Filter{"uuid", ">", list.Items[len(list.Items)-1].UUID})
438                 } else {
439                         params.Offset += len(list.Items)
440                 }
441         }
442         return results, nil
443 }