Files
grafana/pkg/services/secrets/manager/cache.go
Joan López de la Franca Beltran 9826a694a8 Encryption: Add Prometheus metrics (#48603)
2022-05-06 10:21:55 +02:00

80 lines
1.3 KiB
Go

package manager
import (
"strconv"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
)
var (
now = time.Now
)
type dataKeyCacheEntry struct {
dataKey []byte
expiration time.Time
}
func (e dataKeyCacheEntry) expired() bool {
return e.expiration.Before(now())
}
type dataKeyCache struct {
sync.RWMutex
entries map[string]dataKeyCacheEntry
cacheTTL time.Duration
}
func newDataKeyCache(ttl time.Duration) *dataKeyCache {
return &dataKeyCache{
entries: make(map[string]dataKeyCacheEntry),
cacheTTL: ttl,
}
}
func (c *dataKeyCache) get(id string) ([]byte, bool) {
c.RLock()
defer c.RUnlock()
entry, exists := c.entries[id]
cacheReadsCounter.With(prometheus.Labels{
"hit": strconv.FormatBool(exists),
}).Inc()
if !exists || entry.expired() {
return nil, false
}
return entry.dataKey, true
}
func (c *dataKeyCache) add(id string, dataKey []byte) {
c.Lock()
defer c.Unlock()
c.entries[id] = dataKeyCacheEntry{
dataKey: dataKey,
expiration: now().Add(c.cacheTTL),
}
}
func (c *dataKeyCache) removeExpired() {
c.Lock()
defer c.Unlock()
for id, entry := range c.entries {
if entry.expired() {
delete(c.entries, id)
}
}
}
func (c *dataKeyCache) flush() {
c.Lock()
c.entries = make(map[string]dataKeyCacheEntry)
c.Unlock()
}