diff --git a/main.go b/main.go index 1ff26f2..875da7e 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( "log" "os" + "github.com/yannh/kubeconform/pkg/cache" "github.com/yannh/kubeconform/pkg/registry" "github.com/yannh/kubeconform/pkg/resource" "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) } + var schema []byte 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 { break } diff --git a/pkg/cache/main.go b/pkg/cache/main.go new file mode 100644 index 0000000..9bb8cae --- /dev/null +++ b/pkg/cache/main.go @@ -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 + } +} \ No newline at end of file