0
Fork 0
mirror of https://github.com/project-zot/zot.git synced 2024-12-16 21:56:37 -05:00

feat(cve): cache trivy results for an image:tag (#1101)

Signed-off-by: Andrei Aaron <aaaron@luxoft.com>
This commit is contained in:
Andrei Aaron 2023-01-17 23:14:17 +02:00 committed by GitHub
parent eebc750367
commit 9f8bc60b20
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 56 additions and 1 deletions

2
go.mod
View file

@ -243,7 +243,7 @@ require (
github.com/hashicorp/go-safetemp v1.0.0 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/hashicorp/go-version v1.6.0 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/hashicorp/golang-lru v0.5.4
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/hcl/v2 v2.10.1 // indirect
github.com/huandu/xstrings v1.3.2 // indirect

View file

@ -0,0 +1,41 @@
package trivy
import (
lru "github.com/hashicorp/golang-lru"
cvemodel "zotregistry.io/zot/pkg/extensions/search/cve/model"
"zotregistry.io/zot/pkg/log"
)
type CveCache struct {
cache *lru.Cache
log log.Logger
}
func NewCveCache(size int, log log.Logger) *CveCache {
cache, _ := lru.New(size)
return &CveCache{cache: cache, log: log}
}
func (cveCache *CveCache) Add(image string, cveMap map[string]cvemodel.CVE) {
cveCache.cache.Add(image, cveMap)
}
func (cveCache *CveCache) Get(image string) map[string]cvemodel.CVE {
value, ok := cveCache.cache.Get(image)
if !ok {
return nil
}
cveMap, ok := value.(map[string]cvemodel.CVE)
if !ok {
return nil
}
return cveMap
}
func (cveCache *CveCache) Purge() {
cveCache.cache.Purge()
}

View file

@ -77,6 +77,7 @@ type Scanner struct {
storeController storage.StoreController
log log.Logger
dbLock *sync.Mutex
cache *CveCache
}
func NewScanner(storeController storage.StoreController,
@ -114,6 +115,7 @@ func NewScanner(storeController storage.StoreController,
cveController: cveController,
storeController: storeController,
dbLock: &sync.Mutex{},
cache: NewCveCache(10000, log), //nolint:gomnd
}
}
@ -147,6 +149,10 @@ func (scanner Scanner) getTrivyContext(image string) *trivyCtx {
}
func (scanner Scanner) IsImageFormatScannable(image string) (bool, error) {
if scanner.cache.Get(image) != nil {
return true, nil
}
imageDir, inputTag := common.GetImageDirAndTag(image)
repoMeta, err := scanner.repoDB.GetRepoMeta(imageDir)
@ -194,6 +200,10 @@ func (scanner Scanner) IsImageFormatScannable(image string) (bool, error) {
}
func (scanner Scanner) ScanImage(image string) (map[string]cvemodel.CVE, error) {
if scanner.cache.Get(image) != nil {
return scanner.cache.Get(image), nil
}
cveidMap := make(map[string]cvemodel.CVE)
scanner.log.Debug().Str("image", image).Msg("scanning image")
@ -264,6 +274,8 @@ func (scanner Scanner) ScanImage(image string) (map[string]cvemodel.CVE, error)
}
}
scanner.cache.Add(image, cveidMap)
return cveidMap, nil
}
@ -293,6 +305,8 @@ func (scanner Scanner) UpdateDB() error {
}
}
scanner.cache.Purge()
return nil
}