forked from istio/istio
/
validate.go
212 lines (182 loc) · 6.09 KB
/
validate.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Copyright 2018 Istio Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package validate
import (
"errors"
"fmt"
"io"
multierror "github.com/hashicorp/go-multierror"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions/resource"
"istio.io/istio/pilot/pkg/config/kube/crd"
"istio.io/istio/pilot/pkg/model"
)
// TODO use k8s.io/cli-runtime when we switch to v1.12 k8s dependency
// k8s.io/cli-runtime was created for k8s v.12. Prior to that release,
// the genericclioptions packages are organized under kubectl.
var (
// Expect YAML to only include these top-level fields
validFields = map[string]bool{
"apiVersion": true,
"kind": true,
"metadata": true,
"spec": true,
"status": true,
}
)
/*
TODO(https://github.com/istio/istio/issues/4887)
Reusing the existing mixer validation code pulls in all of the mixer
adapter packages into istioctl. Not only is this not ideal (see
issue), but it also breaks the istioctl build on windows as some mixer
adapters use linux specific packges (e.g. syslog).
func createMixerValidator() store.BackendValidator {
info := generatedTmplRepo.SupportedTmplInfo
templates := make(map[string]*template.Info, len(info))
for k := range info {
t := info[k]
templates[k] = &t
}
adapters := config.AdapterInfoMap(adapter.Inventory(), template.NewRepository(info).SupportsTemplate)
return store.NewValidator(nil, runtimeConfig.KindMap(adapters, templates))
}
var mixerValidator = createMixerValidator()
type validateArgs struct {
filenames []string
// TODO validateObjectStream namespace/object?
}
func (args validateArgs) validate() error {
var errs *multierror.Error
if len(args.filenames) == 0 {
errs = multierror.Append(errs, errors.New("no filenames set (see --filename/-f)"))
}
return errs.ErrorOrNil()
}
*/
func validateResource(un *unstructured.Unstructured) error {
schema, exists := model.IstioConfigTypes.GetByType(crd.CamelCaseToKebabCase(un.GetKind()))
if exists {
obj, err := crd.ConvertObjectFromUnstructured(schema, un, "")
if err != nil {
return fmt.Errorf("cannot parse proto message: %v", err)
}
return schema.Validate(obj.Name, obj.Namespace, obj.Spec)
}
return fmt.Errorf("%s.%s validation is not supported", un.GetKind(), un.GetAPIVersion())
/*
TODO(https://github.com/istio/istio/issues/4887)
ev := &store.BackendEvent{
Key: store.Key{
Name: un.GetName(),
Namespace: un.GetNamespace(),
Kind: un.GetKind(),
},
Value: mixerCrd.ToBackEndResource(un),
}
return mixerValidator.Validate(ev)
*/
}
var errMissingResource = errors.New(`error: you must specify resources by --filename.
Example resource specifications include:
'-f rsrc.yaml'
'--filename=rsrc.json'`)
func validateObjects(restClientGetter resource.RESTClientGetter, options resource.FilenameOptions, writer io.Writer) error {
// resource.Builder{} validates most of the CLI flags consistent
// with kubectl which is good. Unfortunately, it also assumes
// resources can be specified as '<resource> <name>' which is
// bad. We don't don't for file-based configuration validation. If
// a filename is missing, resource.Builder{} prints a warning
// referencing '<resource> <name>' which would be confusing to the
// user. Avoid this confusion by checking for missing filenames
// are ourselves for invoking the builder.
if len(options.Filenames) == 0 {
return errMissingResource
}
r := resource.NewBuilder(restClientGetter).
Unstructured().
FilenameParam(false, &options).
Flatten().
Local().
Do()
if err := r.Err(); err != nil {
return err
}
var errs error
_ = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
content, err := runtime.DefaultUnstructuredConverter.ToUnstructured(info.Object)
if err != nil {
errs = multierror.Append(errs, err)
return nil
}
un := &unstructured.Unstructured{Object: content}
for key := range content {
if _, ok := validFields[key]; !ok {
errs = multierror.Append(errs, fmt.Errorf("%s: Unknown field %q on %s resource %s namespace %q",
info.Source, key, un.GetObjectKind().GroupVersionKind(), un.GetName(), un.GetNamespace()))
}
}
if err := validateResource(un); err != nil {
errs = multierror.Append(errs, fmt.Errorf("error validating resource (%v Name=%v Namespace=%v): %v",
un.GetObjectKind().GroupVersionKind(), un.GetName(), un.GetNamespace(), err))
}
return nil
})
if errs != nil {
return errs
}
for _, fname := range options.Filenames {
fmt.Fprintf(writer, "%q is valid\n", fname)
}
return nil
}
func strPtr(val string) *string {
return &val
}
func boolPtr(val bool) *bool {
return &val
}
// NewValidateCommand creates a new command for validating Istio k8s resources.
func NewValidateCommand() *cobra.Command {
var (
kubeConfigFlags = &genericclioptions.ConfigFlags{
Context: strPtr(""),
Namespace: strPtr(""),
KubeConfig: strPtr(""),
}
filenames = []string{}
fileNameFlags = &genericclioptions.FileNameFlags{
Filenames: &filenames,
Recursive: boolPtr(true),
}
)
c := &cobra.Command{
Use: "validate -f FILENAME [options]",
Short: "Validate Istio policy and rules",
Example: `istioctl validate -f bookinfo-gateway.yaml`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
return validateObjects(kubeConfigFlags, fileNameFlags.ToOptions(), c.OutOrStderr())
},
}
flags := c.PersistentFlags()
kubeConfigFlags.AddFlags(flags)
fileNameFlags.AddFlags(flags)
return c
}