forked from kyverno/kyverno
-
Notifications
You must be signed in to change notification settings - Fork 2
/
command.go
104 lines (90 loc) · 2.75 KB
/
command.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package validate
import (
"encoding/json"
"errors"
"fmt"
"os"
"github.com/nirmata/kyverno/pkg/utils"
"github.com/nirmata/kyverno/pkg/kyverno/common"
"github.com/nirmata/kyverno/pkg/kyverno/sanitizedError"
policy2 "github.com/nirmata/kyverno/pkg/policy"
"github.com/spf13/cobra"
_ "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation"
yamlv2 "gopkg.in/yaml.v2"
log "sigs.k8s.io/controller-runtime/pkg/log"
)
func Command() *cobra.Command {
var outputType string
var crdPaths []string
cmd := &cobra.Command{
Use: "validate",
Short: "Validates kyverno policies",
Example: "kyverno validate /path/to/policy.yaml /path/to/folderOfPolicies",
RunE: func(cmd *cobra.Command, policyPaths []string) (err error) {
log := log.Log
defer func() {
if err != nil {
if !sanitizedError.IsErrorSanitized(err) {
log.Error(err, "failed to sanitize")
err = fmt.Errorf("internal error")
}
}
}()
if outputType != "" {
if outputType != "yaml" && outputType != "json" {
return sanitizedError.NewWithError(fmt.Sprintf("%s format is not supported", outputType), errors.New("yaml and json are supported"))
}
}
policies, openAPIController, err := common.GetPoliciesValidation(policyPaths)
if err != nil {
return err
}
// if CRD's are passed, add these to OpenAPIController
if len(crdPaths) > 0 {
crds, err := common.GetCRDs(crdPaths)
if err != nil {
log.Error(err, "crd is invalid", "file", crdPaths)
os.Exit(1)
}
for _, crd := range crds {
openAPIController.ParseCRD(*crd)
}
}
invalidPolicyFound := false
for _, policy := range policies {
err := policy2.Validate(utils.MarshalPolicy(*policy), nil, true, openAPIController)
if err != nil {
fmt.Printf("Policy %s is invalid.\n", policy.Name)
log.Error(err, "policy "+policy.Name+" is invalid")
invalidPolicyFound = true
} else {
fmt.Printf("Policy %s is valid.\n\n", policy.Name)
if outputType != "" {
logger := log.WithName("validate")
p, err := common.MutatePolicy(policy, logger)
if err != nil {
if !sanitizedError.IsErrorSanitized(err) {
return sanitizedError.NewWithError("failed to mutate policy.", err)
}
return err
}
if outputType == "yaml" {
yamlPolicy, _ := yamlv2.Marshal(p)
fmt.Println(string(yamlPolicy))
} else {
jsonPolicy, _ := json.MarshalIndent(p, "", " ")
fmt.Println(string(jsonPolicy))
}
}
}
}
if invalidPolicyFound == true {
os.Exit(1)
}
return nil
},
}
cmd.Flags().StringVarP(&outputType, "output", "o", "", "Prints the mutated policy")
cmd.Flags().StringArrayVarP(&crdPaths, "crd", "c", []string{}, "Path to CRD files")
return cmd
}