forked from cilium/cilium
/
register.go
1285 lines (1191 loc) · 47.7 KB
/
register.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
// Copyright 2017 Authors of Cilium
//
// 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 v2
import (
goerrors "errors"
"fmt"
"time"
k8sconst "github.com/cilium/cilium/pkg/k8s/apis/cilium.io"
"github.com/cilium/cilium/pkg/k8s/version"
"github.com/cilium/cilium/pkg/option"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/wait"
goVersion "github.com/hashicorp/go-version"
)
const (
// CustomResourceDefinitionGroup is the name of the third party resource group
CustomResourceDefinitionGroup = k8sconst.GroupName
// CustomResourceDefinitionVersion is the current version of the resource
CustomResourceDefinitionVersion = "v2"
// CustomResourceDefinitionSchemaVersion is semver-conformant version of CRD schema
// Used to determine if CRD needs to be updated in cluster
CustomResourceDefinitionSchemaVersion = "1.15.1"
// CustomResourceDefinitionSchemaVersionKey is key to label which holds the CRD schema version
CustomResourceDefinitionSchemaVersionKey = "io.cilium.k8s.crd.schema.version"
// CNPKindDefinition is the kind name for Cilium Network Policy
CNPKindDefinition = "CiliumNetworkPolicy"
fqdnNameRegex = `^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])\.?$`
fqdnPatternRegex = `^(([a-zA-Z0-9\*]|[a-zA-Z0-9\*][a-zA-Z0-9\-\*]*[a-zA-Z0-9\*])\.)*([A-Za-z0-9\*]|[A-Za-z0-9\*][A-Za-z0-9\-\*]*[A-Za-z0-9\*])\.?$`
)
// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{
Group: CustomResourceDefinitionGroup,
Version: CustomResourceDefinitionVersion,
}
// Resource takes an unqualified resource and returns a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
var (
// SchemeBuilder is needed by DeepCopy generator.
SchemeBuilder runtime.SchemeBuilder
// localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes.
localSchemeBuilder = &SchemeBuilder
// AddToScheme adds all types of this clientset into the given scheme.
// This allows composition of clientsets, like in:
//
// import (
// "k8s.io/client-go/kubernetes"
// clientsetscheme "k8s.io/client-go/kuberentes/scheme"
// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme"
// )
//
// kclientset, _ := kubernetes.NewForConfig(c)
// aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme)
AddToScheme = localSchemeBuilder.AddToScheme
comparableCRDSchemaVersion *goVersion.Version
)
func init() {
comparableCRDSchemaVersion = goVersion.Must(
goVersion.NewVersion(CustomResourceDefinitionSchemaVersion))
// We only register manually written functions here. The registration of the
// generated functions takes place in the generated files. The separation
// makes the code compile even when the generated files are missing.
localSchemeBuilder.Register(addKnownTypes)
}
// Adds the list of known types to api.Scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&CiliumNetworkPolicy{},
&CiliumNetworkPolicyList{},
&CiliumEndpoint{},
&CiliumEndpointList{},
&CiliumNode{},
&CiliumNodeList{},
&CiliumIdentity{},
&CiliumIdentityList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}
// CreateCustomResourceDefinitions creates our CRD objects in the kubernetes
// cluster
func CreateCustomResourceDefinitions(clientset apiextensionsclient.Interface) error {
if err := createCNPCRD(clientset); err != nil {
return err
}
if err := createCEPCRD(clientset); err != nil {
return err
}
if err := createNodeCRD(clientset); err != nil {
return err
}
if option.Config.IdentityAllocationMode == option.IdentityAllocationModeCRD {
if err := createIdentityCRD(clientset); err != nil {
return err
}
}
return nil
}
// createCNPCRD creates and updates the CiliumNetworkPolicies CRD. It should be called
// on agent startup but is idempotent and safe to call again.
func createCNPCRD(clientset apiextensionsclient.Interface) error {
var (
// CustomResourceDefinitionSingularName is the singular name of custom resource definition
CustomResourceDefinitionSingularName = "ciliumnetworkpolicy"
// CustomResourceDefinitionPluralName is the plural name of custom resource definition
CustomResourceDefinitionPluralName = "ciliumnetworkpolicies"
// CustomResourceDefinitionShortNames are the abbreviated names to refer to this CRD's instances
CustomResourceDefinitionShortNames = []string{"cnp", "ciliumnp"}
// CustomResourceDefinitionKind is the Kind name of custom resource definition
CustomResourceDefinitionKind = CNPKindDefinition
CRDName = CustomResourceDefinitionPluralName + "." + SchemeGroupVersion.Group
)
res := &apiextensionsv1beta1.CustomResourceDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: CRDName,
Labels: map[string]string{
CustomResourceDefinitionSchemaVersionKey: CustomResourceDefinitionSchemaVersion,
},
},
Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
Group: SchemeGroupVersion.Group,
Version: SchemeGroupVersion.Version,
Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
Plural: CustomResourceDefinitionPluralName,
Singular: CustomResourceDefinitionSingularName,
ShortNames: CustomResourceDefinitionShortNames,
Kind: CustomResourceDefinitionKind,
},
Subresources: &apiextensionsv1beta1.CustomResourceSubresources{
Status: &apiextensionsv1beta1.CustomResourceSubresourceStatus{},
},
Scope: apiextensionsv1beta1.NamespaceScoped,
Validation: &CNPCRV,
},
}
// Kubernetes < 1.12 does not support having the field Type set in the root
// schema so we need to set it to empty if kube-apiserver does not supports
// it.
if !version.Capabilities().FieldTypeInCRDSchema {
res.Spec.Validation.OpenAPIV3Schema.Type = ""
}
return createUpdateCRD(clientset, "CiliumNetworkPolicy/v2", res)
}
// createCEPCRD creates and updates the CiliumEndpoint CRD. It should be called
// on agent startup but is idempotent and safe to call again.
func createCEPCRD(clientset apiextensionsclient.Interface) error {
var (
// CustomResourceDefinitionSingularName is the singular name of custom resource definition
CustomResourceDefinitionSingularName = "ciliumendpoint"
// CustomResourceDefinitionPluralName is the plural name of custom resource definition
CustomResourceDefinitionPluralName = "ciliumendpoints"
// CustomResourceDefinitionShortNames are the abbreviated names to refer to this CRD's instances
CustomResourceDefinitionShortNames = []string{"cep", "ciliumep"}
// CustomResourceDefinitionKind is the Kind name of custom resource definition
CustomResourceDefinitionKind = "CiliumEndpoint"
CRDName = CustomResourceDefinitionPluralName + "." + SchemeGroupVersion.Group
)
res := &apiextensionsv1beta1.CustomResourceDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: CRDName,
},
Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
Group: SchemeGroupVersion.Group,
Version: SchemeGroupVersion.Version,
Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
Plural: CustomResourceDefinitionPluralName,
Singular: CustomResourceDefinitionSingularName,
ShortNames: CustomResourceDefinitionShortNames,
Kind: CustomResourceDefinitionKind,
},
AdditionalPrinterColumns: []apiextensionsv1beta1.CustomResourceColumnDefinition{
{
Name: "Endpoint ID",
Type: "integer",
Description: "Cilium endpoint id",
JSONPath: ".status.id",
},
{
Name: "Identity ID",
Type: "integer",
Description: "Cilium identity id",
JSONPath: ".status.identity.id",
},
{
Name: "Ingress Enforcement",
Type: "boolean",
Description: "Ingress enforcement in the endpoint",
JSONPath: ".status.policy.ingress.enforcing",
},
{
Name: "Egress Enforcement",
Type: "boolean",
Description: "Egress enforcement in the endpoint",
JSONPath: ".status.policy.egress.enforcing",
},
{
Name: "Endpoint State",
Type: "string",
Description: "Endpoint current state",
JSONPath: ".status.state",
},
{
Name: "IPv4",
Type: "string",
Description: "Endpoint IPv4 address",
JSONPath: ".status.networking.addressing[0].ipv4",
},
{
Name: "IPv6",
Type: "string",
Description: "Endpoint IPv6 address",
JSONPath: ".status.networking.addressing[0].ipv6",
},
},
Subresources: &apiextensionsv1beta1.CustomResourceSubresources{
Status: &apiextensionsv1beta1.CustomResourceSubresourceStatus{},
},
Scope: apiextensionsv1beta1.NamespaceScoped,
Validation: &cepCRV,
},
}
return createUpdateCRD(clientset, "v2.CiliumEndpoint", res)
}
// createNodeCRD creates and updates the CiliumNode CRD. It should be called on
// agent startup but is idempotent and safe to call again.
func createNodeCRD(clientset apiextensionsclient.Interface) error {
res := &apiextensionsv1beta1.CustomResourceDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: "ciliumnodes." + SchemeGroupVersion.Group,
},
Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
Group: SchemeGroupVersion.Group,
Version: SchemeGroupVersion.Version,
Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
Plural: "ciliumnodes",
Singular: "ciliumnode",
ShortNames: []string{"cn"},
Kind: "CiliumNode",
},
Subresources: &apiextensionsv1beta1.CustomResourceSubresources{
Status: &apiextensionsv1beta1.CustomResourceSubresourceStatus{},
},
Scope: apiextensionsv1beta1.ClusterScoped,
},
}
return createUpdateCRD(clientset, "v2.CiliumNode", res)
}
// createIdentityCRD creates and updates the CiliumIdentity CRD. It should be
// called on agent startup but is idempotent and safe to call again.
func createIdentityCRD(clientset apiextensionsclient.Interface) error {
var (
// CustomResourceDefinitionSingularName is the singular name of custom resource definition
CustomResourceDefinitionSingularName = "ciliumidentity"
// CustomResourceDefinitionPluralName is the plural name of custom resource definition
CustomResourceDefinitionPluralName = "ciliumidentities"
// CustomResourceDefinitionShortNames are the abbreviated names to refer to this CRD's instances
CustomResourceDefinitionShortNames = []string{"ciliumid"}
// CustomResourceDefinitionKind is the Kind name of custom resource definition
CustomResourceDefinitionKind = "CiliumIdentity"
CRDName = CustomResourceDefinitionPluralName + "." + SchemeGroupVersion.Group
)
res := &apiextensionsv1beta1.CustomResourceDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: CRDName,
},
Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
Group: SchemeGroupVersion.Group,
Version: SchemeGroupVersion.Version,
Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
Plural: CustomResourceDefinitionPluralName,
Singular: CustomResourceDefinitionSingularName,
ShortNames: CustomResourceDefinitionShortNames,
Kind: CustomResourceDefinitionKind,
},
Subresources: &apiextensionsv1beta1.CustomResourceSubresources{
Status: &apiextensionsv1beta1.CustomResourceSubresourceStatus{},
},
Scope: apiextensionsv1beta1.ClusterScoped,
},
}
return createUpdateCRD(clientset, "v2.CiliumIdentity", res)
}
// createUpdateCRD ensures the CRD object is installed into the k8s cluster. It
// will create or update the CRD and it's validation when needed
func createUpdateCRD(clientset apiextensionsclient.Interface, CRDName string, crd *apiextensionsv1beta1.CustomResourceDefinition) error {
scopedLog := log.WithField("name", CRDName)
clusterCRD, err := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(crd.ObjectMeta.Name, metav1.GetOptions{})
if errors.IsNotFound(err) {
scopedLog.Info("Creating CRD (CustomResourceDefinition)...")
clusterCRD, err = clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Create(crd)
// This occurs when multiple agents race to create the CRD. Since another has
// created it, it will also update it, hence the non-error return.
if errors.IsAlreadyExists(err) {
return nil
}
}
if err != nil {
return err
}
scopedLog.Debug("Checking if CRD (CustomResourceDefinition) needs update...")
if needsUpdate(clusterCRD) {
scopedLog.Info("Updating CRD (CustomResourceDefinition)...")
// Update the CRD with the validation schema.
err = wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) {
clusterCRD, err = clientset.ApiextensionsV1beta1().
CustomResourceDefinitions().Get(crd.ObjectMeta.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
// This seems too permissive but we only get here if the version is
// different per needsUpdate above. If so, we want to update on any
// validation change including adding or removing validation.
if needsUpdate(clusterCRD) {
scopedLog.Debug("CRD validation is different, updating it...")
clusterCRD.ObjectMeta.Labels = crd.ObjectMeta.Labels
clusterCRD.Spec = crd.Spec
_, err = clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Update(clusterCRD)
if err == nil {
return true, nil
}
scopedLog.WithError(err).Debug("Unable to update CRD validation")
return false, err
}
return true, nil
})
if err != nil {
scopedLog.WithError(err).Error("Unable to update CRD")
return err
}
}
// wait for the CRD to be established
scopedLog.Debug("Waiting for CRD (CustomResourceDefinition) to be available...")
err = wait.Poll(500*time.Millisecond, 60*time.Second, func() (bool, error) {
crd, err := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(crd.ObjectMeta.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
for _, cond := range crd.Status.Conditions {
switch cond.Type {
case apiextensionsv1beta1.Established:
if cond.Status == apiextensionsv1beta1.ConditionTrue {
return true, err
}
case apiextensionsv1beta1.NamesAccepted:
if cond.Status == apiextensionsv1beta1.ConditionFalse {
scopedLog.WithError(goerrors.New(cond.Reason)).Error("Name conflict for CRD")
return false, err
}
}
}
return false, err
})
if err != nil {
deleteErr := clientset.ApiextensionsV1beta1().CustomResourceDefinitions().Delete(crd.ObjectMeta.Name, nil)
if deleteErr != nil {
return fmt.Errorf("unable to delete k8s %s CRD %s. Deleting CRD due: %s", CRDName, deleteErr, err)
}
return err
}
scopedLog.Info("CRD (CustomResourceDefinition) is installed and up-to-date")
return nil
}
func needsUpdate(clusterCRD *apiextensionsv1beta1.CustomResourceDefinition) bool {
if clusterCRD.Spec.Validation == nil {
// no validation detected
return true
}
v, ok := clusterCRD.Labels[CustomResourceDefinitionSchemaVersionKey]
if !ok {
// no schema version detected
return true
}
clusterVersion, err := goVersion.NewVersion(v)
if err != nil || clusterVersion.LessThan(comparableCRDSchemaVersion) {
// version in cluster is either unparsable or smaller than current version
return true
}
return false
}
func getStr(str string) *string {
return &str
}
func getInt64(i int64) *int64 {
return &i
}
var (
// cepCRV is a minimal validation for CEP objects. Since only the agent is
// creating them, it is better to be permissive and have some data, if buggy,
// than to have no data in k8s.
cepCRV = apiextensionsv1beta1.CustomResourceValidation{
OpenAPIV3Schema: &apiextensionsv1beta1.JSONSchemaProps{},
}
CNPCRV = apiextensionsv1beta1.CustomResourceValidation{
OpenAPIV3Schema: &apiextensionsv1beta1.JSONSchemaProps{
// TODO: remove the following comment when we add checker
// to detect if we should install the CNP validation for k8s > 1.11
// with this line uncommented.
Type: "object",
Properties: properties,
},
}
properties = map[string]apiextensionsv1beta1.JSONSchemaProps{
"CIDR": CIDR,
"CIDRRule": CIDRRule,
"EgressRule": EgressRule,
"EndpointSelector": EndpointSelector,
"IngressRule": IngressRule,
"K8sServiceNamespace": K8sServiceNamespace,
"L7Rules": L7Rules,
"Label": Label,
"LabelSelector": LabelSelector,
"LabelSelectorRequirement": LabelSelectorRequirement,
"PortProtocol": PortProtocol,
"PortRule": PortRule,
"PortRuleHTTP": PortRuleHTTP,
"PortRuleKafka": PortRuleKafka,
"PortRuleL7": PortRuleL7,
"Rule": Rule,
"Service": Service,
"ServiceSelector": ServiceSelector,
"spec": spec,
"specs": specs,
}
CIDR = apiextensionsv1beta1.JSONSchemaProps{
Description: "CIDR is a CIDR prefix / IP Block.",
Type: "string",
OneOf: []apiextensionsv1beta1.JSONSchemaProps{
{
// IPv4 CIDR
Pattern: `^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4]` +
`[0-9]|[01]?[0-9][0-9]?)\/([0-9]|[1-2][0-9]|3[0-2])$`,
},
{
// IPv6 CIDR
Pattern: `^s*((([0-9A-Fa-f]{1,4}:){7}(:|([0-9A-Fa-f]{1,4})))` +
`|(([0-9A-Fa-f]{1,4}:){6}:([0-9A-Fa-f]{1,4})?)` +
`|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){0,1}):([0-9A-Fa-f]{1,4})?))` +
`|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){0,2}):([0-9A-Fa-f]{1,4})?))` +
`|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){0,3}):([0-9A-Fa-f]{1,4})?))` +
`|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){0,4}):([0-9A-Fa-f]{1,4})?))` +
`|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){0,5}):([0-9A-Fa-f]{1,4})?))` +
`|(:(:|((:[0-9A-Fa-f]{1,4}){1,7}))))` +
`(%.+)?s*/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8])$`,
},
},
}
CIDRRule = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: "CIDRRule is a rule that specifies a CIDR prefix to/from which outside " +
"communication is allowed, along with an optional list of subnets within that CIDR " +
"prefix to/from which outside communication is not allowed.",
Required: []string{
"cidr",
},
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"cidr": CIDR,
"except": {
Description: "ExceptCIDRs is a list of IP blocks which the endpoint subject to " +
"the rule is not allowed to initiate connections to. These CIDR prefixes " +
"should be contained within Cidr. These exceptions are only applied to the " +
"Cidr in this CIDRRule, and do not apply to any other CIDR prefixes in any " +
"other CIDRRules.",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &CIDR,
},
},
},
}
EgressRule = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: "EgressRule contains all rule types which can be applied at egress, i.e. " +
"network traffic that originates inside the endpoint and exits the endpoint " +
"selected by the endpointSelector.\n\n- All members of this structure are optional. " +
"If omitted or empty, the\n member will have no effect on the rule.\n\n- For now, " +
"combining ToPorts and ToCIDR in the same rule is not supported\n and such rules " +
"will be rejected. In the future, this will be supported and\n if if multiple " +
"members of the structure are specified, then all members\n must match in order " +
"for the rule to take effect.",
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"toCIDR": {
Description: "ToCIDR is a list of IP blocks which the endpoint subject to the " +
"rule is allowed to initiate connections. This will match on the " +
"destination IP address of outgoing connections. Adding a prefix into " +
"ToCIDR or into ToCIDRSet with no ExcludeCIDRs is equivalent. Overlaps are " +
"allowed between ToCIDR and ToCIDRSet.\n\nExample: Any endpoint with the " +
"label \"app=database-proxy\" is allowed to initiate connections to " +
"10.2.3.0/24",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &CIDR,
},
},
"toCIDRSet": {
Description: "ToCIDRSet is a list of IP blocks which the endpoint subject to " +
"the rule is allowed to initiate connections to in addition to connections " +
"which are allowed via FromEndpoints, along with a list of subnets " +
"contained within their corresponding IP block to which traffic should not " +
"be allowed. This will match on the destination IP address of outgoing " +
"connections. Adding a prefix into ToCIDR or into ToCIDRSet with no " +
"ExcludeCIDRs is equivalent. Overlaps are allowed between ToCIDR and " +
"ToCIDRSet.\n\nExample: Any endpoint with the label \"app=database-proxy\" " +
"is allowed to initiate connections to 10.2.3.0/24 except from IPs in " +
"subnet 10.2.3.0/28.",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &CIDRRule,
},
},
"toEntities": {
Description: "ToEntities is a list of special entities to which the endpoint " +
"subject to the rule is allowed to initiate connections. Supported " +
"entities are `world`, `cluster` and `host`",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &apiextensionsv1beta1.JSONSchemaProps{
Type: "string",
},
},
},
"toPorts": {
Description: "ToPorts is a list of destination ports identified by port number " +
"and protocol which the endpoint subject to the rule is allowed to connect " +
"to.\n\nExample: Any endpoint with the label \"role=frontend\" is allowed " +
"to initiate connections to destination port 8080/tcp",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &PortRule,
},
},
"toServices": {
Description: "ToServices is a list of services to which the endpoint subject " +
"to the rule is allowed to initiate connections.\n\nExample: Any endpoint " +
"with the label \"app=backend-app\" is allowed to initiate connections to " +
"all cidrs backing the \"external-service\" service",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &Service,
},
},
"toEndpoints": {
Description: "ToEndpoints is a list of endpoints identified by an " +
"EndpointSelector to which the endpoint subject to the rule" +
"is allowed to communicate.\n\nExample: Any endpoint with the label " +
"\"role=frontend\" can be consumed by any endpoint carrying the label " +
"\"role=backend\".",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &EndpointSelector,
},
},
"toRequires": {
Description: "ToRequires is a list of additional constraints which must be " +
"met in order for the selected endpoints to be able to reach other " +
"endpoints. These additional constraints do not by themselves grant access " +
"privileges and must always be accompanied with at least one matching " +
"FromEndpoints.\n\nExample: Any Endpoint with the label \"team=A\" " +
"requires any endpoint to which it communicates to also carry the label " +
"\"team=A\".",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &EndpointSelector,
},
},
"toGroups": {
Type: "array",
Description: `ToGroups is a list of constraints that will
gather data from third-party providers and create a new
derived policy.`,
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"aws": AWSGroup,
},
},
},
},
"toFQDNs": {
Description: `ToFQDNs is a list of rules matching fqdns that endpoint
is allowed to communicate with`,
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &FQDNRule,
},
},
},
}
FQDNRule = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: `FQDNRule is a rule that specifies an fully qualified domain name to which outside communication is allowed`,
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"matchName": MatchFQDNName,
"matchPattern": MatchFQDNPattern,
},
}
MatchFQDNName = apiextensionsv1beta1.JSONSchemaProps{
Description: `MatchName matches fqdn name`,
Type: "string",
Pattern: fqdnNameRegex,
}
MatchFQDNPattern = apiextensionsv1beta1.JSONSchemaProps{
Description: `MatchPattern matches fqdn by pattern`,
Type: "string",
Pattern: fqdnPatternRegex,
}
AWSGroup = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"securityGroupsIds": {
Description: `SecurityGroupsIds is the list of AWS security
group IDs that will filter the instances IPs from the AWS API`,
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &apiextensionsv1beta1.JSONSchemaProps{
Type: "string",
},
},
},
"securityGroupsNames": {
Description: `SecurityGroupsNames is the list of AWS security
group names that will filter the instances IPs from the AWS API`,
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &apiextensionsv1beta1.JSONSchemaProps{
Type: "string",
},
},
},
"region": {
Description: `Region is the key that will filter the AWS EC2
instances in the given region`,
Type: "string",
},
},
}
EndpointSelector = initEndpointSelector()
IngressRule = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: "IngressRule contains all rule types which can be applied at ingress, " +
"i.e. network traffic that originates outside of the endpoint and is entering " +
"the endpoint selected by the endpointSelector.\n\n- All members of this structure " +
"are optional. If omitted or empty, the\n member will have no effect on the rule." +
"\n\n- If multiple members are set, all of them need to match in order for\n " +
"the rule to take effect. The exception to this rule is FromRequires field;\n " +
"the effects of any Requires field in any rule will apply to all other\n rules " +
"as well.\n\n- For now, combining ToPorts, FromCIDR, and FromEndpoints in the same " +
"rule\n is not supported and any such rules will be rejected. In the future, " +
"this\n will be supported and if multiple members of this structure are specified," +
"\n then all members must match in order for the rule to take effect. The\n " +
"exception to this rule is the Requires field, the effects of any Requires\n " +
"field in any rule will apply to all other rules as well.",
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"fromCIDR": {
Description: "FromCIDR is a list of IP blocks which the endpoint subject to " +
"the rule is allowed to receive connections from. This will match on the " +
"source IP address of incoming connections. Adding a prefix into FromCIDR " +
"or into FromCIDRSet with no ExcludeCIDRs is equivalent. Overlaps are " +
"allowed between FromCIDR and FromCIDRSet.\n\nExample: Any endpoint with " +
"the label \"app=my-legacy-pet\" is allowed to receive connections from " +
"10.3.9.1",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &CIDR,
},
},
"fromCIDRSet": {
Description: "FromCIDRSet is a list of IP blocks which the endpoint subject to " +
"the rule is allowed to receive connections from in addition to " +
"FromEndpoints, along with a list of subnets contained within their " +
"corresponding IP block from which traffic should not be allowed. This " +
"will match on the source IP address of incoming connections. Adding a " +
"prefix into FromCIDR or into FromCIDRSet with no ExcludeCIDRs is " +
"equivalent. Overlaps are allowed between FromCIDR and FromCIDRSet." +
"\n\nExample: Any endpoint with the label \"app=my-legacy-pet\" is allowed " +
"to receive connections from 10.0.0.0/8 except from IPs in subnet " +
"10.96.0.0/12.",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &CIDRRule,
},
},
"fromEndpoints": {
Description: "FromEndpoints is a list of endpoints identified by an " +
"EndpointSelector which are allowed to communicate with the endpoint " +
"subject to the rule.\n\nExample: Any endpoint with the label " +
"\"role=backend\" can be consumed by any endpoint carrying the label " +
"\"role=frontend\".",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &EndpointSelector,
},
},
"fromEntities": {
Description: "FromEntities is a list of special entities which the endpoint " +
"subject to the rule is allowed to receive connections from. Supported " +
"entities are `world`, `cluster`, `host`, and `init`",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &apiextensionsv1beta1.JSONSchemaProps{
Type: "string",
},
},
},
"fromRequires": {
Description: "FromRequires is a list of additional constraints which must be " +
"met in order for the selected endpoints to be reachable. These additional " +
"constraints do no by itself grant access privileges and must always be " +
"accompanied with at least one matching FromEndpoints.\n\nExample: Any " +
"Endpoint with the label \"team=A\" requires consuming endpoint to also " +
"carry the label \"team=A\".",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &EndpointSelector,
},
},
"toPorts": {
Description: "ToPorts is a list of destination ports identified by port number " +
"and protocol which the endpoint subject to the rule is allowed to receive " +
"connections on.\n\nExample: Any endpoint with the label \"app=httpd\" can " +
"only accept incoming connections on port 80/tcp.",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &PortRule,
},
},
},
}
K8sServiceNamespace = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: "K8sServiceNamespace is an abstraction for the k8s service + namespace " +
"types.",
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"namespace": {
Type: "string",
},
"serviceName": {
Type: "string",
},
},
}
L7Rules = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: "L7Rules is a union of port level rule types. Mixing of different port " +
"level rule types is disallowed, so exactly one of the following must be set. If " +
"none are specified, then no additional port level rules are applied.",
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"http": {
Description: "HTTP specific rules.",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &PortRuleHTTP,
},
},
"kafka": {
Description: "Kafka-specific rules.",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &PortRuleKafka,
},
},
"l7proto": {
Description: "Parser type name that uses Key-Value pair rules.",
Type: "string",
},
"l7": {
Description: "Generic Key-Value pair rules.",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &PortRuleL7,
},
},
"dns": {
Description: "DNS specific rules",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &PortRuleDNS,
},
},
},
}
PortRuleDNS = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: `FQDNRule is a rule that specifies an fully qualified domain name to which outside communication is allowed`,
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"matchName": MatchFQDNName,
"matchPattern": MatchFQDNPattern,
},
}
Label = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: "Label is the cilium's representation of a container label.",
Required: []string{
"key",
},
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"key": {
Type: "string",
},
"source": {
Description: "Source can be one of the values present in const.go " +
"(e.g.: LabelSourceContainer)",
Type: "string",
},
"value": {
Type: "string",
},
},
}
LabelSelector = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: "A label selector is a label query over a set of resources. The result " +
"of matchLabels and matchExpressions are ANDed. An empty label selector matches " +
"all objects. A null label selector matches no objects.",
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"matchLabels": {
Description: "matchLabels is a map of {key,value} pairs. A single {key,value} " +
"in the matchLabels map is equivalent to an element of matchExpressions, " +
"whose key field is \"key\", the operator is \"In\", and the values array " +
"contains only \"value\". The requirements are ANDed.",
Type: "object",
},
"matchExpressions": {
Description: "matchExpressions is a list of label selector requirements. " +
"The requirements are ANDed.",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &LabelSelectorRequirement,
},
},
},
}
LabelSelectorRequirement = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: "A label selector requirement is a selector that contains values, a key, " +
"and an operator that relates the key and values.",
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"key": {
Description: "key is the label key that the selector applies to.",
Type: "string",
},
"operator": {
Description: "operator represents a key's relationship to a set of values. " +
"Valid operators are In, NotIn, Exists and DoesNotExist.",
Type: "string",
Enum: []apiextensionsv1beta1.JSON{
{
Raw: []byte(`"In"`),
},
{
Raw: []byte(`"NotIn"`),
},
{
Raw: []byte(`"Exists"`),
},
{
Raw: []byte(`"DoesNotExist"`),
},
},
},
"values": {
Description: "values is an array of string values. If the operator is In or " +
"NotIn, the values array must be non-empty. If the operator is Exists or " +
"DoesNotExist, the values array must be empty. This array is replaced " +
"during a strategic merge patch.",
Type: "array",
Items: &apiextensionsv1beta1.JSONSchemaPropsOrArray{
Schema: &apiextensionsv1beta1.JSONSchemaProps{
Type: "string",
},
},
},
},
Required: []string{"key", "operator"},
}
PortProtocol = apiextensionsv1beta1.JSONSchemaProps{
Type: "object",
Description: "PortProtocol specifies an L4 port with an optional transport protocol",
Required: []string{
"port",
},
Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{
"port": {
Description: "Port is an L4 port number. For now the string will be strictly " +
"parsed as a single uint16. In the future, this field may support ranges " +
"in the form \"1024-2048",
Type: "string",
// uint16 string regex
Pattern: `^(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|` +
`[1-5][0-9]{4}|[0-9]{1,4})$`,
},
"protocol": {
Description: `Protocol is the L4 protocol. If omitted or empty, any protocol ` +
`matches. Accepted values: "TCP", "UDP", ""/"ANY"\n\nMatching on ` +
`ICMP is not supported.`,
Type: "string",
Enum: []apiextensionsv1beta1.JSON{
{
Raw: []byte(`"TCP"`),
},
{
Raw: []byte(`"UDP"`),
},