forked from replicatedhq/libyaml
/
validate.go
1315 lines (1047 loc) · 37.6 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
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package libyaml
import (
"fmt"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/blang/semver"
validator "gopkg.in/go-playground/validator.v8"
)
var (
KeyRegExp = regexp.MustCompile(`^([^\[]+)(?:\[(\d+)\])?$`)
BytesRegExp = regexp.MustCompile(`(?i)^(\d+(?:\.\d{1,3})?)([KMGTPE]B?)$`)
RAMRegExp = regexp.MustCompile(`(?i)^(\d+(?:\.\d{1,3})?)([KMGTPE]iB?)$`)
K8sQuantityRegExp = regexp.MustCompile(`^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$`)
DockerVerLegacyRegExp = regexp.MustCompile(`^1\.([0-9]|(1[0-3]))\.[0-9]+$`)
DockerVerRegExp = regexp.MustCompile(`^[0-9]{2}\.((0[1-9])|(1[0-2]))\.[0-9]+(-(ce|ee))?$`)
registeredValidationFuncs = map[string]validator.Func{}
registeredValidationErrorFuncs = map[string]ValidationErrorFunc{}
)
type ValidationErrorFunc func(formatted string, key string, fieldErr *validator.FieldError, root *RootConfig) error
func RegisterValidation(key string, validatorFn validator.Func, errorFn ValidationErrorFunc) {
registeredValidationFuncs[key] = validatorFn
registeredValidationErrorFuncs[key] = errorFn
}
// RegisterValidations will register all known validation for the libyaml project.
func RegisterValidations(v *validator.Validate) error {
if err := v.RegisterValidation("int", IntValidation); err != nil {
return err
}
if err := v.RegisterValidation("configitemtype", ConfigItemTypeValidation); err != nil {
return err
}
if err := v.RegisterValidation("configitemwhen", ConfigItemWhenValidation); err != nil {
return err
}
if err := v.RegisterValidation("apiversion", SemverValidation); err != nil {
return err
}
if err := v.RegisterValidation("dockerversion", DockerVersionValidation); err != nil {
return err
}
if err := v.RegisterValidation("semver", SemverValidation); err != nil {
return err
}
if err := v.RegisterValidation("semverrange", SemverRangeValidation); err != nil {
return err
}
if err := v.RegisterValidation("hastarget", HasTargetValidation); err != nil {
return err
}
if err := v.RegisterValidation("absolutepath", IsAbsolutePathValidation); err != nil {
return err
}
if err := v.RegisterValidation("isempty", IsEmptyValidation); err != nil {
return err
}
// will handle this in vendor web. this prevents panic from validator.v8 library
if err := v.RegisterValidation("integrationexists", NoopValidation); err != nil {
return err
}
// will handle this in vendor web. this prevents panic from validator.v8 library
if err := v.RegisterValidation("externalregistryexists", NoopValidation); err != nil {
return err
}
if err := v.RegisterValidation("bytes", IsBytesValidation); err != nil {
return err
}
if err := v.RegisterValidation("ram", IsRAMValidation); err != nil {
return err
}
if err := v.RegisterValidation("quantity", IsK8sQuantityValidation); err != nil {
return err
}
if err := v.RegisterValidation("bool", IsBoolValidation); err != nil {
return err
}
if err := v.RegisterValidation("uint", IsUintValidation); err != nil {
return err
}
if err := v.RegisterValidation("tcpport", IsTCPUDPPortValidation); err != nil {
return err
}
if err := v.RegisterValidation("udpport", IsTCPUDPPortValidation); err != nil {
return err
}
if err := v.RegisterValidation("graphiteretention", GraphiteRetentionFormatValidation); err != nil {
return err
}
if err := v.RegisterValidation("graphiteaggregation", GraphiteAggregationFormatValidation); err != nil {
return err
}
if err := v.RegisterValidation("monitorlabelscale", MonitorLabelScaleValidation); err != nil {
return err
}
if err := v.RegisterValidation("fingerprint", Fingerprint); err != nil {
return err
}
if err := v.RegisterValidation("shellalias", ShellAlias); err != nil {
return err
}
if err := v.RegisterValidation("url", URLValid); err != nil {
return err
}
if err := v.RegisterValidation("customrequirementidunique", CustomRequirementIDUnique); err != nil {
return err
}
if err := v.RegisterValidation("mapkeylengthnonzero", MapKeyLengthNonZero); err != nil {
return err
}
if err := v.RegisterValidation("required_minapiversion", RequiredMinAPIVersion); err != nil {
return err
}
// These validations are scheduler specific
schedulerValidations := []string{
"componentexists", "containerexists", "componentcontainer", "containernameexists",
"containernameunique", "requiressubscription", "clusterstrategy",
"volumeoptions",
}
for _, key := range schedulerValidations {
if err := v.RegisterValidation(key, NoopValidation); err != nil {
return fmt.Errorf("register %s: %v", key, err)
}
}
for key, fn := range registeredValidationFuncs {
if err := v.RegisterValidation(key, fn); err != nil {
return err
}
}
return nil
}
// RegisterNativeValidations will register validations for the Native scheduler.
// NOTE: Validations defined here must also be defined in the schedulerValidations slice in the
// RegisterValidations function above.
func RegisterNativeValidations(v *validator.Validate) error {
if err := v.RegisterValidation("componentexists", ComponentExistsValidation); err != nil {
return err
}
if err := v.RegisterValidation("containerexists", ContainerExistsValidation); err != nil {
return err
}
if err := v.RegisterValidation("componentcontainer", ComponentContainerFormatValidation); err != nil {
return err
}
if err := v.RegisterValidation("containernameexists", ContainerNameExists); err != nil {
return err
}
if err := v.RegisterValidation("containernameunique", ContainerNameUnique); err != nil {
return err
}
if err := v.RegisterValidation("requiressubscription", RequiresSubscription); err != nil {
return err
}
if err := v.RegisterValidation("clusterstrategy", ClusterStrategyValidation); err != nil {
return err
}
if err := v.RegisterValidation("volumeoptions", VolumeOptionsValidation); err != nil {
return err
}
return nil
}
// RegisterKubernetesValidations will register validations for the Kubernetes scheduler.
// NOTE: Validations defined here must also be defined in the schedulerValidations slice in the
// RegisterValidations function above.
func RegisterKubernetesValidations(v *validator.Validate) error {
return nil
}
// RegisterSwarmValidations will register validations for the Swarm scheduler.
// NOTE: Validations defined here must also be defined in the schedulerValidations slice in the
// RegisterValidations function above.
func RegisterSwarmValidations(v *validator.Validate) error {
return nil
}
func FormatFieldError(key string, fieldErr *validator.FieldError, root *RootConfig) error {
formatted, err := FormatKey(key, fieldErr, root)
if err != nil {
formatted = key
}
switch fieldErr.Tag {
case "int":
return fmt.Errorf("Value %q must be a valid integer at key %q", fieldErr.Value, formatted)
case "configitemtype":
var validTypes []string
for t := range configItemValidTypes {
validTypes = append(validTypes, t)
}
return fmt.Errorf("Invalid config item type %q at key %q (must be one of %q)", fieldErr.Value, formatted, validTypes)
case "configitemwhen":
return fmt.Errorf("Referenced config item %q in when clause does not exist at key %q", fieldErr.Value, formatted)
case "apiversion":
return fmt.Errorf("A valid \"replicated_api_version\" is required as a root element")
case "dockerversion":
return fmt.Errorf("Invalid Docker version suppiled in %q", formatted)
case "semver":
return fmt.Errorf("Invalid version suppiled in %q", formatted)
case "semverrange":
return fmt.Errorf("Invalid version range suppiled in %q", formatted)
case "hastarget":
return fmt.Errorf("Custom monitor is missing targets at key %q", formatted)
case "componentexists":
return fmt.Errorf("Component %q does not exist at key %q", fieldErr.Value, formatted)
case "containerexists":
return fmt.Errorf("Container %q does not exist at key %q", fieldErr.Value, formatted)
case "componentcontainer":
return fmt.Errorf("Should be in the format \"<component name>,<container image name>\" at key %q", formatted)
case "clusterstrategy":
return fmt.Errorf("Invalid strategy value at key %q, valid values are \"autoscale\", \"random\"", formatted)
case "absolutepath":
return fmt.Errorf("Path %q must be absolute at key %q", fieldErr.Value, formatted)
case "volumeoptions":
return fmt.Errorf("Invalid volume option list at key %q", formatted)
case "isempty":
return fmt.Errorf("Value must be emoty at key %q", formatted)
case "integrationexists":
return fmt.Errorf("Missing integration %q at key %q", fieldErr.Value, formatted)
case "externalregistryexists":
return fmt.Errorf("Missing external registry integration %q at key %q", fieldErr.Value, formatted)
case "bytes":
// omit M and G
return fmt.Errorf("Byte quantity key %q must be a positive decimal with a unit of measurement like MB, or GB", formatted)
case "ram":
// omit M and G
return fmt.Errorf("Byte quantity key %q must be a positive decimal with a unit of measurement like MiB, or GiB", formatted)
case "bytes|ram":
// omit M and G
return fmt.Errorf("Byte quantity key %q must be a positive decimal with a unit of measurement like MB, MiB, GB, or GiB", formatted)
case "quantity", "bytes|quantity", "bytes|ram|quantity":
// omit bytes and ram, prefer quantity
return fmt.Errorf("Quantity at key %q must be expressed as a plain integer, a fixed-point integer, or the power-of-two equivalent (e.g. 128974848, 129e6, 129M, 123Mi)", formatted)
case "bool":
return fmt.Errorf("Value %q must be a valid boolean at key %q", fieldErr.Value, formatted)
case "uint":
return fmt.Errorf("Value %q must be a valid unsigned integer at key %q", fieldErr.Value, formatted)
case "required":
return fmt.Errorf("Value required at key %q", formatted)
case "tcpport":
return fmt.Errorf("A valid port number must be between 0 and 65535: %q", formatted)
case "udpport":
return fmt.Errorf("A valid port number must be between 0 and 65535: %q", formatted)
case "graphiteretention":
return fmt.Errorf("Should be in the new style graphite retention policy at key %q", formatted)
case "graphiteaggregation":
return fmt.Errorf("Valid values for graphite aggregation method are 'average', 'sum', 'min', 'max', 'last' at key %q", formatted)
case "monitorlabelscale":
return fmt.Errorf("Please specify 'metric', 'none', or a floating point number for scale at %q", formatted)
case "fingerprint":
return fmt.Errorf("Please specify a valid RFC4716 key fingerprint at %q", formatted)
case "shellalias":
return fmt.Errorf("Valid characters for shell alias are [a-zA-Z0-9_\\-] at %q", formatted)
case "url":
return fmt.Errorf("A valid URL accessible from the internet is required at %q", formatted)
case "containernameexists":
return fmt.Errorf("Container name %q does not exist at key %q", fieldErr.Value, formatted)
case "containernameunique":
return fmt.Errorf("Container name %q is required to be unique at key %q", fieldErr.Value, formatted)
case "requiressubscription":
return fmt.Errorf("Failed to traverse subscription tree from key %q to container with name %q", formatted, fieldErr.Value)
case "customrequirementidunique":
return fmt.Errorf("Custom requirement %q is required to be unique at key %q", fieldErr.Value, formatted)
case "mapkeylengthnonzero":
return fmt.Errorf("Map keys are required to have a length greater than zero: %q", formatted)
case "required_minapiversion":
return fmt.Errorf("Field is required for \"min_api_version\" < %s at key %q", fieldErr.Param, formatted)
default:
if fn, ok := registeredValidationErrorFuncs[fieldErr.Tag]; ok {
return fn(formatted, key, fieldErr, root)
}
return fmt.Errorf("Validation failed on the %q tag at key %q", fieldErr.Tag, formatted)
}
}
func FormatKey(keyChain string, fieldErr *validator.FieldError, root *RootConfig) (string, error) {
value := reflect.ValueOf(*root)
keys := strings.Split(keyChain, ".")
rest, err := formatKey(keys, value)
if err != nil {
return "", err
}
if rest != "" {
rest = rest[1:]
matches := KeyRegExp.FindStringSubmatch(fieldErr.Field)
if matches[2] != "" {
rest += fmt.Sprintf("[%s]", matches[2])
}
}
return rest, nil
}
func formatKey(keys []string, parent reflect.Value) (string, error) {
if len(keys) == 1 {
return "", nil
}
if parent.Type().Kind() == reflect.Ptr {
parent = parent.Elem()
}
if parent.Type().Kind() == reflect.Struct {
key := keys[1]
matches := KeyRegExp.FindStringSubmatch(key)
field, ok := parent.Type().FieldByName(matches[1])
if !ok {
return "", fmt.Errorf("field %q not found", matches[1])
}
yamlTag := field.Tag.Get("yaml")
yamlTagParts := strings.Split(yamlTag, ",")
if len(yamlTagParts) > 0 {
yamlTag = yamlTagParts[0]
}
value := parent.FieldByName(matches[1])
rest, err := formatKey(keys[1:], value)
if err != nil {
return "", err
}
return "." + yamlTag + rest, nil
} else if parent.Type().Kind() == reflect.Slice {
key := keys[0]
matches := KeyRegExp.FindStringSubmatch(key)
i, err := strconv.Atoi(matches[2])
if err != nil {
return "", err
}
value := parent.Index(i)
rest, err := formatKey(keys, value)
if err != nil {
return "", err
}
return fmt.Sprintf("[%d]", i) + rest, nil
}
return "", nil
}
var intRegex = regexp.MustCompile(`^[-+]?[0-9]+$`)
// IntValidation is the validation function for validating if the current field's value is a valid integer
func IntValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
return intRegex.MatchString(field.String())
}
var configItemValidTypes = map[string]bool{
"text": true,
"label": true,
"password": true,
"file": true,
"bool": true,
"select_one": true,
"select_many": true,
"textarea": true,
"select": true,
"heading": true,
}
// ConfigItemTypeValidation will validate that the type element of a config item is a supported and valid option.
func ConfigItemTypeValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
return false
}
if configItemValidTypes[field.String()] {
return true
}
return false
}
// ConfigItemWhenValidation will validate that the when element of a config item is in a valid format and references other valid, created objects.
func ConfigItemWhenValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
root, ok := topStruct.Interface().(*RootConfig)
if !ok {
// this is an issue with the code and really should be a panic
return true
}
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
var whenValue string
whenValue = field.String()
if whenValue == "" {
return true
}
// new style
if hasReplTemplate(field) {
return true
}
if _, err := strconv.ParseBool(whenValue); err == nil {
return true
}
splitString := "="
if strings.Contains(whenValue, "!=") {
splitString = "!="
}
parts := strings.SplitN(whenValue, splitString, 2)
if len(parts) >= 2 {
whenValue = parts[0]
}
return configItemExists(whenValue, root)
}
func configItemExists(configItemName string, root *RootConfig) bool {
for _, group := range root.ConfigGroups {
for _, item := range group.Items {
if item != nil && item.Name == configItemName {
return true
}
if item != nil {
for _, childItem := range item.Items {
if childItem != nil && childItem.Name == configItemName {
return true
}
}
}
}
}
return false
}
func componentExists(componentName string, root *RootConfig) bool {
for _, component := range root.Components {
if component != nil && component.Name == componentName {
return true
}
}
return false
}
func containerExists(componentName, containerName string, root *RootConfig) bool {
for _, component := range root.Components {
if component != nil && component.Name == componentName {
for _, container := range component.Containers {
if container != nil && container.ImageName == containerName {
return true
}
}
return false
}
}
return false
}
// HasTargetValidation validates that all custom monitors have at least one target defined
func HasTargetValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
customMonitors, ok := field.Interface().([]CustomMonitor)
if !ok {
// this is an issue with the code and really should be a panic
return true
}
for _, monitor := range customMonitors {
if len(monitor.Target) == 0 && len(monitor.Targets) == 0 {
return false
}
}
return true
}
// ComponentExistsValidation will validate that the specified component name is present in the current YAML.
func ComponentExistsValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
// validates that the component exists in the root.Components slice
root, ok := topStruct.Interface().(*RootConfig)
if !ok {
// this is an issue with the code and really should be a panic
return true
}
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
var componentName string
componentName = field.String()
parts := strings.SplitN(componentName, ",", 2)
if len(parts) == 1 {
//This might be a swarm config
//If the scheduler is swarm, accept it
if IsSwarm(root) {
return true
}
}
if len(parts) >= 2 {
componentName = parts[0]
}
return componentExists(componentName, root)
}
// ContainerExistsValidation will validate that the specified container name is present in the current YAML.
func ContainerExistsValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
// validates that the container exists in the root.components.containers slice
root, ok := topStruct.Interface().(*RootConfig)
if !ok {
// this is an issue with the code and really should be a panic
return true
}
var componentName, containerName string
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
containerName = field.String()
if param != "" {
componentField, componentKind, ok := v.GetStructFieldOK(currentStructOrField, param)
if !ok || componentKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
componentName = componentField.String()
} else {
parts := strings.SplitN(containerName, ",", 2)
if len(parts) < 2 {
// let "componentcontainer" validation handle this case
return true
}
componentName = parts[0]
containerName = parts[1]
}
if !componentExists(componentName, root) {
// let "componentexists" validation handle this case
return true
}
return containerExists(componentName, containerName, root)
}
// IsAbsolutePathValidation validates that the format of the field begins with a "/" unless is't a repl template
func IsAbsolutePathValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
return strings.HasPrefix(field.String(), "/") || strings.HasPrefix(field.String(), "{{repl ")
}
// VolumeOptionsValidation checks that volume option list does not contain any conlicting or duplicate options.
func VolumeOptionsValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
// TODO: There are more rules. Look for errInvalidMode in docker source code.
// Specifically, the nocopy option requires some additional checks.
if fieldKind != reflect.Slice {
// this is an issue with the code and really should be a panic
return true
}
options, ok := field.Interface().([]string)
if !ok {
return false
}
// Only one of each is allowed.
rwModes := map[string]bool{"rw": true, "ro": true}
labelModes := map[string]bool{"z": true, "Z": true}
propModes := map[string]bool{"shared": true, "slave": true, "private": true, "rshared": true, "rslave": true, "rprivate": true}
copyModes := map[string]bool{"nocopy": true}
numRwModes := 0
numLabelModes := 0
numPropModes := 0
numCopyModes := 0
for _, o := range options {
switch {
case rwModes[o]:
numRwModes++
case labelModes[o]:
numLabelModes++
case propModes[o]:
numPropModes++
case copyModes[o]:
numCopyModes++
default:
return false
}
}
return numRwModes < 2 && numLabelModes < 2 && numPropModes < 2 && numCopyModes < 2
}
// ComponentContainerFormatValidation will validate that component/container name is in the correct format.
func ComponentContainerFormatValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
// validates the format of the string field conforms to "<component name>,<container image name>"
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
parts := strings.SplitN(field.String(), ",", 2)
if len(parts) == 1 {
//This might be a swarm config
//If the scheduler is swarm, accept it
root, ok := topStruct.Interface().(*RootConfig)
if !ok {
// this is an issue with the code and really should be a panic
return true
}
return IsSwarm(root)
}
if len(parts) < 2 {
return false
}
return true
}
// ClusterStrategyValidation will validate that component/container name is in the correct format.
func ClusterStrategyValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
return field.String() == "autoscale" || field.String() == "random"
}
// DockerVersionValidation will validate that the field is in correct, proper docker version format.
func DockerVersionValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
return true
}
// new style docker version e.g. 17.03.0-ce
if DockerVerRegExp.MatchString(field.String()) {
return true
}
// legacy style docker version e.g. 1.13.1
if DockerVerLegacyRegExp.MatchString(field.String()) {
return true
}
return false
}
// SemverValidation will validate that the field is in correct, proper semver format.
func SemverValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
return true
}
_, err := semver.Make(field.String())
return err == nil
}
// SemverRangeValidation will validate that the field is in correct, proper semver format.
func SemverRangeValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
return true
}
_, err := semver.ParseRange(field.String())
return err == nil
}
// IsBytesValidation will return if a field is a parseable bytes value.
func IsBytesValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
if hasReplTemplate(field) {
// all bets are off
return true
}
parts := BytesRegExp.FindStringSubmatch(strings.TrimSpace(field.String()))
if len(parts) < 3 {
return false
}
value, err := strconv.ParseFloat(parts[1], 64)
if err != nil || value <= 0 {
return false
}
return true
}
// IsRAMValidation will return if a field is a parseable bytes value.
func IsRAMValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
if hasReplTemplate(field) {
// all bets are off
return true
}
parts := RAMRegExp.FindStringSubmatch(strings.TrimSpace(field.String()))
if len(parts) < 3 {
return false
}
value, err := strconv.ParseFloat(parts[1], 64)
if err != nil || value <= 0 {
return false
}
return true
}
// IsK8sQuantityValidation will return if a field is a parseable kubernetes resource.Quantity.
// https://github.com/kubernetes/apimachinery/blob/2de00c78cb6d6127fb51b9531c1b3def1cbcac8c/pkg/api/resource/quantity.go#L144
func IsK8sQuantityValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
if hasReplTemplate(field) {
// all bets are off
return true
}
return K8sQuantityRegExp.MatchString(strings.TrimSpace(field.String()))
}
// IsBoolValidation will return if a string field parses to a bool.
func IsBoolValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
if hasReplTemplate(field) {
// all bets are off
return true
}
_, err := strconv.ParseBool(field.String())
if err != nil {
return false
}
return true
}
// IsUintValidation will return if a string field parses to a uint.
func IsUintValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
// this is an issue with the code and really should be a panic
return true
}
if hasReplTemplate(field) {
// all bets are off
return true
}
_, err := strconv.ParseUint(field.String(), 10, 64)
if err != nil {
return false
}
return true
}
// IsTCPUDPPortValidation will return true if a field value is also a valid TCP port.
func IsTCPUDPPortValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.Int32 {
// this is an issue with the code and really should be a panic
return true
}
port := field.Int()
return 0 <= port && port <= 65535
}
func IsEmptyValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
return true
}
valueStr := field.String()
if valueStr == "" {
return true
}
return false
}
// NoopValidation will return true always.
func NoopValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
return true
}
// GraphiteRetentionFormatValidation will return true if the field value is a valid graphite retention value.
func GraphiteRetentionFormatValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
return true
}
valueStr := field.String()
if valueStr == "" {
return true
}
validate := func(amount, unit string) bool {
_, err := strconv.Atoi(amount)
if err != nil {
return false
}
switch unit {
case "s", "m", "h", "d", "y":
return true
default:
return false
}
}
// Example: 15s:7d,1m:21d,15m:5y
periods := strings.Split(valueStr, ",")
for _, period := range periods {
periodParts := strings.Split(period, ":")
if len(periodParts) != 2 {
return false
}
for _, part := range periodParts {
partLen := len(part)
if partLen < 2 {
return false
}
if !validate(part[:partLen-1], part[partLen-1:]) {
return false
}
}
}
return true
}
// GraphiteAggregationFormatValidation will return true if the field value is a valid value for the a graphite aggregation.
func GraphiteAggregationFormatValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
return true
}
valueStr := field.String()
if valueStr == "" {
return true
}
switch valueStr {
case "average", "sum", "min", "max", "last":
return true
default:
return false
}
}
// MonitorLabelScaleValidation will return true only if the value is a parseable and correct value for the scale.
func MonitorLabelScaleValidation(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
if fieldKind != reflect.String {
return true
}
valueStr := field.String()
if valueStr == "" {
return true
}
switch valueStr {