Skip to content

Commit

Permalink
snp: clear kds cache daily
Browse files Browse the repository at this point in the history
  • Loading branch information
3u13r committed Jan 2, 2024
1 parent ae5a52d commit 1d283d8
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 10 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ require (
gopkg.in/yaml.v2 v2.4.0
k8s.io/api v0.28.4
k8s.io/apimachinery v0.28.4
k8s.io/utils v0.0.0-20230406110748-d93618cff8a2
)

require (
Expand All @@ -38,7 +39,6 @@ require (
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/klog/v2 v2.100.1 // indirect
k8s.io/utils v0.0.0-20230406110748-d93618cff8a2 // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect
sigs.k8s.io/yaml v1.3.0 // indirect
Expand Down
28 changes: 19 additions & 9 deletions internal/attestation/snp/cachedClient.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,54 @@ package snp

import (
"log/slog"
"time"

"github.com/edgelesssys/nunki/internal/memstore"
"github.com/google/go-sev-guest/verify/trust"
"k8s.io/utils/clock"
)

type cachedKDSHTTPClient struct {
trust.HTTPSGetter
logger *slog.Logger

cache *memstore.Store[string, cacheEntry]
gcTicker clock.Ticker
cache *memstore.Store[string, []byte]
}

func NewCachedKDSHTTPClient(log *slog.Logger) *cachedKDSHTTPClient {
trust.DefaultHTTPSGetter()
return &cachedKDSHTTPClient{

gc := clock.RealClock{}.NewTicker(24 * time.Hour)
c := &cachedKDSHTTPClient{
HTTPSGetter: trust.DefaultHTTPSGetter(),
logger: log.WithGroup("cached-kds-http-client"),
cache: memstore.New[string, cacheEntry](),
cache: memstore.New[string, []byte](),
gcTicker: gc,
}

go c.garbageCollect()
return c
}

func (c *cachedKDSHTTPClient) Get(url string) ([]byte, error) {
if cached, ok := c.cache.Get(url); ok {
c.logger.Debug("Get cached", "url", url)
return cached.data, nil
return cached, nil
}

c.logger.Debug("Get not cached", "url", url)
res, err := c.HTTPSGetter.Get(url)
if err != nil {
return nil, err
}
c.cache.Set(url, cacheEntry{
data: res,
})
c.cache.Set(url, res)
return res, nil
}

type cacheEntry struct {
data []byte
func (c *cachedKDSHTTPClient) garbageCollect() {
for range c.gcTicker.C() {
c.logger.Debug("Garbage collecting")
c.cache.Clear()
}
}
6 changes: 6 additions & 0 deletions internal/memstore/memstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,9 @@ func (s *Store[keyT, valueT]) GetAll() []valueT {
}
return values
}

func (s *Store[keyT, valueT]) Clear() {
s.mux.Lock()
defer s.mux.Unlock()
clear(s.m)
}

0 comments on commit 1d283d8

Please sign in to comment.