forked from fission/fission
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
458 lines (350 loc) · 13.6 KB
/
validation.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
Copyright 2018 The Fission 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 fission
import (
"fmt"
"net/http"
"regexp"
"strings"
"github.com/hashicorp/go-multierror"
nsUtil "github.com/nats-io/nats-streaming-server/util"
"github.com/robfig/cron"
"k8s.io/apimachinery/pkg/util/validation"
)
const (
ErrorUnsupportedType = iota
ErrorInvalidValue
ErrorInvalidObject
)
var (
validAzureQueueName = regexp.MustCompile("^[a-z0-9][a-z0-9\\-]*[a-z0-9]$")
)
type ValidationErrorType int
// ValidationError is a custom error type for resource validation.
// It indicate which field is invalid or illegal in the fission resource.
// Also, it shows what kind of error type, bad value and detail error messages.
type ValidationError struct {
// Type of validation error.
// It indicates what kind of error of field in error output.
Type ValidationErrorType
// Name of error field.
// Example: FunctionReference.Name
Field string
// Error field value.
BadValue interface{}
// Detail error message
Detail string
}
func (e ValidationError) Error() string {
// Example error message
// Failed to create HTTP trigger: Invalid fission HTTPTrigger object:
// * FunctionReference.Name: Invalid value: findped.ts: [...]
errMsg := fmt.Sprintf("%v: ", e.Field)
switch e.Type {
case ErrorUnsupportedType:
errMsg += fmt.Sprintf("Unsupported type: %v", e.BadValue)
case ErrorInvalidValue:
errMsg += fmt.Sprintf("Invalid value: %v", e.BadValue)
case ErrorInvalidObject:
errMsg += fmt.Sprintf("Invalid object: %v", e.BadValue)
default:
errMsg += fmt.Sprintf("Unknown error type: %v", e.BadValue)
}
if len(e.Detail) > 0 {
errMsg += fmt.Sprintf(": %v", e.Detail)
}
return errMsg
}
func AggregateValidationErrors(objName string, err error) error {
var result *multierror.Error
result = multierror.Append(result, err)
result.ErrorFormat = func(errs []error) string {
errMsg := fmt.Sprintf("Invalid fission %v object:\n", objName)
for _, err := range errs {
errMsg += fmt.Sprintf("* %v\n", err.Error())
}
return errMsg
}
return result.ErrorOrNil()
}
func MakeValidationErr(errType ValidationErrorType, field string, val interface{}, detail ...string) ValidationError {
return ValidationError{
Type: errType,
Field: field,
BadValue: val,
Detail: fmt.Sprintf("%v", detail),
}
}
func ValidateKubeLabel(field string, labels map[string]string) error {
var result *multierror.Error
for k, v := range labels {
// Example: XXX -> YYY
// KubernetesWatchTriggerSpec.LabelSelector.Key: Invalid value: XXX
// KubernetesWatchTriggerSpec.LabelSelector.Value: Invalid value: YYY
result = multierror.Append(result,
MakeValidationErr(ErrorInvalidValue, fmt.Sprintf("%v.Key", field), k, validation.IsQualifiedName(k)...),
MakeValidationErr(ErrorInvalidValue, fmt.Sprintf("%v.Value", field), v, validation.IsValidLabelValue(v)...))
}
return result.ErrorOrNil()
}
func ValidateKubePort(field string, port int) error {
var result *multierror.Error
e := validation.IsValidPortNum(port)
if len(e) > 0 {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, field, port, e...))
}
return result.ErrorOrNil()
}
func ValidateKubeName(field string, val string) error {
var result *multierror.Error
e := validation.IsDNS1123Label(val)
if len(e) > 0 {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, field, val, e...))
}
return result.ErrorOrNil()
}
func ValidateKubeReference(refName string, name string, namespace string) error {
var result *multierror.Error
result = multierror.Append(result,
ValidateKubeName(fmt.Sprintf("%v.Name", refName), name),
ValidateKubeName(fmt.Sprintf("%v.Namespace", refName), namespace))
return result.ErrorOrNil()
}
func IsTopicValid(mqType MessageQueueType, topic string) bool {
switch mqType {
case MessageQueueTypeNats:
return nsUtil.IsChannelNameValid(topic, false)
case MessageQueueTypeASQ:
return len(topic) >= 3 && len(topic) <= 63 && validAzureQueueName.MatchString(topic)
}
return false
}
func IsValidCronSpec(spec string) error {
_, err := cron.Parse(spec)
return err
}
/* Resource validation function */
func (checksum Checksum) Validate() error {
var result *multierror.Error
switch checksum.Type {
case ChecksumTypeSHA256: // no op
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "Checksum.Type", checksum.Type, "not a valid checksum type"))
}
return result.ErrorOrNil()
}
func (archive Archive) Validate() error {
var result *multierror.Error
if len(archive.Type) > 0 {
switch archive.Type {
case ArchiveTypeLiteral, ArchiveTypeUrl: // no op
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "Archive.Type", archive.Type, "not a valid archive type"))
}
}
if archive.Checksum != (Checksum{}) {
result = multierror.Append(result, archive.Checksum.Validate())
}
return result.ErrorOrNil()
}
func (ref EnvironmentReference) Validate() error {
var result *multierror.Error
result = multierror.Append(result, ValidateKubeReference("EnvironmentReference", ref.Name, ref.Namespace))
return result.ErrorOrNil()
}
func (ref SecretReference) Validate() error {
var result *multierror.Error
result = multierror.Append(result, ValidateKubeReference("SecretReference", ref.Name, ref.Namespace))
return result.ErrorOrNil()
}
func (ref ConfigMapReference) Validate() error {
var result *multierror.Error
result = multierror.Append(result, ValidateKubeReference("ConfigMapReference", ref.Name, ref.Namespace))
return result.ErrorOrNil()
}
func (spec PackageSpec) Validate() error {
var result *multierror.Error
result = multierror.Append(result, spec.Environment.Validate())
for _, r := range []Archive{spec.Source, spec.Deployment} {
if len(r.URL) > 0 || len(r.Literal) > 0 {
result = multierror.Append(result, r.Validate())
}
}
return result.ErrorOrNil()
}
func (sts PackageStatus) Validate() error {
var result *multierror.Error
switch sts.BuildStatus {
case BuildStatusPending, BuildStatusRunning, BuildStatusSucceeded, BuildStatusFailed, BuildStatusNone: // no op
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "PackageStatus.BuildStatus", sts.BuildStatus, "not a valid build status"))
}
return result.ErrorOrNil()
}
func (ref PackageRef) Validate() error {
var result *multierror.Error
result = multierror.Append(result, ValidateKubeReference("PackageRef", ref.Name, ref.Namespace))
return result.ErrorOrNil()
}
func (ref FunctionPackageRef) Validate() error {
var result *multierror.Error
result = multierror.Append(result, ref.PackageRef.Validate())
return result.ErrorOrNil()
}
func (spec FunctionSpec) Validate() error {
var result *multierror.Error
if spec.Environment != (EnvironmentReference{}) {
result = multierror.Append(result, spec.Environment.Validate())
}
if spec.Package != (FunctionPackageRef{}) {
result = multierror.Append(result, spec.Package.Validate())
}
for _, s := range spec.Secrets {
result = multierror.Append(result, s.Validate())
}
for _, c := range spec.ConfigMaps {
result = multierror.Append(result, c.Validate())
}
if spec.InvokeStrategy != (InvokeStrategy{}) {
result = multierror.Append(result, spec.InvokeStrategy.Validate())
}
return result.ErrorOrNil()
}
func (is InvokeStrategy) Validate() error {
var result *multierror.Error
switch is.StrategyType {
case StrategyTypeExecution: // no op
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "InvokeStrategy.StrategyType", is.StrategyType, "not a valid valid strategy"))
}
result = multierror.Append(result, is.ExecutionStrategy.Validate())
return result.ErrorOrNil()
}
func (es ExecutionStrategy) Validate() error {
var result *multierror.Error
switch es.ExecutorType {
case ExecutorTypeNewdeploy, ExecutorTypePoolmgr: // no op
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "ExecutionStrategy.ExecutorType", es.ExecutorType, "not a valid executor type"))
}
if es.MinScale < 0 {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "ExecutionStrategy.MinScale", es.MinScale, "minimum scale must be greater or equal to 0"))
}
if es.MaxScale < es.MinScale {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "ExecutionStrategy.MaxScale", es.MaxScale, "maximum scale must be greater or equal to minimum scale"))
}
if es.TargetCPUPercent <= 0 || es.TargetCPUPercent > 100 {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "ExecutionStrategy.TargetCPUPercent", es.TargetCPUPercent, "TargetCPUPercent must be a value between 1 - 100"))
}
return result.ErrorOrNil()
}
func (ref FunctionReference) Validate() error {
var result *multierror.Error
switch ref.Type {
case FunctionReferenceTypeFunctionName: // no op
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "FunctionReference.Type", ref.Type, "not a valid function reference type"))
}
result = multierror.Append(result, ValidateKubeName("FunctionReference.Name", ref.Name))
return result.ErrorOrNil()
}
func (runtime Runtime) Validate() error {
var result *multierror.Error
if runtime.LoadEndpointPort > 0 {
result = multierror.Append(result, ValidateKubePort("Runtime.LoadEndpointPort", int(runtime.LoadEndpointPort)))
}
if runtime.FunctionEndpointPort > 0 {
result = multierror.Append(result, ValidateKubePort("Runtime.FunctionEndpointPort", int(runtime.FunctionEndpointPort)))
}
return result.ErrorOrNil()
}
func (builder Builder) Validate() error {
// do nothing for now
return nil
}
func (spec EnvironmentSpec) Validate() error {
var result *multierror.Error
if spec.Version < 1 && spec.Version > 3 {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "EnvironmentSpec.Version", spec.Version, "not a valid environment version"))
}
result = multierror.Append(result, spec.Runtime.Validate())
if spec.Builder != (Builder{}) {
result = multierror.Append(result, spec.Builder.Validate())
}
if len(spec.AllowedFunctionsPerContainer) > 0 {
switch spec.AllowedFunctionsPerContainer {
case AllowedFunctionsPerContainerSingle, AllowedFunctionsPerContainerInfinite: // no op
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "EnvironmentSpec.AllowedFunctionsPerContainer", spec.AllowedFunctionsPerContainer, "not a valid value"))
}
}
if spec.Poolsize < 0 {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "EnvironmentSpec.Poolsize", spec.Poolsize, "Poolsize must be greater or equal to 0"))
}
return result.ErrorOrNil()
}
func (spec HTTPTriggerSpec) Validate() error {
var result *multierror.Error
switch spec.Method {
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch,
http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace: // no op
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "HTTPTriggerSpec.Method", spec.Method, "not a valid HTTP method"))
}
result = multierror.Append(result, spec.FunctionReference.Validate())
if len(spec.Host) > 0 {
e := validation.IsDNS1123Subdomain(spec.Host)
if len(e) > 0 {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "HTTPTriggerSpec.Host", spec.Host, e...))
}
}
return result.ErrorOrNil()
}
func (spec KubernetesWatchTriggerSpec) Validate() error {
var result *multierror.Error
switch strings.ToUpper(spec.Type) {
case "POD", "SERVICE", "REPLICATIONCONTROLLER", "JOB":
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "KubernetesWatchTriggerSpec.Type", spec.Type, "not a valid supported type"))
}
result = multierror.Append(result,
ValidateKubeName("KubernetesWatchTriggerSpec.Namespace", spec.Namespace),
ValidateKubeLabel("KubernetesWatchTriggerSpec.LabelSelector", spec.LabelSelector),
spec.FunctionReference.Validate())
return result.ErrorOrNil()
}
func (spec MessageQueueTriggerSpec) Validate() error {
var result *multierror.Error
result = multierror.Append(result, spec.FunctionReference.Validate())
switch spec.MessageQueueType {
case MessageQueueTypeNats, MessageQueueTypeASQ: // no op
default:
result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "MessageQueueTriggerSpec.MessageQueueType", spec.MessageQueueType, "not a supported message queue type"))
}
if !IsTopicValid(spec.MessageQueueType, spec.Topic) {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "MessageQueueTriggerSpec.Topic", spec.Topic, "not a valid topic"))
}
if len(spec.ResponseTopic) > 0 && !IsTopicValid(spec.MessageQueueType, spec.ResponseTopic) {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "MessageQueueTriggerSpec.ResponseTopic", spec.ResponseTopic, "not a valid topic"))
}
return result.ErrorOrNil()
}
func (spec TimeTriggerSpec) Validate() error {
var result *multierror.Error
err := IsValidCronSpec(spec.Cron)
if err != nil {
result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "TimeTriggerSpec.Cron", spec.Cron, "not a valid cron spec"))
}
result = multierror.Append(result, spec.FunctionReference.Validate())
return result.ErrorOrNil()
}