-
Notifications
You must be signed in to change notification settings - Fork 682
/
resource_validator.go
88 lines (78 loc) · 1.97 KB
/
resource_validator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package entrypoint
import (
"context"
"fmt"
"io/ioutil"
"os"
"github.com/datawire/ambassador/v2/pkg/kates"
)
type resourceValidator struct {
invalid map[string]*kates.Unstructured
katesValidator *kates.Validator
}
func newResourceValidator() (*resourceValidator, error) {
crdFile, err := findCRDFile()
if err != nil {
return nil, err
}
crdYAML, err := ioutil.ReadAll(crdFile)
if err != nil {
_ = crdFile.Close()
return nil, err
}
if err := crdFile.Close(); err != nil {
return nil, err
}
crdObjs, err := kates.ParseManifests(string(crdYAML))
if err != nil {
return nil, err
}
katesValidator, err := kates.NewValidator(nil, crdObjs)
if err != nil {
return nil, err
}
return &resourceValidator{
katesValidator: katesValidator,
invalid: map[string]*kates.Unstructured{},
}, nil
}
func (v *resourceValidator) isValid(ctx context.Context, un *kates.Unstructured) bool {
key := string(un.GetUID())
err := v.katesValidator.Validate(ctx, un)
if err != nil {
fmt.Printf("validation error: %s %s/%s -- %s\n", un.GetKind(), un.GetNamespace(), un.GetName(), err.Error())
copy := un.DeepCopy()
copy.Object["errors"] = err.Error()
v.invalid[key] = copy
return false
} else {
delete(v.invalid, key)
return true
}
}
func (v *resourceValidator) getInvalid() []*kates.Unstructured {
var result []*kates.Unstructured
for _, inv := range v.invalid {
result = append(result, inv)
}
return result
}
func findCRDFile() (*os.File, error) {
candidateFilepaths := []string{
"/opt/ambassador/etc/crds.yaml",
"manifests/emissary/emissary-crds.yaml",
"ambassador/manifests/emissary/emissary-crds.yaml",
"../../manifests/emissary/emissary-crds.yaml",
}
for _, filepath := range candidateFilepaths {
file, err := os.Open(filepath)
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
return file, nil
}
return nil, fmt.Errorf("couldn't find CRDs at any of the following locations: %q", candidateFilepaths)
}