forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
master.go
843 lines (702 loc) · 39.2 KB
/
master.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
package validation
import (
"fmt"
"net"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"time"
knet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/sets"
kuval "k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/validation/field"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
auditvalidation "k8s.io/apiserver/pkg/apis/audit/validation"
auditpolicy "k8s.io/apiserver/pkg/audit/policy"
"k8s.io/client-go/tools/clientcmd"
apiserveroptions "k8s.io/kubernetes/cmd/kube-apiserver/app/options"
kcmoptions "k8s.io/kubernetes/cmd/kube-controller-manager/app/options"
kvalidation "k8s.io/kubernetes/pkg/api/validation"
"k8s.io/kubernetes/pkg/serviceaccount"
"github.com/openshift/origin/pkg/cmd/server/api"
"github.com/openshift/origin/pkg/cmd/server/bootstrappolicy"
"github.com/openshift/origin/pkg/cmd/server/cm"
"github.com/openshift/origin/pkg/security/mcs"
"github.com/openshift/origin/pkg/security/uid"
"github.com/openshift/origin/pkg/util/labelselector"
)
// TODO: this should just be two return arrays, no need to be clever
type ValidationResults struct {
Warnings field.ErrorList
Errors field.ErrorList
}
func (r *ValidationResults) Append(additionalResults ValidationResults) {
r.AddErrors(additionalResults.Errors...)
r.AddWarnings(additionalResults.Warnings...)
}
func (r *ValidationResults) AddErrors(errors ...*field.Error) {
if len(errors) == 0 {
return
}
r.Errors = append(r.Errors, errors...)
}
func (r *ValidationResults) AddWarnings(warnings ...*field.Error) {
if len(warnings) == 0 {
return
}
r.Warnings = append(r.Warnings, warnings...)
}
func ValidateMasterConfig(config *api.MasterConfig, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
if _, urlErrs := ValidateURL(config.MasterPublicURL, fldPath.Child("masterPublicURL")); len(urlErrs) > 0 {
validationResults.AddErrors(urlErrs...)
}
switch {
case config.ControllerLeaseTTL > 300,
config.ControllerLeaseTTL < -1,
config.ControllerLeaseTTL > 0 && config.ControllerLeaseTTL < 10:
validationResults.AddErrors(field.Invalid(fldPath.Child("controllerLeaseTTL"), config.ControllerLeaseTTL, "TTL must be -1 (disabled), 0 (default), or between 10 and 300 seconds"))
}
validationResults.AddErrors(ValidateDisabledFeatures(config.DisabledFeatures, fldPath.Child("disabledFeatures"))...)
if config.AssetConfig != nil {
assetConfigPath := fldPath.Child("assetConfig")
validationResults.Append(ValidateAssetConfig(config.AssetConfig, assetConfigPath))
colocated := config.AssetConfig.ServingInfo.BindAddress == config.ServingInfo.BindAddress
if colocated {
publicURL, _ := url.Parse(config.AssetConfig.PublicURL)
if publicURL.Path == "/" {
validationResults.AddErrors(field.Invalid(assetConfigPath.Child("publicURL"), config.AssetConfig.PublicURL, "path can not be / when colocated with master API"))
}
// Warn if they have customized the asset certificates in ways that will be ignored
if !reflect.DeepEqual(config.AssetConfig.ServingInfo.ServerCert, config.ServingInfo.ServerCert) ||
!reflect.DeepEqual(config.AssetConfig.ServingInfo.NamedCertificates, config.ServingInfo.NamedCertificates) {
validationResults.AddWarnings(field.Invalid(assetConfigPath.Child("servingInfo"), "<not displayed>", "changes to assetConfig certificate configuration are not used when colocated with master API"))
}
}
if config.OAuthConfig != nil {
if config.OAuthConfig.AssetPublicURL != config.AssetConfig.PublicURL {
validationResults.AddErrors(
field.Invalid(assetConfigPath.Child("publicURL"), config.AssetConfig.PublicURL, "must match oauthConfig.assetPublicURL"),
field.Invalid(fldPath.Child("oauthConfig", "assetPublicURL"), config.OAuthConfig.AssetPublicURL, "must match assetConfig.publicURL"),
)
}
}
// TODO warn when the CORS list does not include the assetConfig.publicURL host:port
// only warn cause they could handle CORS headers themselves in a proxy
}
if config.DNSConfig != nil {
dnsConfigPath := fldPath.Child("dnsConfig")
validationResults.AddErrors(ValidateHostPort(config.DNSConfig.BindAddress, dnsConfigPath.Child("bindAddress"))...)
switch config.DNSConfig.BindNetwork {
case "tcp", "tcp4", "tcp6":
default:
validationResults.AddErrors(field.Invalid(dnsConfigPath.Child("bindNetwork"), config.DNSConfig.BindNetwork, "must be 'tcp', 'tcp4', or 'tcp6'"))
}
}
if config.EtcdConfig != nil {
etcdConfigErrs := ValidateEtcdConfig(config.EtcdConfig, fldPath.Child("etcdConfig"))
validationResults.Append(etcdConfigErrs)
if len(etcdConfigErrs.Errors) == 0 {
// Validate the etcdClientInfo with the internal etcdConfig
validationResults.AddErrors(ValidateEtcdConnectionInfo(config.EtcdClientInfo, config.EtcdConfig, fldPath.Child("etcdClientInfo"))...)
} else {
// Validate the etcdClientInfo by itself
validationResults.AddErrors(ValidateEtcdConnectionInfo(config.EtcdClientInfo, nil, fldPath.Child("etcdClientInfo"))...)
}
} else {
// Validate the etcdClientInfo by itself
validationResults.AddErrors(ValidateEtcdConnectionInfo(config.EtcdClientInfo, nil, fldPath.Child("etcdClientInfo"))...)
}
validationResults.AddErrors(ValidateEtcdStorageConfig(config.EtcdStorageConfig, fldPath.Child("etcdStorageConfig"))...)
validationResults.AddErrors(ValidateImageConfig(config.ImageConfig, fldPath.Child("imageConfig"))...)
validationResults.AddErrors(ValidateImagePolicyConfig(config.ImagePolicyConfig, fldPath.Child("imagePolicyConfig"))...)
validationResults.AddErrors(ValidateKubeletConnectionInfo(config.KubeletClientInfo, fldPath.Child("kubeletClientInfo"))...)
builtInKubernetes := config.KubernetesMasterConfig != nil
if config.KubernetesMasterConfig != nil {
validationResults.Append(ValidateKubernetesMasterConfig(config.KubernetesMasterConfig, fldPath.Child("kubernetesMasterConfig")))
}
if (config.KubernetesMasterConfig == nil) && (len(config.MasterClients.ExternalKubernetesKubeConfig) == 0) {
validationResults.AddErrors(field.Invalid(fldPath.Child("kubernetesMasterConfig"), config.KubernetesMasterConfig, "either kubernetesMasterConfig or masterClients.externalKubernetesKubeConfig must have a value"))
}
if (config.KubernetesMasterConfig != nil) && (len(config.MasterClients.ExternalKubernetesKubeConfig) != 0) {
validationResults.AddErrors(field.Invalid(fldPath.Child("kubernetesMasterConfig"), config.KubernetesMasterConfig, "kubernetesMasterConfig and masterClients.externalKubernetesKubeConfig are mutually exclusive"))
}
if len(config.NetworkConfig.ServiceNetworkCIDR) > 0 {
if _, _, err := net.ParseCIDR(strings.TrimSpace(config.NetworkConfig.ServiceNetworkCIDR)); err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("networkConfig", "serviceNetworkCIDR"), config.NetworkConfig.ServiceNetworkCIDR, "must be a valid CIDR notation IP range (e.g. 172.30.0.0/16)"))
} else if config.KubernetesMasterConfig != nil && len(config.KubernetesMasterConfig.ServicesSubnet) > 0 && config.KubernetesMasterConfig.ServicesSubnet != config.NetworkConfig.ServiceNetworkCIDR {
validationResults.AddErrors(field.Invalid(fldPath.Child("networkConfig", "serviceNetworkCIDR"), config.NetworkConfig.ServiceNetworkCIDR, fmt.Sprintf("must match kubernetesMasterConfig.servicesSubnet value of %q", config.KubernetesMasterConfig.ServicesSubnet)))
}
}
if len(config.NetworkConfig.ExternalIPNetworkCIDRs) > 0 {
for i, s := range config.NetworkConfig.ExternalIPNetworkCIDRs {
s = strings.TrimPrefix(s, "!")
if _, _, err := net.ParseCIDR(s); err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("networkConfig", "externalIPNetworkCIDRs").Index(i), config.NetworkConfig.ExternalIPNetworkCIDRs[i], "must be a valid CIDR notation IP range (e.g. 172.30.0.0/16) with an optional leading !"))
}
}
}
validationResults.AddErrors(ValidateIngressIPNetworkCIDR(config, fldPath.Child("networkConfig", "ingressIPNetworkCIDR").Index(0))...)
validationResults.Append(ValidateDeprecatedClusterNetworkConfig(config, fldPath.Child("networkConfig")))
validationResults.AddErrors(ValidateKubeConfig(config.MasterClients.OpenShiftLoopbackKubeConfig, fldPath.Child("masterClients", "openShiftLoopbackKubeConfig"))...)
if len(config.MasterClients.ExternalKubernetesKubeConfig) > 0 {
validationResults.AddErrors(ValidateKubeConfig(config.MasterClients.ExternalKubernetesKubeConfig, fldPath.Child("masterClients", "externalKubernetesKubeConfig"))...)
}
validationResults.AddErrors(ValidatePolicyConfig(config.PolicyConfig, fldPath.Child("policyConfig"))...)
if config.OAuthConfig != nil {
validationResults.Append(ValidateOAuthConfig(config.OAuthConfig, fldPath.Child("oauthConfig")))
}
validationResults.Append(ValidateServiceAccountConfig(config.ServiceAccountConfig, builtInKubernetes, fldPath.Child("serviceAccountConfig")))
validationResults.Append(ValidateHTTPServingInfo(config.ServingInfo, fldPath.Child("servingInfo")))
validationResults.Append(ValidateProjectConfig(config.ProjectConfig, fldPath.Child("projectConfig")))
validationResults.AddErrors(ValidateRoutingConfig(config.RoutingConfig, fldPath.Child("routingConfig"))...)
validationResults.Append(ValidateAPILevels(config.APILevels, api.KnownOpenShiftAPILevels, api.DeadOpenShiftAPILevels, fldPath.Child("apiLevels")))
if config.AdmissionConfig.PluginConfig != nil {
validationResults.Append(ValidateAdmissionPluginConfig(config.AdmissionConfig.PluginConfig, fldPath.Child("admissionConfig", "pluginConfig")))
}
if len(config.AdmissionConfig.PluginOrderOverride) != 0 {
validationResults.AddWarnings(field.Invalid(fldPath.Child("admissionConfig", "pluginOrderOverride"), config.AdmissionConfig.PluginOrderOverride, "specified admission ordering is being phased out. Convert to DefaultAdmissionConfig in admissionConfig.pluginConfig."))
}
validationResults.Append(ValidateControllerConfig(config.ControllerConfig, fldPath.Child("controllerConfig")))
validationResults.Append(ValidateAuditConfig(config.AuditConfig, fldPath.Child("auditConfig")))
validationResults.Append(ValidateMasterAuthConfig(config.AuthConfig, fldPath.Child("authConfig")))
validationResults.Append(ValidateAggregatorConfig(config.AggregatorConfig, fldPath.Child("aggregatorConfig")))
return validationResults
}
func ValidateMasterAuthConfig(config api.MasterAuthConfig, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
if config.RequestHeader == nil {
return validationResults
}
if len(config.RequestHeader.ClientCA) == 0 {
validationResults.AddErrors(field.Required(fldPath.Child("requestHeader.clientCA"), "must be specified for a secure connection"))
}
if len(config.RequestHeader.ClientCommonNames) == 0 {
validationResults.AddErrors(field.Required(fldPath.Child("requestHeader.clientCommonNames"), "must be specified for a secure connection"))
}
if len(config.RequestHeader.UsernameHeaders) == 0 {
validationResults.AddErrors(field.Required(fldPath.Child("requestHeader.usernameHeaders"), "must be specified for a secure connection"))
}
if len(config.RequestHeader.GroupHeaders) == 0 {
validationResults.AddErrors(field.Required(fldPath.Child("requestHeader.groupHeaders"), "must be specified for a secure connection"))
}
if len(config.RequestHeader.ExtraHeaderPrefixes) == 0 {
validationResults.AddErrors(field.Required(fldPath.Child("requestHeader.extraHeaderPrefixes"), "must be specified for a secure connection"))
}
return validationResults
}
func ValidateAggregatorConfig(config api.AggregatorConfig, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
validationResults.AddErrors(ValidateCertInfo(config.ProxyClientInfo, false, fldPath.Child("proxyClientInfo"))...)
if len(config.ProxyClientInfo.CertFile) == 0 && len(config.ProxyClientInfo.KeyFile) == 0 {
validationResults.AddWarnings(field.Invalid(fldPath.Child("proxyClientInfo"), "", "if no client certificate is specified, the aggregator will be unable to proxy to remote servers"))
}
return validationResults
}
func ValidateAuditConfig(config api.AuditConfig, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
if !config.Enabled {
return validationResults
}
if len(config.AuditFilePath) == 0 {
// for backwards compatibility reasons we can't error this out
validationResults.AddWarnings(field.Required(fldPath.Child("auditFilePath"), "audit can not be logged to a separate file"))
}
if config.MaximumFileRetentionDays < 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("maximumFileRetentionDays"), config.MaximumFileRetentionDays, "must be greater than or equal to 0"))
}
if config.MaximumRetainedFiles < 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("maximumRetainedFiles"), config.MaximumRetainedFiles, "must be greater than or equal to 0"))
}
if config.MaximumFileSizeMegabytes < 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("maximumFileSizeMegabytes"), config.MaximumFileSizeMegabytes, "must be greater than or equal to 0"))
}
// setting policy file will turn the advanced auditing on
if config.PolicyConfiguration != nil && len(config.PolicyFile) > 0 {
validationResults.AddErrors(field.Forbidden(fldPath.Child("policyFile"), "both policyFile and policyConfiguration cannot be specified"))
}
if config.PolicyConfiguration != nil || len(config.PolicyFile) > 0 {
if config.PolicyConfiguration == nil {
policy, err := auditpolicy.LoadPolicyFromFile(config.PolicyFile)
if err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("policyFile"), config.PolicyFile, err.Error()))
}
if policy == nil || len(policy.Rules) == 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("policyFile"), config.PolicyFile, "a policy file with 0 policies is not valid"))
}
} else {
policyConfiguration, ok := config.PolicyConfiguration.(*auditinternal.Policy)
if !ok {
validationResults.AddErrors(field.Invalid(fldPath.Child("policyConfiguration"), config.PolicyConfiguration, "must be of type audit/v1alpha1.Policy"))
} else {
if err := auditvalidation.ValidatePolicy(policyConfiguration); err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("policyConfiguration"), config.PolicyConfiguration, err.ToAggregate().Error()))
}
if len(policyConfiguration.Rules) == 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("policyConfiguration"), config.PolicyFile, "a policy configuration with 0 policies is not valid"))
}
}
}
if len(config.AuditFilePath) == 0 {
validationResults.AddErrors(field.Required(fldPath.Child("auditFilePath"), "advanced audit requires a separate log file"))
}
switch config.LogFormat {
case api.LogFormatLegacy, api.LogFormatJson:
// ok
default:
validationResults.AddErrors(field.NotSupported(fldPath.Child("logFormat"), config.LogFormat, []string{string(api.LogFormatLegacy), string(api.LogFormatJson)}))
}
if len(config.WebHookKubeConfig) > 0 {
switch config.WebHookMode {
case api.WebHookModeBatch, api.WebHookModeBlocking:
// ok
default:
validationResults.AddErrors(field.NotSupported(fldPath.Child("webHookMode"), config.WebHookMode, []string{string(api.WebHookModeBatch), string(api.WebHookModeBlocking)}))
}
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRules.ExplicitPath = config.WebHookKubeConfig
loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
if _, err := loader.ClientConfig(); err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("webHookKubeConfig"), config.WebHookKubeConfig, err.Error()))
}
} else if len(config.WebHookMode) > 0 {
validationResults.AddErrors(field.Required(fldPath.Child("webHookKubeConfig"), "must be specified when webHookMode is set"))
}
}
return validationResults
}
func ValidateControllerConfig(config api.ControllerConfig, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
if election := config.Election; election != nil {
if len(election.LockName) == 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("election", "lockName"), election.LockName, "may not be empty"))
}
for _, msg := range kvalidation.ValidateServiceName(election.LockName, false) {
validationResults.AddErrors(field.Invalid(fldPath.Child("election", "lockName"), election.LockName, msg))
}
if len(election.LockNamespace) == 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("election", "lockNamespace"), election.LockNamespace, "may not be empty"))
}
for _, msg := range kvalidation.ValidateNamespaceName(election.LockNamespace, false) {
validationResults.AddErrors(field.Invalid(fldPath.Child("election", "lockNamespace"), election.LockNamespace, msg))
}
if len(election.LockResource.Resource) == 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("election", "lockResource", "resource"), election.LockResource.Resource, "may not be empty"))
}
}
if config.ServiceServingCert.Signer == nil {
validationResults.AddWarnings(field.Required(fldPath.Child("serviceServingCert", "signer"), "required for the service serving cert signer; automatic serving certificate signing will fail"))
} else {
validationResults.AddErrors(ValidateCertInfo(*config.ServiceServingCert.Signer, true, fldPath.Child("serviceServingCert.signer"))...)
}
return validationResults
}
func ValidateAPILevels(apiLevels []string, knownAPILevels, deadAPILevels []string, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
if len(apiLevels) == 0 {
validationResults.AddErrors(field.Required(fldPath, ""))
}
deadLevels := sets.NewString(deadAPILevels...)
knownLevels := sets.NewString(knownAPILevels...)
for i, apiLevel := range apiLevels {
idxPath := fldPath.Index(i)
if deadLevels.Has(apiLevel) {
validationResults.AddWarnings(field.Invalid(idxPath, apiLevel, "unsupported level"))
}
if !knownLevels.Has(apiLevel) {
validationResults.AddWarnings(field.Invalid(idxPath, apiLevel, "unknown level"))
}
}
return validationResults
}
func ValidateEtcdStorageConfig(config api.EtcdStorageConfig, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateStorageVersionLevel(
config.KubernetesStorageVersion,
api.KnownKubernetesStorageVersionLevels,
api.DeadKubernetesStorageVersionLevels,
fldPath.Child("kubernetesStorageVersion"))...)
allErrs = append(allErrs, ValidateStorageVersionLevel(
config.OpenShiftStorageVersion,
api.KnownOpenShiftStorageVersionLevels,
api.DeadOpenShiftStorageVersionLevels,
fldPath.Child("openShiftStorageVersion"))...)
if strings.ContainsRune(config.KubernetesStoragePrefix, '%') {
allErrs = append(allErrs, field.Invalid(fldPath.Child("kubernetesStoragePrefix"), config.KubernetesStoragePrefix, "the '%' character may not be used in etcd path prefixes"))
}
if strings.ContainsRune(config.OpenShiftStoragePrefix, '%') {
allErrs = append(allErrs, field.Invalid(fldPath.Child("openShiftStoragePrefix"), config.OpenShiftStoragePrefix, "the '%' character may not be used in etcd path prefixes"))
}
return allErrs
}
func ValidateStorageVersionLevel(level string, knownAPILevels, deadAPILevels []string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(level) == 0 {
allErrs = append(allErrs, field.Required(fldPath, ""))
return allErrs
}
supportedLevels := sets.NewString(knownAPILevels...)
supportedLevels.Delete(deadAPILevels...)
if !supportedLevels.Has(level) {
allErrs = append(allErrs, field.NotSupported(fldPath, level, supportedLevels.List()))
}
return allErrs
}
func ValidateServiceAccountConfig(config api.ServiceAccountConfig, builtInKubernetes bool, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
managedNames := sets.NewString(config.ManagedNames...)
managedNamesPath := fldPath.Child("managedNames")
if !managedNames.Has(bootstrappolicy.BuilderServiceAccountName) {
validationResults.AddWarnings(field.Invalid(managedNamesPath, "", fmt.Sprintf("missing %q, which will require manual creation in each namespace before builds can run", bootstrappolicy.BuilderServiceAccountName)))
}
if !managedNames.Has(bootstrappolicy.DeployerServiceAccountName) {
validationResults.AddWarnings(field.Invalid(managedNamesPath, "", fmt.Sprintf("missing %q, which will require manual creation in each namespace before deployments can run", bootstrappolicy.DeployerServiceAccountName)))
}
if builtInKubernetes && !managedNames.Has(bootstrappolicy.DefaultServiceAccountName) {
validationResults.AddWarnings(field.Invalid(managedNamesPath, "", fmt.Sprintf("missing %q, which will prevent creation of pods that do not specify a valid service account", bootstrappolicy.DefaultServiceAccountName)))
}
for i, name := range config.ManagedNames {
if reasons := kvalidation.ValidateServiceAccountName(name, false); len(reasons) != 0 {
validationResults.AddErrors(field.Invalid(managedNamesPath.Index(i), name, strings.Join(reasons, ", ")))
}
}
if len(config.PrivateKeyFile) > 0 {
privateKeyFilePath := fldPath.Child("privateKeyFile")
if fileErrs := ValidateFile(config.PrivateKeyFile, privateKeyFilePath); len(fileErrs) > 0 {
validationResults.AddErrors(fileErrs...)
} else if _, err := serviceaccount.ReadPrivateKey(config.PrivateKeyFile); err != nil {
validationResults.AddErrors(field.Invalid(privateKeyFilePath, config.PrivateKeyFile, err.Error()))
}
} else if builtInKubernetes {
validationResults.AddWarnings(field.Invalid(fldPath.Child("privateKeyFile"), "", "no service account tokens will be generated, which could prevent builds and deployments from working"))
}
if len(config.PublicKeyFiles) == 0 {
validationResults.AddWarnings(field.Invalid(fldPath.Child("publicKeyFiles"), "", "no service account tokens will be accepted by the API, which will prevent builds and deployments from working"))
}
for i, publicKeyFile := range config.PublicKeyFiles {
idxPath := fldPath.Child("publicKeyFiles").Index(i)
if fileErrs := ValidateFile(publicKeyFile, idxPath); len(fileErrs) > 0 {
validationResults.AddErrors(fileErrs...)
} else if _, err := serviceaccount.ReadPublicKeys(publicKeyFile); err != nil {
validationResults.AddErrors(field.Invalid(idxPath, publicKeyFile, err.Error()))
}
}
if len(config.MasterCA) > 0 {
validationResults.AddErrors(ValidateFile(config.MasterCA, fldPath.Child("masterCA"))...)
} else if builtInKubernetes {
validationResults.AddWarnings(field.Invalid(fldPath.Child("masterCA"), "", "master CA information will not be automatically injected into pods, which will prevent verification of the API server from inside a pod"))
}
return validationResults
}
func ValidateAssetConfig(config *api.AssetConfig, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
validationResults.Append(ValidateHTTPServingInfo(config.ServingInfo, fldPath.Child("servingInfo")))
if len(config.LogoutURL) > 0 {
_, urlErrs := ValidateURL(config.LogoutURL, fldPath.Child("logoutURL"))
if len(urlErrs) > 0 {
validationResults.AddErrors(urlErrs...)
}
}
urlObj, urlErrs := ValidateURL(config.PublicURL, fldPath.Child("publicURL"))
if len(urlErrs) > 0 {
validationResults.AddErrors(urlErrs...)
}
if urlObj != nil {
if !strings.HasSuffix(urlObj.Path, "/") {
validationResults.AddErrors(field.Invalid(fldPath.Child("publicURL"), config.PublicURL, "must have a trailing slash in path"))
}
}
if _, urlErrs := ValidateURL(config.MasterPublicURL, fldPath.Child("masterPublicURL")); len(urlErrs) > 0 {
validationResults.AddErrors(urlErrs...)
}
if len(config.LoggingPublicURL) > 0 {
if _, loggingURLErrs := ValidateSecureURL(config.LoggingPublicURL, fldPath.Child("loggingPublicURL")); len(loggingURLErrs) > 0 {
validationResults.AddErrors(loggingURLErrs...)
}
} else {
validationResults.AddWarnings(field.Invalid(fldPath.Child("loggingPublicURL"), "", "required to view aggregated container logs in the console"))
}
if len(config.MetricsPublicURL) > 0 {
if _, metricsURLErrs := ValidateSecureURL(config.MetricsPublicURL, fldPath.Child("metricsPublicURL")); len(metricsURLErrs) > 0 {
validationResults.AddErrors(metricsURLErrs...)
}
} else {
validationResults.AddWarnings(field.Invalid(fldPath.Child("metricsPublicURL"), "", "required to view cluster metrics in the console"))
}
for i, scriptFile := range config.ExtensionScripts {
validationResults.AddErrors(ValidateFile(scriptFile, fldPath.Child("extensionScripts").Index(i))...)
}
for i, stylesheetFile := range config.ExtensionStylesheets {
validationResults.AddErrors(ValidateFile(stylesheetFile, fldPath.Child("extensionStylesheets").Index(i))...)
}
nameTaken := map[string]bool{}
for i, extConfig := range config.Extensions {
idxPath := fldPath.Child("extensions").Index(i)
extConfigErrors := ValidateAssetExtensionsConfig(extConfig, idxPath)
validationResults.AddErrors(extConfigErrors...)
if nameTaken[extConfig.Name] {
dupError := field.Invalid(idxPath.Child("name"), extConfig.Name, "duplicate extension name")
validationResults.AddErrors(dupError)
} else {
nameTaken[extConfig.Name] = true
}
}
return validationResults
}
var extNameExp = regexp.MustCompile(`^[A-Za-z0-9_]+$`)
func ValidateAssetExtensionsConfig(extConfig api.AssetExtensionsConfig, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateDir(extConfig.SourceDirectory, fldPath.Child("sourceDirectory"))...)
if len(extConfig.Name) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("name"), ""))
} else if !extNameExp.MatchString(extConfig.Name) {
allErrs = append(allErrs, field.Invalid(fldPath.Child("name"), extConfig.Name, fmt.Sprintf("does not match %v", extNameExp)))
}
return allErrs
}
func ValidateImageConfig(config api.ImageConfig, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(config.Format) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("format"), ""))
}
return allErrs
}
func ValidateImagePolicyConfig(config api.ImagePolicyConfig, fldPath *field.Path) field.ErrorList {
errs := field.ErrorList{}
if config.MaxImagesBulkImportedPerRepository == 0 || config.MaxImagesBulkImportedPerRepository < -1 {
errs = append(errs, field.Invalid(fldPath.Child("maxImagesBulkImportedPerRepository"), config.MaxImagesBulkImportedPerRepository, "must be a positive integer or -1"))
}
if config.ScheduledImageImportMinimumIntervalSeconds <= 0 {
errs = append(errs, field.Invalid(fldPath.Child("scheduledImageImportMinimumIntervalSeconds"), config.ScheduledImageImportMinimumIntervalSeconds, "must be a positive integer"))
}
if config.MaxScheduledImageImportsPerMinute == 0 || config.MaxScheduledImageImportsPerMinute < -1 {
errs = append(errs, field.Invalid(fldPath.Child("maxScheduledImageImportsPerMinute"), config.MaxScheduledImageImportsPerMinute, "must be a positive integer or -1"))
}
if config.AllowedRegistriesForImport != nil {
for i, registry := range *config.AllowedRegistriesForImport {
if len(registry.DomainName) == 0 {
errs = append(errs, field.Invalid(fldPath.Index(i).Child("allowedRegistriesForImport", "domainName"), registry.DomainName, "cannot be an empty string"))
}
parts := strings.Split(registry.DomainName, ":")
// Check for ':8080'
if len(parts) == 0 || len(parts[0]) == 0 {
errs = append(errs, field.Invalid(fldPath.Index(i).Child("allowedRegistriesForImport", "domainName"), registry.DomainName, "invalid domain specified, must be registry.url.local[:port]"))
}
// Check for 'foo:bar:1234'
if len(parts) > 2 {
errs = append(errs, field.Invalid(fldPath.Index(i).Child("allowedRegistriesForImport", "domainName"), registry.DomainName, "invalid format, must be registry.url.local[:port]"))
}
// Check for 'foo:bar'
if len(parts) == 2 {
if _, err := strconv.Atoi(parts[1]); err != nil {
errs = append(errs, field.Invalid(fldPath.Index(i).Child("allowedRegistriesForImport", "domainName"), registry.DomainName, "invalid port format, must be a number"))
}
}
}
}
return errs
}
func ValidateKubeletConnectionInfo(config api.KubeletConnectionInfo, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if config.Port == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("port"), ""))
}
if len(config.CA) > 0 {
allErrs = append(allErrs, ValidateFile(config.CA, fldPath.Child("ca"))...)
}
allErrs = append(allErrs, ValidateCertInfo(config.ClientCert, false, fldPath)...)
return allErrs
}
func ValidateKubernetesMasterConfig(config *api.KubernetesMasterConfig, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
if len(config.MasterIP) > 0 {
validationResults.AddErrors(ValidateSpecifiedIP(config.MasterIP, fldPath.Child("masterIP"))...)
}
if config.MasterCount == 0 || config.MasterCount < -1 {
validationResults.AddErrors(field.Invalid(fldPath.Child("masterCount"), config.MasterCount, "must be a positive integer or -1"))
}
validationResults.AddErrors(ValidateCertInfo(config.ProxyClientInfo, false, fldPath.Child("proxyClientInfo"))...)
if len(config.ProxyClientInfo.CertFile) == 0 && len(config.ProxyClientInfo.KeyFile) == 0 {
validationResults.AddWarnings(field.Invalid(fldPath.Child("proxyClientInfo"), "", "if no client certificate is specified, TLS pods and services cannot validate requests came from the proxy"))
}
if len(config.ServicesSubnet) > 0 {
if _, _, err := net.ParseCIDR(strings.TrimSpace(config.ServicesSubnet)); err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("servicesSubnet"), config.ServicesSubnet, "must be a valid CIDR notation IP range (e.g. 172.30.0.0/16)"))
}
}
if len(config.ServicesNodePortRange) > 0 {
if _, err := knet.ParsePortRange(strings.TrimSpace(config.ServicesNodePortRange)); err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("servicesNodePortRange"), config.ServicesNodePortRange, "must be a valid port range (e.g. 30000-32000)"))
}
}
if len(config.SchedulerConfigFile) > 0 {
validationResults.AddErrors(ValidateFile(config.SchedulerConfigFile, fldPath.Child("schedulerConfigFile"))...)
}
for i, nodeName := range config.StaticNodeNames {
if len(nodeName) == 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("staticNodeName").Index(i), nodeName, "may not be empty"))
} else {
validationResults.AddWarnings(field.Invalid(fldPath.Child("staticNodeName").Index(i), nodeName, "static nodes are not supported"))
}
}
if len(config.PodEvictionTimeout) > 0 {
if _, err := time.ParseDuration(config.PodEvictionTimeout); err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("podEvictionTimeout"), config.PodEvictionTimeout, "must be a valid time duration string (e.g. '300ms' or '2m30s'). Valid time units are 'ns', 'us', 'ms', 's', 'm', 'h'"))
}
}
for group, versions := range config.DisabledAPIGroupVersions {
keyPath := fldPath.Child("disabledAPIGroupVersions").Key(group)
if !api.KnownKubeAPIGroups.Has(group) {
validationResults.AddWarnings(field.NotSupported(keyPath, group, api.KnownKubeAPIGroups.List()))
continue
}
allowedVersions := sets.NewString(api.KubeAPIGroupsToAllowedVersions[group]...)
for i, version := range versions {
if version == "*" {
continue
}
if !allowedVersions.Has(version) {
validationResults.AddWarnings(field.NotSupported(keyPath.Index(i), version, allowedVersions.List()))
}
}
}
if config.AdmissionConfig.PluginConfig != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("admissionConfig", "pluginConfig"), config.AdmissionConfig.PluginConfig, "separate admission chains are no longer allowed. Convert to admissionConfig.pluginConfig."))
}
if len(config.AdmissionConfig.PluginOrderOverride) != 0 {
validationResults.AddErrors(field.Invalid(fldPath.Child("admissionConfig", "pluginOrderOverride"), config.AdmissionConfig.PluginOrderOverride, "separate admission chains are no longer allowed. Convert to DefaultAdmissionConfig in admissionConfig.pluginConfig."))
}
validationResults.Append(ValidateAPIServerExtendedArguments(config.APIServerArguments, fldPath.Child("apiServerArguments")))
validationResults.AddErrors(ValidateControllerExtendedArguments(config.ControllerArguments, fldPath.Child("controllerArguments"))...)
return validationResults
}
func ValidatePolicyConfig(config api.PolicyConfig, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, ValidateNamespace(config.OpenShiftSharedResourcesNamespace, fldPath.Child("openShiftSharedResourcesNamespace"))...)
allErrs = append(allErrs, ValidateNamespace(config.OpenShiftInfrastructureNamespace, fldPath.Child("openShiftInfrastructureNamespace"))...)
for i, matchingRule := range config.UserAgentMatchingConfig.DeniedClients {
_, err := regexp.Compile(matchingRule.Regex)
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("userAgentMatchingConfig", "deniedClients").Index(i), matchingRule.Regex, err.Error()))
}
}
for i, matchingRule := range config.UserAgentMatchingConfig.RequiredClients {
_, err := regexp.Compile(matchingRule.Regex)
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("userAgentMatchingConfig", "requiredClients").Index(i), matchingRule.Regex, err.Error()))
}
}
return allErrs
}
func ValidateProjectConfig(config api.ProjectConfig, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
if _, _, err := api.ParseNamespaceAndName(config.ProjectRequestTemplate); err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("projectRequestTemplate"), config.ProjectRequestTemplate, "must be in the form: namespace/templateName"))
}
if len(config.DefaultNodeSelector) > 0 {
_, err := labelselector.Parse(config.DefaultNodeSelector)
if err != nil {
validationResults.AddErrors(field.Invalid(fldPath.Child("defaultNodeSelector"), config.DefaultNodeSelector, "must be a valid label selector"))
}
}
if alloc := config.SecurityAllocator; alloc != nil {
securityAllocatorPath := fldPath.Child("securityAllocator")
if _, err := uid.ParseRange(alloc.UIDAllocatorRange); err != nil {
validationResults.AddErrors(field.Invalid(securityAllocatorPath.Child("uidAllocatorRange"), alloc.UIDAllocatorRange, err.Error()))
}
if _, err := mcs.ParseRange(alloc.MCSAllocatorRange); err != nil {
validationResults.AddErrors(field.Invalid(securityAllocatorPath.Child("mcsAllocatorRange"), alloc.MCSAllocatorRange, err.Error()))
}
if alloc.MCSLabelsPerProject <= 0 {
validationResults.AddErrors(field.Invalid(securityAllocatorPath.Child("mcsLabelsPerProject"), alloc.MCSLabelsPerProject, "must be a positive integer"))
}
} else {
validationResults.AddWarnings(field.Invalid(fldPath.Child("securityAllocator"), "null", "allocation of UIDs and MCS labels to a project must be done manually"))
}
return validationResults
}
func ValidateRoutingConfig(config api.RoutingConfig, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(config.Subdomain) == 0 {
allErrs = append(allErrs, field.Required(fldPath.Child("subdomain"), ""))
} else if len(kuval.IsDNS1123Subdomain(config.Subdomain)) != 0 {
allErrs = append(allErrs, field.Invalid(fldPath.Child("subdomain"), config.Subdomain, "must be a valid subdomain"))
}
return allErrs
}
func ValidateAPIServerExtendedArguments(config api.ExtendedArguments, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
validationResults.AddErrors(ValidateExtendedArguments(config, apiserveroptions.NewServerRunOptions().AddFlags, fldPath)...)
if len(config["admission-control"]) > 0 {
validationResults.AddWarnings(field.Invalid(fldPath.Key("admission-control"), config["admission-control"], "specified admission ordering is being phased out. Convert to DefaultAdmissionConfig in admissionConfig.pluginConfig."))
}
if len(config["admission-control-config-file"]) > 0 {
validationResults.AddWarnings(field.Invalid(fldPath.Key("admission-control-config-file"), config["admission-control-config-file"], "specify a single admission control config file is being phased out. Convert to admissionConfig.pluginConfig, one file per plugin."))
}
return validationResults
}
func ValidateControllerExtendedArguments(config api.ExtendedArguments, fldPath *field.Path) field.ErrorList {
return ValidateExtendedArguments(config, cm.OriginControllerManagerAddFlags(kcmoptions.NewCMServer()), fldPath)
}
// deprecatedAdmissionPluginNames returns the set of admission plugin names that are deprecated from use.
func deprecatedAdmissionPluginNames() sets.String {
return sets.NewString("openshift.io/OriginResourceQuota")
}
func ValidateAdmissionPluginConfig(pluginConfig map[string]api.AdmissionPluginConfig, fieldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
deprecatedPlugins := deprecatedAdmissionPluginNames()
for name, config := range pluginConfig {
if deprecatedPlugins.Has(name) {
validationResults.AddWarnings(field.Invalid(fieldPath.Key(name), "", "specified admission plugin is deprecated"))
}
if len(config.Location) > 0 && config.Configuration != nil {
validationResults.AddErrors(field.Invalid(fieldPath.Key(name), "", "cannot specify both location and embedded config"))
}
if len(config.Location) == 0 && config.Configuration == nil {
validationResults.AddErrors(field.Invalid(fieldPath.Key(name), "", "must specify either a location or an embedded config"))
}
}
return validationResults
}
func ValidateIngressIPNetworkCIDR(config *api.MasterConfig, fldPath *field.Path) (errors field.ErrorList) {
cidr := config.NetworkConfig.IngressIPNetworkCIDR
if len(cidr) == 0 {
return
}
addError := func(errMessage string) {
errors = append(errors, field.Invalid(fldPath, cidr, errMessage))
}
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
addError(fmt.Sprintf("must be a valid CIDR notation IP range (e.g. %s)", api.DefaultIngressIPNetworkCIDR))
return
}
// TODO Detect cloud provider when not using built-in kubernetes
kubeConfig := config.KubernetesMasterConfig
noCloudProvider := kubeConfig != nil && (len(kubeConfig.ControllerArguments["cloud-provider"]) == 0 || kubeConfig.ControllerArguments["cloud-provider"][0] == "")
if noCloudProvider {
for _, entry := range config.NetworkConfig.ClusterNetworks {
if api.CIDRsOverlap(cidr, entry.CIDR) {
addError(fmt.Sprintf("conflicts with cluster network CIDR: %s", entry.CIDR))
}
}
if api.CIDRsOverlap(cidr, config.NetworkConfig.ServiceNetworkCIDR) {
addError("conflicts with service network CIDR")
}
} else if !ipNet.IP.IsUnspecified() {
addError("should not be provided when a cloud-provider is enabled")
}
return
}
func ValidateDeprecatedClusterNetworkConfig(config *api.MasterConfig, fldPath *field.Path) ValidationResults {
validationResults := ValidationResults{}
if len(config.NetworkConfig.ClusterNetworks) > 0 && config.NetworkConfig.DeprecatedHostSubnetLength != config.NetworkConfig.ClusterNetworks[0].HostSubnetLength {
validationResults.AddErrors(field.Invalid(fldPath.Child("hostSubnetLength"), config.NetworkConfig.DeprecatedHostSubnetLength, "cannot set hostSubnetLength and clusterNetworks, please use clusterNetworks"))
}
if len(config.NetworkConfig.ClusterNetworks) > 0 && config.NetworkConfig.DeprecatedClusterNetworkCIDR != config.NetworkConfig.ClusterNetworks[0].CIDR {
validationResults.AddErrors(field.Invalid(fldPath.Child("clusterNetworkCIDR"), config.NetworkConfig.DeprecatedClusterNetworkCIDR, "cannot set clusterNetworkCIDR and clusterNetworks, please use clusterNetworks"))
}
return validationResults
}