19428: Fix failing request on normal failed user lookup case.
[arvados.git] / services / keep-web / cache.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package keepweb
6
7 import (
8         "sync"
9         "sync/atomic"
10         "time"
11
12         "git.arvados.org/arvados.git/sdk/go/arvados"
13         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
14         "git.arvados.org/arvados.git/sdk/go/keepclient"
15         lru "github.com/hashicorp/golang-lru"
16         "github.com/prometheus/client_golang/prometheus"
17         "github.com/sirupsen/logrus"
18 )
19
20 const metricsUpdateInterval = time.Second / 10
21
22 type cache struct {
23         cluster     *arvados.Cluster
24         logger      logrus.FieldLogger
25         registry    *prometheus.Registry
26         metrics     cacheMetrics
27         pdhs        *lru.TwoQueueCache
28         collections *lru.TwoQueueCache
29         sessions    *lru.TwoQueueCache
30         setupOnce   sync.Once
31
32         chPruneSessions    chan struct{}
33         chPruneCollections chan struct{}
34 }
35
36 type cacheMetrics struct {
37         requests          prometheus.Counter
38         collectionBytes   prometheus.Gauge
39         collectionEntries prometheus.Gauge
40         sessionEntries    prometheus.Gauge
41         collectionHits    prometheus.Counter
42         pdhHits           prometheus.Counter
43         sessionHits       prometheus.Counter
44         sessionMisses     prometheus.Counter
45         apiCalls          prometheus.Counter
46 }
47
48 func (m *cacheMetrics) setup(reg *prometheus.Registry) {
49         m.requests = prometheus.NewCounter(prometheus.CounterOpts{
50                 Namespace: "arvados",
51                 Subsystem: "keepweb_collectioncache",
52                 Name:      "requests",
53                 Help:      "Number of targetID-to-manifest lookups handled.",
54         })
55         reg.MustRegister(m.requests)
56         m.collectionHits = prometheus.NewCounter(prometheus.CounterOpts{
57                 Namespace: "arvados",
58                 Subsystem: "keepweb_collectioncache",
59                 Name:      "hits",
60                 Help:      "Number of pdh-to-manifest cache hits.",
61         })
62         reg.MustRegister(m.collectionHits)
63         m.pdhHits = prometheus.NewCounter(prometheus.CounterOpts{
64                 Namespace: "arvados",
65                 Subsystem: "keepweb_collectioncache",
66                 Name:      "pdh_hits",
67                 Help:      "Number of uuid-to-pdh cache hits.",
68         })
69         reg.MustRegister(m.pdhHits)
70         m.apiCalls = prometheus.NewCounter(prometheus.CounterOpts{
71                 Namespace: "arvados",
72                 Subsystem: "keepweb_collectioncache",
73                 Name:      "api_calls",
74                 Help:      "Number of outgoing API calls made by cache.",
75         })
76         reg.MustRegister(m.apiCalls)
77         m.collectionBytes = prometheus.NewGauge(prometheus.GaugeOpts{
78                 Namespace: "arvados",
79                 Subsystem: "keepweb_sessions",
80                 Name:      "cached_collection_bytes",
81                 Help:      "Total size of all cached manifests and sessions.",
82         })
83         reg.MustRegister(m.collectionBytes)
84         m.collectionEntries = prometheus.NewGauge(prometheus.GaugeOpts{
85                 Namespace: "arvados",
86                 Subsystem: "keepweb_collectioncache",
87                 Name:      "cached_manifests",
88                 Help:      "Number of manifests in cache.",
89         })
90         reg.MustRegister(m.collectionEntries)
91         m.sessionEntries = prometheus.NewGauge(prometheus.GaugeOpts{
92                 Namespace: "arvados",
93                 Subsystem: "keepweb_sessions",
94                 Name:      "active",
95                 Help:      "Number of active token sessions.",
96         })
97         reg.MustRegister(m.sessionEntries)
98         m.sessionHits = prometheus.NewCounter(prometheus.CounterOpts{
99                 Namespace: "arvados",
100                 Subsystem: "keepweb_sessions",
101                 Name:      "hits",
102                 Help:      "Number of token session cache hits.",
103         })
104         reg.MustRegister(m.sessionHits)
105         m.sessionMisses = prometheus.NewCounter(prometheus.CounterOpts{
106                 Namespace: "arvados",
107                 Subsystem: "keepweb_sessions",
108                 Name:      "misses",
109                 Help:      "Number of token session cache misses.",
110         })
111         reg.MustRegister(m.sessionMisses)
112 }
113
114 type cachedPDH struct {
115         expire  time.Time
116         refresh time.Time
117         pdh     string
118 }
119
120 type cachedCollection struct {
121         expire     time.Time
122         collection *arvados.Collection
123 }
124
125 type cachedPermission struct {
126         expire time.Time
127 }
128
129 type cachedSession struct {
130         expire        time.Time
131         fs            atomic.Value
132         client        *arvados.Client
133         arvadosclient *arvadosclient.ArvadosClient
134         keepclient    *keepclient.KeepClient
135         user          atomic.Value
136 }
137
138 func (c *cache) setup() {
139         var err error
140         c.pdhs, err = lru.New2Q(c.cluster.Collections.WebDAVCache.MaxUUIDEntries)
141         if err != nil {
142                 panic(err)
143         }
144         c.collections, err = lru.New2Q(c.cluster.Collections.WebDAVCache.MaxCollectionEntries)
145         if err != nil {
146                 panic(err)
147         }
148         c.sessions, err = lru.New2Q(c.cluster.Collections.WebDAVCache.MaxSessions)
149         if err != nil {
150                 panic(err)
151         }
152
153         reg := c.registry
154         if reg == nil {
155                 reg = prometheus.NewRegistry()
156         }
157         c.metrics.setup(reg)
158         go func() {
159                 for range time.Tick(metricsUpdateInterval) {
160                         c.updateGauges()
161                 }
162         }()
163         c.chPruneCollections = make(chan struct{}, 1)
164         go func() {
165                 for range c.chPruneCollections {
166                         c.pruneCollections()
167                 }
168         }()
169         c.chPruneSessions = make(chan struct{}, 1)
170         go func() {
171                 for range c.chPruneSessions {
172                         c.pruneSessions()
173                 }
174         }()
175 }
176
177 func (c *cache) updateGauges() {
178         c.metrics.collectionBytes.Set(float64(c.collectionBytes()))
179         c.metrics.collectionEntries.Set(float64(c.collections.Len()))
180         c.metrics.sessionEntries.Set(float64(c.sessions.Len()))
181 }
182
183 var selectPDH = map[string]interface{}{
184         "select": []string{"portable_data_hash"},
185 }
186
187 // Update saves a modified version (fs) to an existing collection
188 // (coll) and, if successful, updates the relevant cache entries so
189 // subsequent calls to Get() reflect the modifications.
190 func (c *cache) Update(client *arvados.Client, coll arvados.Collection, fs arvados.CollectionFileSystem) error {
191         c.setupOnce.Do(c.setup)
192
193         m, err := fs.MarshalManifest(".")
194         if err != nil || m == coll.ManifestText {
195                 return err
196         }
197         coll.ManifestText = m
198         var updated arvados.Collection
199         err = client.RequestAndDecode(&updated, "PATCH", "arvados/v1/collections/"+coll.UUID, nil, map[string]interface{}{
200                 "collection": map[string]string{
201                         "manifest_text": coll.ManifestText,
202                 },
203         })
204         if err != nil {
205                 c.pdhs.Remove(coll.UUID)
206                 return err
207         }
208         c.collections.Add(client.AuthToken+"\000"+updated.PortableDataHash, &cachedCollection{
209                 expire:     time.Now().Add(time.Duration(c.cluster.Collections.WebDAVCache.TTL)),
210                 collection: &updated,
211         })
212         c.pdhs.Add(coll.UUID, &cachedPDH{
213                 expire:  time.Now().Add(time.Duration(c.cluster.Collections.WebDAVCache.TTL)),
214                 refresh: time.Now().Add(time.Duration(c.cluster.Collections.WebDAVCache.UUIDTTL)),
215                 pdh:     updated.PortableDataHash,
216         })
217         return nil
218 }
219
220 // ResetSession unloads any potentially stale state. Should be called
221 // after write operations, so subsequent reads don't return stale
222 // data.
223 func (c *cache) ResetSession(token string) {
224         c.setupOnce.Do(c.setup)
225         c.sessions.Remove(token)
226 }
227
228 // Get a long-lived CustomFileSystem suitable for doing a read operation
229 // with the given token.
230 func (c *cache) GetSession(token string) (arvados.CustomFileSystem, *cachedSession, error) {
231         c.setupOnce.Do(c.setup)
232         now := time.Now()
233         ent, _ := c.sessions.Get(token)
234         sess, _ := ent.(*cachedSession)
235         expired := false
236         if sess == nil {
237                 c.metrics.sessionMisses.Inc()
238                 sess = &cachedSession{
239                         expire: now.Add(c.cluster.Collections.WebDAVCache.TTL.Duration()),
240                 }
241                 var err error
242                 sess.client, err = arvados.NewClientFromConfig(c.cluster)
243                 if err != nil {
244                         return nil, nil, err
245                 }
246                 sess.client.AuthToken = token
247                 sess.arvadosclient, err = arvadosclient.New(sess.client)
248                 if err != nil {
249                         return nil, nil, err
250                 }
251                 sess.keepclient = keepclient.New(sess.arvadosclient)
252                 c.sessions.Add(token, sess)
253         } else if sess.expire.Before(now) {
254                 c.metrics.sessionMisses.Inc()
255                 expired = true
256         } else {
257                 c.metrics.sessionHits.Inc()
258         }
259         select {
260         case c.chPruneSessions <- struct{}{}:
261         default:
262         }
263         fs, _ := sess.fs.Load().(arvados.CustomFileSystem)
264         if fs != nil && !expired {
265                 return fs, sess, nil
266         }
267         fs = sess.client.SiteFileSystem(sess.keepclient)
268         fs.ForwardSlashNameSubstitution(c.cluster.Collections.ForwardSlashNameSubstitution)
269         sess.fs.Store(fs)
270         return fs, sess, nil
271 }
272
273 // Remove all expired session cache entries, then remove more entries
274 // until approximate remaining size <= maxsize/2
275 func (c *cache) pruneSessions() {
276         now := time.Now()
277         keys := c.sessions.Keys()
278         sizes := make([]int64, len(keys))
279         var size int64
280         for i, token := range keys {
281                 ent, ok := c.sessions.Peek(token)
282                 if !ok {
283                         continue
284                 }
285                 s := ent.(*cachedSession)
286                 if s.expire.Before(now) {
287                         c.sessions.Remove(token)
288                         continue
289                 }
290                 if fs, ok := s.fs.Load().(arvados.CustomFileSystem); ok {
291                         sizes[i] = fs.MemorySize()
292                         size += sizes[i]
293                 }
294         }
295         // Remove tokens until reaching size limit, starting with the
296         // least frequently used entries (which Keys() returns last).
297         for i := len(keys) - 1; i >= 0 && size > c.cluster.Collections.WebDAVCache.MaxCollectionBytes/2; i-- {
298                 if sizes[i] > 0 {
299                         c.sessions.Remove(keys[i])
300                         size -= sizes[i]
301                 }
302         }
303 }
304
305 func (c *cache) Get(arv *arvadosclient.ArvadosClient, targetID string, forceReload bool) (*arvados.Collection, error) {
306         c.setupOnce.Do(c.setup)
307         c.metrics.requests.Inc()
308
309         var pdhRefresh bool
310         var pdh string
311         if arvadosclient.PDHMatch(targetID) {
312                 pdh = targetID
313         } else if ent, cached := c.pdhs.Get(targetID); cached {
314                 ent := ent.(*cachedPDH)
315                 if ent.expire.Before(time.Now()) {
316                         c.pdhs.Remove(targetID)
317                 } else {
318                         pdh = ent.pdh
319                         pdhRefresh = forceReload || time.Now().After(ent.refresh)
320                         c.metrics.pdhHits.Inc()
321                 }
322         }
323
324         if pdh == "" {
325                 // UUID->PDH mapping is not cached, might as well get
326                 // the whole collection record and be done (below).
327                 c.logger.Debugf("cache(%s): have no pdh", targetID)
328         } else if cached := c.lookupCollection(arv.ApiToken + "\000" + pdh); cached == nil {
329                 // PDH->manifest is not cached, might as well get the
330                 // whole collection record (below).
331                 c.logger.Debugf("cache(%s): have pdh %s but manifest is not cached", targetID, pdh)
332         } else if !pdhRefresh {
333                 // We looked up UUID->PDH very recently, and we still
334                 // have the manifest for that PDH.
335                 c.logger.Debugf("cache(%s): have pdh %s and refresh not needed", targetID, pdh)
336                 return cached, nil
337         } else {
338                 // Get current PDH for this UUID (and confirm we still
339                 // have read permission).  Most likely, the cached PDH
340                 // is still correct, in which case we can use our
341                 // cached manifest.
342                 c.metrics.apiCalls.Inc()
343                 var current arvados.Collection
344                 err := arv.Get("collections", targetID, selectPDH, &current)
345                 if err != nil {
346                         return nil, err
347                 }
348                 if current.PortableDataHash == pdh {
349                         // PDH has not changed, cached manifest is
350                         // correct.
351                         c.logger.Debugf("cache(%s): verified cached pdh %s is still correct", targetID, pdh)
352                         return cached, nil
353                 }
354                 if cached := c.lookupCollection(arv.ApiToken + "\000" + current.PortableDataHash); cached != nil {
355                         // PDH changed, and we already have the
356                         // manifest for that new PDH.
357                         c.logger.Debugf("cache(%s): cached pdh %s was stale, new pdh is %s and manifest is already in cache", targetID, pdh, current.PortableDataHash)
358                         return cached, nil
359                 }
360         }
361
362         // Either UUID->PDH is not cached, or PDH->manifest is not
363         // cached.
364         var retrieved arvados.Collection
365         c.metrics.apiCalls.Inc()
366         err := arv.Get("collections", targetID, nil, &retrieved)
367         if err != nil {
368                 return nil, err
369         }
370         c.logger.Debugf("cache(%s): retrieved manifest, caching with pdh %s", targetID, retrieved.PortableDataHash)
371         exp := time.Now().Add(time.Duration(c.cluster.Collections.WebDAVCache.TTL))
372         if targetID != retrieved.PortableDataHash {
373                 c.pdhs.Add(targetID, &cachedPDH{
374                         expire:  exp,
375                         refresh: time.Now().Add(time.Duration(c.cluster.Collections.WebDAVCache.UUIDTTL)),
376                         pdh:     retrieved.PortableDataHash,
377                 })
378         }
379         c.collections.Add(arv.ApiToken+"\000"+retrieved.PortableDataHash, &cachedCollection{
380                 expire:     exp,
381                 collection: &retrieved,
382         })
383         if int64(len(retrieved.ManifestText)) > c.cluster.Collections.WebDAVCache.MaxCollectionBytes/int64(c.cluster.Collections.WebDAVCache.MaxCollectionEntries) {
384                 select {
385                 case c.chPruneCollections <- struct{}{}:
386                 default:
387                 }
388         }
389         return &retrieved, nil
390 }
391
392 // pruneCollections checks the total bytes occupied by manifest_text
393 // in the collection cache and removes old entries as needed to bring
394 // the total size down to CollectionBytes. It also deletes all expired
395 // entries.
396 //
397 // pruneCollections does not aim to be perfectly correct when there is
398 // concurrent cache activity.
399 func (c *cache) pruneCollections() {
400         var size int64
401         now := time.Now()
402         keys := c.collections.Keys()
403         entsize := make([]int, len(keys))
404         expired := make([]bool, len(keys))
405         for i, k := range keys {
406                 v, ok := c.collections.Peek(k)
407                 if !ok {
408                         continue
409                 }
410                 ent := v.(*cachedCollection)
411                 n := len(ent.collection.ManifestText)
412                 size += int64(n)
413                 entsize[i] = n
414                 expired[i] = ent.expire.Before(now)
415         }
416         for i, k := range keys {
417                 if expired[i] {
418                         c.collections.Remove(k)
419                         size -= int64(entsize[i])
420                 }
421         }
422         for i, k := range keys {
423                 if size <= c.cluster.Collections.WebDAVCache.MaxCollectionBytes/2 {
424                         break
425                 }
426                 if expired[i] {
427                         // already removed this entry in the previous loop
428                         continue
429                 }
430                 c.collections.Remove(k)
431                 size -= int64(entsize[i])
432         }
433 }
434
435 // collectionBytes returns the approximate combined memory size of the
436 // collection cache and session filesystem cache.
437 func (c *cache) collectionBytes() uint64 {
438         var size uint64
439         for _, k := range c.collections.Keys() {
440                 v, ok := c.collections.Peek(k)
441                 if !ok {
442                         continue
443                 }
444                 size += uint64(len(v.(*cachedCollection).collection.ManifestText))
445         }
446         for _, token := range c.sessions.Keys() {
447                 ent, ok := c.sessions.Peek(token)
448                 if !ok {
449                         continue
450                 }
451                 if fs, ok := ent.(*cachedSession).fs.Load().(arvados.CustomFileSystem); ok {
452                         size += uint64(fs.MemorySize())
453                 }
454         }
455         return size
456 }
457
458 func (c *cache) lookupCollection(key string) *arvados.Collection {
459         e, cached := c.collections.Get(key)
460         if !cached {
461                 return nil
462         }
463         ent := e.(*cachedCollection)
464         if ent.expire.Before(time.Now()) {
465                 c.collections.Remove(key)
466                 return nil
467         }
468         c.metrics.collectionHits.Inc()
469         return ent.collection
470 }
471
472 func (c *cache) GetTokenUser(token string) (*arvados.User, error) {
473         // Get and cache user record associated with this
474         // token.  We need to know their UUID for logging, and
475         // whether they are an admin or not for certain
476         // permission checks.
477
478         // Get/create session entry
479         _, sess, err := c.GetSession(token)
480         if err != nil {
481                 return nil, err
482         }
483
484         // See if the user is already set, and if so, return it
485         user, _ := sess.user.Load().(*arvados.User)
486         if user != nil {
487                 return user, nil
488         }
489
490         // Fetch the user record
491         c.metrics.apiCalls.Inc()
492         var current arvados.User
493
494         err = sess.client.RequestAndDecode(&current, "GET", "arvados/v1/users/current", nil, nil)
495         if err != nil {
496                 return nil, err
497         }
498
499         // Stash the user record for next time
500         sess.user.Store(&current)
501         return &current, nil
502 }