18870: Need to declare NODES as array
[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         var size int64
278         keys := c.sessions.Keys()
279         for _, token := range keys {
280                 ent, ok := c.sessions.Peek(token)
281                 if !ok {
282                         continue
283                 }
284                 s := ent.(*cachedSession)
285                 if s.expire.Before(now) {
286                         c.sessions.Remove(token)
287                         continue
288                 }
289                 if fs, ok := s.fs.Load().(arvados.CustomFileSystem); ok {
290                         size += fs.MemorySize()
291                 }
292         }
293         // Remove tokens until reaching size limit, starting with the
294         // least frequently used entries (which Keys() returns last).
295         for i := len(keys) - 1; i >= 0; i-- {
296                 token := keys[i]
297                 if size <= c.cluster.Collections.WebDAVCache.MaxCollectionBytes/2 {
298                         break
299                 }
300                 ent, ok := c.sessions.Peek(token)
301                 if !ok {
302                         continue
303                 }
304                 s := ent.(*cachedSession)
305                 fs, _ := s.fs.Load().(arvados.CustomFileSystem)
306                 if fs == nil {
307                         continue
308                 }
309                 c.sessions.Remove(token)
310                 size -= fs.MemorySize()
311         }
312 }
313
314 func (c *cache) Get(arv *arvadosclient.ArvadosClient, targetID string, forceReload bool) (*arvados.Collection, error) {
315         c.setupOnce.Do(c.setup)
316         c.metrics.requests.Inc()
317
318         var pdhRefresh bool
319         var pdh string
320         if arvadosclient.PDHMatch(targetID) {
321                 pdh = targetID
322         } else if ent, cached := c.pdhs.Get(targetID); cached {
323                 ent := ent.(*cachedPDH)
324                 if ent.expire.Before(time.Now()) {
325                         c.pdhs.Remove(targetID)
326                 } else {
327                         pdh = ent.pdh
328                         pdhRefresh = forceReload || time.Now().After(ent.refresh)
329                         c.metrics.pdhHits.Inc()
330                 }
331         }
332
333         if pdh == "" {
334                 // UUID->PDH mapping is not cached, might as well get
335                 // the whole collection record and be done (below).
336                 c.logger.Debugf("cache(%s): have no pdh", targetID)
337         } else if cached := c.lookupCollection(arv.ApiToken + "\000" + pdh); cached == nil {
338                 // PDH->manifest is not cached, might as well get the
339                 // whole collection record (below).
340                 c.logger.Debugf("cache(%s): have pdh %s but manifest is not cached", targetID, pdh)
341         } else if !pdhRefresh {
342                 // We looked up UUID->PDH very recently, and we still
343                 // have the manifest for that PDH.
344                 c.logger.Debugf("cache(%s): have pdh %s and refresh not needed", targetID, pdh)
345                 return cached, nil
346         } else {
347                 // Get current PDH for this UUID (and confirm we still
348                 // have read permission).  Most likely, the cached PDH
349                 // is still correct, in which case we can use our
350                 // cached manifest.
351                 c.metrics.apiCalls.Inc()
352                 var current arvados.Collection
353                 err := arv.Get("collections", targetID, selectPDH, &current)
354                 if err != nil {
355                         return nil, err
356                 }
357                 if current.PortableDataHash == pdh {
358                         // PDH has not changed, cached manifest is
359                         // correct.
360                         c.logger.Debugf("cache(%s): verified cached pdh %s is still correct", targetID, pdh)
361                         return cached, nil
362                 }
363                 if cached := c.lookupCollection(arv.ApiToken + "\000" + current.PortableDataHash); cached != nil {
364                         // PDH changed, and we already have the
365                         // manifest for that new PDH.
366                         c.logger.Debugf("cache(%s): cached pdh %s was stale, new pdh is %s and manifest is already in cache", targetID, pdh, current.PortableDataHash)
367                         return cached, nil
368                 }
369         }
370
371         // Either UUID->PDH is not cached, or PDH->manifest is not
372         // cached.
373         var retrieved arvados.Collection
374         c.metrics.apiCalls.Inc()
375         err := arv.Get("collections", targetID, nil, &retrieved)
376         if err != nil {
377                 return nil, err
378         }
379         c.logger.Debugf("cache(%s): retrieved manifest, caching with pdh %s", targetID, retrieved.PortableDataHash)
380         exp := time.Now().Add(time.Duration(c.cluster.Collections.WebDAVCache.TTL))
381         if targetID != retrieved.PortableDataHash {
382                 c.pdhs.Add(targetID, &cachedPDH{
383                         expire:  exp,
384                         refresh: time.Now().Add(time.Duration(c.cluster.Collections.WebDAVCache.UUIDTTL)),
385                         pdh:     retrieved.PortableDataHash,
386                 })
387         }
388         c.collections.Add(arv.ApiToken+"\000"+retrieved.PortableDataHash, &cachedCollection{
389                 expire:     exp,
390                 collection: &retrieved,
391         })
392         if int64(len(retrieved.ManifestText)) > c.cluster.Collections.WebDAVCache.MaxCollectionBytes/int64(c.cluster.Collections.WebDAVCache.MaxCollectionEntries) {
393                 select {
394                 case c.chPruneCollections <- struct{}{}:
395                 default:
396                 }
397         }
398         return &retrieved, nil
399 }
400
401 // pruneCollections checks the total bytes occupied by manifest_text
402 // in the collection cache and removes old entries as needed to bring
403 // the total size down to CollectionBytes. It also deletes all expired
404 // entries.
405 //
406 // pruneCollections does not aim to be perfectly correct when there is
407 // concurrent cache activity.
408 func (c *cache) pruneCollections() {
409         var size int64
410         now := time.Now()
411         keys := c.collections.Keys()
412         entsize := make([]int, len(keys))
413         expired := make([]bool, len(keys))
414         for i, k := range keys {
415                 v, ok := c.collections.Peek(k)
416                 if !ok {
417                         continue
418                 }
419                 ent := v.(*cachedCollection)
420                 n := len(ent.collection.ManifestText)
421                 size += int64(n)
422                 entsize[i] = n
423                 expired[i] = ent.expire.Before(now)
424         }
425         for i, k := range keys {
426                 if expired[i] {
427                         c.collections.Remove(k)
428                         size -= int64(entsize[i])
429                 }
430         }
431         for i, k := range keys {
432                 if size <= c.cluster.Collections.WebDAVCache.MaxCollectionBytes/2 {
433                         break
434                 }
435                 if expired[i] {
436                         // already removed this entry in the previous loop
437                         continue
438                 }
439                 c.collections.Remove(k)
440                 size -= int64(entsize[i])
441         }
442 }
443
444 // collectionBytes returns the approximate combined memory size of the
445 // collection cache and session filesystem cache.
446 func (c *cache) collectionBytes() uint64 {
447         var size uint64
448         for _, k := range c.collections.Keys() {
449                 v, ok := c.collections.Peek(k)
450                 if !ok {
451                         continue
452                 }
453                 size += uint64(len(v.(*cachedCollection).collection.ManifestText))
454         }
455         for _, token := range c.sessions.Keys() {
456                 ent, ok := c.sessions.Peek(token)
457                 if !ok {
458                         continue
459                 }
460                 if fs, ok := ent.(*cachedSession).fs.Load().(arvados.CustomFileSystem); ok {
461                         size += uint64(fs.MemorySize())
462                 }
463         }
464         return size
465 }
466
467 func (c *cache) lookupCollection(key string) *arvados.Collection {
468         e, cached := c.collections.Get(key)
469         if !cached {
470                 return nil
471         }
472         ent := e.(*cachedCollection)
473         if ent.expire.Before(time.Now()) {
474                 c.collections.Remove(key)
475                 return nil
476         }
477         c.metrics.collectionHits.Inc()
478         return ent.collection
479 }
480
481 func (c *cache) GetTokenUser(token string) (*arvados.User, error) {
482         // Get and cache user record associated with this
483         // token.  We need to know their UUID for logging, and
484         // whether they are an admin or not for certain
485         // permission checks.
486
487         // Get/create session entry
488         _, sess, err := c.GetSession(token)
489         if err != nil {
490                 return nil, err
491         }
492
493         // See if the user is already set, and if so, return it
494         user, _ := sess.user.Load().(*arvados.User)
495         if user != nil {
496                 return user, nil
497         }
498
499         // Fetch the user record
500         c.metrics.apiCalls.Inc()
501         var current arvados.User
502
503         err = sess.client.RequestAndDecode(&current, "GET", "/arvados/v1/users/current", nil, nil)
504         if err != nil {
505                 return nil, err
506         }
507
508         // Stash the user record for next time
509         sess.user.Store(&current)
510         return &current, nil
511 }