add schema caching

This commit is contained in:
Yann Hamon 2020-05-30 06:10:58 +02:00
parent 79c9197f38
commit d3ed871833
2 changed files with 40 additions and 1 deletions

View file

@ -7,6 +7,7 @@ import (
"log" "log"
"os" "os"
"github.com/yannh/kubeconform/pkg/cache"
"github.com/yannh/kubeconform/pkg/registry" "github.com/yannh/kubeconform/pkg/registry"
"github.com/yannh/kubeconform/pkg/resource" "github.com/yannh/kubeconform/pkg/resource"
"github.com/yannh/kubeconform/pkg/validator" "github.com/yannh/kubeconform/pkg/validator"
@ -23,9 +24,11 @@ func validateFile(f io.Reader, regs []*registry.KubernetesRegistry, k8sVersion s
return fmt.Errorf("error while parsing: %s", err) return fmt.Errorf("error while parsing: %s", err)
} }
var schema []byte var schema []byte
for _, reg := range regs { for _, reg := range regs {
schema, err = reg.DownloadSchema(sig.Kind, sig.Version, k8sVersion) downloadSchema := cache.WithCache(reg.DownloadSchema)
schema, err = downloadSchema(sig.Kind, sig.Version, k8sVersion)
if err == nil { if err == nil {
break break
} }

36
pkg/cache/main.go vendored Normal file
View file

@ -0,0 +1,36 @@
package cache
import (
"fmt"
"sync"
)
var mu sync.Mutex
var schemas map[string][]byte
func init () {
schemas = map[string][]byte {}
}
func WithCache(downloadSchema func(string, string, string) ([]byte, error)) (func (string, string, string) ([]byte, error)) {
return func(resourceKind, resourceAPIVersion, k8sVersion string) ([]byte, error) {
cacheKey := fmt.Sprintf("%s-%s-%s", resourceKind, resourceAPIVersion, k8sVersion)
mu.Lock()
cachedSchema, ok := schemas[cacheKey];
mu.Unlock()
if ok {
return cachedSchema, nil
}
schema, err := downloadSchema(resourceKind, resourceAPIVersion, k8sVersion)
if err != nil {
return schema, err
}
mu.Lock()
schemas[cacheKey] = schema
mu.Unlock()
return schema, nil
}
}