-
Notifications
You must be signed in to change notification settings - Fork 0
/
validations.go
280 lines (237 loc) · 7.3 KB
/
validations.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright 2017 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// Package cloud provides functionality to parse information
// describing clouds, including regions, supported auth types etc.
package cloud
import (
"fmt"
"reflect"
"strings"
"github.com/juju/errors"
"github.com/juju/gojsonschema"
"gopkg.in/yaml.v2"
)
//ValidationWarning are JSON schema validation errors used to warn users about
//potential schema violations
type ValidationWarning struct {
Messages []string
}
func (e *ValidationWarning) Error() string {
str := ""
for _, msg := range e.Messages {
str = fmt.Sprintf("%s\n%s", str, msg)
}
return str
}
var cloudSetSchema = map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"clouds": map[string]interface{}{
"type": "object",
"additionalProperties": cloudSchema,
},
},
"additionalProperties": false,
}
var cloudSchema = map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"name": map[string]interface{}{"type": "string"},
"type": map[string]interface{}{"type": "string"},
"description": map[string]interface{}{"type": "string"},
"auth-types": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{"type": "string"},
},
"host-cloud-region": map[string]interface{}{"type": "string"},
"endpoint": map[string]interface{}{"type": "string"},
"identity-endpoint": map[string]interface{}{"type": "string"},
"storage-endpoint": map[string]interface{}{"type": "string"},
"config": map[string]interface{}{"type": "object"},
"regions": regionsSchema,
"region-config": map[string]interface{}{"type": "object"},
"ca-certificates": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{"type": "string"},
},
},
"additionalProperties": false,
}
var regionsSchema = map[string]interface{}{
"type": "object",
"additionalProperties": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"endpoint": map[string]interface{}{"type": "string"},
"identity-endpoint": map[string]interface{}{"type": "string"},
"storage-endpoint": map[string]interface{}{"type": "string"},
},
"additionalProperties": false,
},
}
// ValidateCloudSet reports any erroneous properties found in cloud metadata
// YAML. If there are no erroneous properties, then ValidateCloudSet returns nil
// otherwise it return an error listing all erroneous properties and possible
// suggestion.
func ValidateCloudSet(data []byte) error {
return validateCloud(data, &cloudSetSchema)
}
// ValidateOneCloud is like ValidateCloudSet but validates the metadata for only
// one cloud and not multiple.
func ValidateOneCloud(data []byte) error {
return validateCloud(data, &cloudSchema)
}
func validateCloud(data []byte, jsonSchema *map[string]interface{}) error {
var body interface{}
if err := yaml.Unmarshal(data, &body); err != nil {
return errors.Annotate(err, "cannot unmarshal yaml cloud metadata")
}
jsonBody := yamlToJSON(body)
invalidKeys, err := validateCloudMetaData(jsonBody, jsonSchema)
if err != nil {
return errors.Annotate(err, "cannot validate yaml cloud metadata")
}
formatKeyError := func(invalidKey, similarValidKey string) string {
str := fmt.Sprintf("property %s is invalid.", invalidKey)
if similarValidKey != "" {
str = fmt.Sprintf("%s Perhaps you mean %q.", str, similarValidKey)
}
return str
}
cloudValidationError := ValidationWarning{}
for k, v := range invalidKeys {
cloudValidationError.Messages = append(cloudValidationError.Messages, formatKeyError(k, v))
}
if len(cloudValidationError.Messages) != 0 {
return &cloudValidationError
}
return nil
}
func cloudTags() []string {
keys := make(map[string]struct{})
collectTags(reflect.TypeOf((*cloud)(nil)), "yaml", []string{"map[string]*cloud.region", "yaml.MapSlice"}, &keys)
keyList := make([]string, 0, len(keys))
for k := range keys {
keyList = append(keyList, k)
}
return keyList
}
// collectTags returns a set of keys for a specified struct tag. If no tag is
// specified for a particular field of the argument struct type, then the
// all-lowercase field name is used as per Go tag conventions. If the tag
// specified is not the name a conventionally formatted go struct tag, then the
// results of this function are invalid. Values of invalid kinds result in no
// processing.
func collectTags(t reflect.Type, tag string, ignoreTypes []string, keys *map[string]struct{}) {
switch t.Kind() {
case reflect.Array, reflect.Slice, reflect.Map, reflect.Ptr:
collectTags(t.Elem(), tag, ignoreTypes, keys)
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fieldTag := field.Tag.Get(tag)
var fieldTagKey string
ignoredType := false
for _, it := range ignoreTypes {
if field.Type.String() == it {
ignoredType = true
break
}
}
if fieldTag == "-" || ignoredType {
continue
}
if len(fieldTag) > 0 {
fieldTagKey = strings.Split(fieldTag, ",")[0]
} else {
fieldTagKey = strings.ToLower(field.Name)
}
(*keys)[fieldTagKey] = struct{}{}
collectTags(field.Type, tag, ignoreTypes, keys)
}
}
}
func validateCloudMetaData(body interface{}, jsonSchema *map[string]interface{}) (map[string]string, error) {
documentLoader := gojsonschema.NewGoLoader(body)
schemaLoader := gojsonschema.NewGoLoader(jsonSchema)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return nil, err
}
minEditingDistance := 5
validCloudProperties := cloudTags()
suggestionMap := map[string]string{}
for _, rsltErr := range result.Errors() {
invalidProperty := strings.Split(rsltErr.Description, " ")[2]
suggestionMap[invalidProperty] = ""
editingDistance := minEditingDistance
for _, validProperty := range validCloudProperties {
dist := distance(invalidProperty, validProperty)
if dist < editingDistance && dist < minEditingDistance {
editingDistance = dist
suggestionMap[invalidProperty] = validProperty
}
}
}
return suggestionMap, nil
}
func yamlToJSON(i interface{}) interface{} {
switch x := i.(type) {
case map[interface{}]interface{}:
m2 := map[string]interface{}{}
for k, v := range x {
m2[k.(string)] = yamlToJSON(v)
}
return m2
case []interface{}:
for i, v := range x {
x[i] = yamlToJSON(v)
}
}
return i
}
// The following "editing distance" comparator was lifted from
// https://github.com/arbovm/levenshtein/blob/master/levenshtein.go which has a
// compatible BSD license. We use it to calculate the distance between a
// discovered invalid yaml property and known good properties to identify
// suggestions.
func distance(str1, str2 string) int {
var cost, lastdiag, olddiag int
s1 := []rune(str1)
s2 := []rune(str2)
lenS1 := len(s1)
lenS2 := len(s2)
column := make([]int, lenS1+1)
for y := 1; y <= lenS1; y++ {
column[y] = y
}
for x := 1; x <= lenS2; x++ {
column[0] = x
lastdiag = x - 1
for y := 1; y <= lenS1; y++ {
olddiag = column[y]
cost = 0
if s1[y-1] != s2[x-1] {
cost = 1
}
column[y] = min(
column[y]+1,
column[y-1]+1,
lastdiag+cost)
lastdiag = olddiag
}
}
return column[lenS1]
}
func min(a, b, c int) int {
if a < b {
if a < c {
return a
}
} else {
if b < c {
return b
}
}
return c
}