-
Notifications
You must be signed in to change notification settings - Fork 21
/
provisionner.go
651 lines (563 loc) · 21.5 KB
/
provisionner.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
package services
import (
"errors"
"fmt"
"github.com/ca-gip/kubi/internal/authprovider"
"github.com/ca-gip/kubi/internal/utils"
v12 "github.com/ca-gip/kubi/pkg/apis/ca-gip/v1"
"github.com/ca-gip/kubi/pkg/generated/clientset/versioned"
"github.com/ca-gip/kubi/pkg/types"
corev1 "k8s.io/api/core/v1"
v1n "k8s.io/api/networking/v1"
"k8s.io/api/rbac/v1"
kerror "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/wait"
kubernetes "k8s.io/client-go/kubernetes"
v13 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"reflect"
"strings"
"time"
)
// Handler to regenerate all resources created by kubi
func RefreshK8SResources() {
err := GenerateResources()
if err != nil {
utils.Log.Error().Msg(err.Error())
}
}
// Generate Namespaces and Rolebinding from Ldap groups
func GenerateResources() error {
groups, err := ldap.GetAllGroups()
if err != nil {
utils.Log.Error().Msg(err.Error())
return err
}
if len(groups) == 0 {
return errors.New("LDAP, no ldap groups found!")
}
auths := GetUserNamespaces(groups)
GenerateProjects(auths)
return nil
}
// A loop wrapper for generateProject
// splitted for unit test !
func GenerateProjects(context []*types.Project) {
for _, auth := range context {
generateProject(auth)
}
}
// generate a project config or update it if exists
func generateProject(projectInfos *types.Project) {
kconfig, _ := rest.InClusterConfig()
clientSet, _ := versioned.NewForConfig(kconfig)
existingProject, errProject := clientSet.CagipV1().Projects().Get(projectInfos.Namespace(), metav1.GetOptions{})
splits := strings.Split(projectInfos.Namespace(), "-")
if len(splits) < 2 {
utils.Log.Warn().Msgf("Provisionner: The project %v could'nt be split in two part: <namespace>-<environment>.", projectInfos.Namespace())
}
project := &v12.Project{
Spec: v12.ProjectSpec{},
Status: v12.ProjectSpecStatus{
Name: "created",
},
ObjectMeta: metav1.ObjectMeta{
Name: projectInfos.Namespace(),
Labels: map[string]string{
"creator": "kubi",
},
},
}
if utils.Config.Tenant != utils.KubiTenantUndeterminable {
project.Spec.Tenant = utils.Config.Tenant
}
project.Spec.Project = projectInfos.Project
project.Spec.Environment = projectInfos.Environment
switch projectInfos.Environment {
case utils.KubiEnvironmentDevelopment:
project.Spec.Stages = []string{utils.KubiStageScratch, utils.KubiStageStaging, utils.KubiStageStable}
case utils.KubiEnvironmentIntegration:
project.Spec.Stages = []string{utils.KubiStageStaging, utils.KubiStageStable}
case utils.KubiEnvironmentUAT:
project.Spec.Stages = []string{utils.KubiStageStaging, utils.KubiStageStable}
case utils.KubiEnvironmentPreproduction:
project.Spec.Stages = []string{utils.KubiStageStable}
case utils.KubiEnvironmentProduction:
project.Spec.Stages = []string{utils.KubiStageStable}
default:
utils.Log.Warn().Msgf("Provisionner: Can't map stage and environment for project %v.", projectInfos.Namespace())
}
project.Spec.SourceEntity = projectInfos.Source
if utils.Config.Tenant != utils.KubiTenantUndeterminable {
project.Spec.Tenant = utils.Config.Tenant
}
if errProject != nil {
utils.Log.Info().Msgf("Project: %v doesn't exist, will be created", projectInfos.Namespace())
_, errorCreate := clientSet.CagipV1().Projects().Create(project)
if errorCreate != nil {
utils.Log.Error().Msg(errorCreate.Error())
utils.ProjectCreation.WithLabelValues("error", projectInfos.Project).Inc()
} else {
utils.ProjectCreation.WithLabelValues("created", projectInfos.Project).Inc()
}
return
} else {
utils.Log.Info().Msgf("Project: %v already exists, will be updated", projectInfos.Namespace())
existingProject.Spec.Project = project.Spec.Project
if len(project.Spec.Contact) > 0 {
existingProject.Spec.Contact = project.Spec.Contact
}
if len(project.Spec.Environment) > 0 {
existingProject.Spec.Environment = project.Spec.Environment
}
if len(existingProject.Spec.Tenant) == 0 {
existingProject.Spec.Tenant = project.Spec.Tenant
}
for _, stage := range project.Spec.Stages {
existingProject.Spec.Stages = utils.AppendIfMissing(existingProject.Spec.Stages, stage)
}
existingProject.Spec.SourceEntity = projectInfos.Source
_, errUpdate := clientSet.CagipV1().Projects().Update(existingProject)
if errUpdate != nil {
utils.Log.Error().Msg(errUpdate.Error())
utils.ProjectCreation.WithLabelValues("error", projectInfos.Project).Inc()
} else {
utils.ProjectCreation.WithLabelValues("updated", projectInfos.Project).Inc()
}
}
}
// GenerateRolebinding from tupple
// If exists, nothing is done, only creating !
func GenerateUserRoleBinding(namespace string, role string) {
kconfig, err := rest.InClusterConfig()
clientSet, err := kubernetes.NewForConfig(kconfig)
api := clientSet.RbacV1()
roleBindingName := fmt.Sprintf("%s-%s", "namespaced", role)
_, errRB := api.RoleBindings(namespace).Get(roleBindingName, metav1.GetOptions{})
newRoleBinding := v1.RoleBinding{
RoleRef: v1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: roleBindingName,
},
Subjects: []v1.Subject{
{
APIGroup: "rbac.authorization.k8s.io",
Kind: "Group",
Name: fmt.Sprintf("%s-%s", namespace, role),
},
{
APIGroup: "rbac.authorization.k8s.io",
Kind: "Group",
Name: utils.ApplicationMaster,
},
{
APIGroup: "rbac.authorization.k8s.io",
Kind: "Group",
Name: utils.OPSMaster,
},
},
ObjectMeta: metav1.ObjectMeta{
Name: roleBindingName,
Namespace: namespace,
Labels: map[string]string{
"name": roleBindingName,
"creator": "kubi",
"version": "v3",
},
},
}
if errRB != nil {
_, err = api.RoleBindings(namespace).Create(&newRoleBinding)
utils.Log.Info().Msgf("Rolebinding %v has been created for namespace %v and role %v", roleBindingName, namespace, role)
utils.RoleBindingsCreation.WithLabelValues("error", namespace, roleBindingName).Inc()
} else {
_, err = api.RoleBindings(namespace).Update(&newRoleBinding)
utils.Log.Info().Msgf("Rolebinding %v has been update for namespace %v and role %v", roleBindingName, namespace, role)
utils.RoleBindingsCreation.WithLabelValues("updated", namespace, roleBindingName).Inc()
}
if err != nil {
utils.Log.Error().Msg(err.Error())
utils.ServiceAccountCreation.WithLabelValues("created", namespace, roleBindingName).Inc()
}
}
func GenerateAppRoleBinding(namespace string) {
kconfig, err := rest.InClusterConfig()
clientSet, err := kubernetes.NewForConfig(kconfig)
api := clientSet.RbacV1()
_, errRB := api.RoleBindings(namespace).Get(utils.KubiRoleBindingAppName, metav1.GetOptions{})
newRoleBinding := v1.RoleBinding{
RoleRef: v1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: utils.KubiClusterRoleAppName,
},
Subjects: []v1.Subject{
{
Kind: "ServiceAccount",
Name: utils.KubiServiceAccountAppName,
Namespace: namespace,
},
},
ObjectMeta: metav1.ObjectMeta{
Name: utils.KubiRoleBindingAppName,
Namespace: namespace,
Labels: map[string]string{
"name": utils.KubiRoleBindingAppName,
"creator": "kubi",
"version": "v3",
},
},
}
if errRB != nil {
_, err = api.RoleBindings(namespace).Create(&newRoleBinding)
utils.Log.Info().Msgf("Rolebinding %v has been created for namespace %v", utils.KubiServiceAccountAppName, namespace)
utils.RoleBindingsCreation.WithLabelValues("created", namespace, utils.KubiServiceAccountAppName).Inc()
} else {
_, err = api.RoleBindings(namespace).Update(&newRoleBinding)
utils.Log.Info().Msgf("Rolebinding %v has been update for namespace %v", utils.KubiServiceAccountAppName, namespace)
utils.RoleBindingsCreation.WithLabelValues("updated", namespace, utils.KubiServiceAccountAppName).Inc()
}
if err != nil {
utils.Log.Error().Msg(err.Error())
utils.RoleBindingsCreation.WithLabelValues("error", namespace, utils.KubiServiceAccountAppName).Inc()
}
}
func GenerateDefaultRoleBinding(namespace string) {
kconfig, err := rest.InClusterConfig()
clientSet, err := kubernetes.NewForConfig(kconfig)
api := clientSet.RbacV1()
_, errRB := api.RoleBindings(namespace).Get(utils.KubiRoleBindingDefaultName, metav1.GetOptions{})
newRoleBinding := v1.RoleBinding{
RoleRef: v1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: utils.Config.DefaultPermission,
},
Subjects: []v1.Subject{
{
Kind: "ServiceAccount",
Name: utils.KubiServiceAccountDefaultName,
Namespace: namespace,
},
},
ObjectMeta: metav1.ObjectMeta{
Name: utils.KubiRoleBindingDefaultName,
Namespace: namespace,
Labels: map[string]string{
"name": utils.KubiRoleBindingDefaultName,
"creator": "kubi",
"version": "v3",
},
},
}
if errRB != nil {
_, err = api.RoleBindings(namespace).Create(&newRoleBinding)
utils.Log.Info().Msgf("Rolebinding %v has been created for namespace %v", utils.KubiServiceAccountAppName, namespace)
utils.RoleBindingsCreation.WithLabelValues("created", namespace, utils.KubiServiceAccountAppName).Inc()
} else {
_, err = api.RoleBindings(namespace).Update(&newRoleBinding)
utils.Log.Info().Msgf("Rolebinding %v has been update for namespace %v", utils.KubiServiceAccountAppName, namespace)
utils.RoleBindingsCreation.WithLabelValues("updated", namespace, utils.KubiServiceAccountAppName).Inc()
}
if err != nil {
utils.Log.Error().Msg(err.Error())
utils.RoleBindingsCreation.WithLabelValues("error", namespace, utils.KubiServiceAccountAppName).Inc()
}
}
// Generate
func GenerateAppServiceAccount(namespace string) {
kconfig, err := rest.InClusterConfig()
clientSet, err := kubernetes.NewForConfig(kconfig)
api := clientSet.CoreV1()
_, errRB := api.ServiceAccounts(namespace).Get(utils.KubiServiceAccountAppName, metav1.GetOptions{})
newServiceAccount := corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: utils.KubiServiceAccountAppName,
Namespace: namespace,
Labels: map[string]string{
"name": utils.KubiServiceAccountAppName,
"creator": "kubi",
"version": "v3",
},
},
}
if errRB != nil {
_, err = api.ServiceAccounts(namespace).Create(&newServiceAccount)
utils.Log.Info().Msgf("Service Account %v has been created for namespace %v", utils.KubiServiceAccountAppName, namespace)
utils.ServiceAccountCreation.WithLabelValues("created", namespace, utils.KubiServiceAccountAppName).Inc()
} else if err != nil {
utils.Log.Error().Msg(err.Error())
utils.ServiceAccountCreation.WithLabelValues("error", namespace, utils.KubiServiceAccountAppName).Inc()
} else {
utils.ServiceAccountCreation.WithLabelValues("ok", namespace, utils.KubiServiceAccountAppName).Inc()
}
}
// generateNamespace from a name
// If it doesn't exist or the number of labels is different from what it should be
func generateNamespace(namespace string) (err error) {
kconfig, _ := rest.InClusterConfig()
clientSet, _ := kubernetes.NewForConfig(kconfig)
api := clientSet.CoreV1()
ns, errNs := api.Namespaces().Get(namespace, metav1.GetOptions{})
if kerror.IsNotFound(errNs) {
err = createNamespace(namespace, api)
} else if errNs == nil && !reflect.DeepEqual(ns.Labels, generateNamespaceLabels(namespace)) {
err = updateExistingNamespace(namespace, api)
} else {
utils.NamespaceCreation.WithLabelValues("ok", namespace).Inc()
}
return
}
func createNamespace(namespace string, api v13.CoreV1Interface) error {
utils.Log.Info().Msgf("Creating ns %v", namespace)
ns := &corev1.Namespace{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Namespace",
},
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
Labels: generateNamespaceLabels(namespace),
},
}
_, err := api.Namespaces().Create(ns)
if err != nil {
utils.Log.Error().Err(err)
utils.NamespaceCreation.WithLabelValues("error", namespace).Inc()
} else {
utils.NamespaceCreation.WithLabelValues("created", namespace).Inc()
}
return err
}
func updateExistingNamespace(namespace string, api v13.CoreV1Interface) error {
utils.Log.Info().Msgf("Updating ns %v", namespace)
ns := &corev1.Namespace{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Namespace",
},
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
Labels: generateNamespaceLabels(namespace),
},
}
_, err := api.Namespaces().Update(ns)
if err != nil {
utils.Log.Error().Err(err)
utils.NamespaceCreation.WithLabelValues("error", namespace).Inc()
} else {
utils.NamespaceCreation.WithLabelValues("updated", namespace).Inc()
}
return err
}
// Generate CustomLabels that should be applied on Kubi's Namespaces
func generateNamespaceLabels(namespace string) (labels map[string]string) {
defaultLabels := map[string]string{
"name": namespace,
"type": "customer",
"creator": "kubi",
}
return utils.Union(defaultLabels, utils.Config.CustomLabels)
}
// Watch NetworkPolicyConfig, which is a config object for namespace network bubble
// This CRD allow user to deploy global configuration for network configuration
// for update, the default network config is updated
// for deletion, it is automatically recreated
// for create, just create it
func WatchProjects() cache.Store {
kconfig, _ := rest.InClusterConfig()
v3, _ := versioned.NewForConfig(kconfig)
watchlist := cache.NewFilteredListWatchFromClient(v3.CagipV1().RESTClient(), "projects", metav1.NamespaceAll, utils.DefaultWatchOptionModifier)
resyncPeriod := 30 * time.Minute
store, controller := cache.NewInformer(watchlist, &v12.Project{}, resyncPeriod, cache.ResourceEventHandlerFuncs{
AddFunc: projectCreated,
DeleteFunc: projectDelete,
UpdateFunc: projectUpdate,
})
go controller.Run(wait.NeverStop)
return store
}
func projectUpdate(old interface{}, new interface{}) {
newProject := new.(*v12.Project)
utils.Log.Info().Msgf("Operator: the project %v has been updated, updating associated resources: namespace, networkpolicies.", newProject.Name)
generateNamespace(newProject.Name)
if utils.Config.NetworkPolicy {
generateNetworkPolicy(newProject.Name, nil)
}
// TODO: Refactor with a non static list of roles
GenerateUserRoleBinding(newProject.Name, "admin")
GenerateAppServiceAccount(newProject.Name)
GenerateAppRoleBinding(newProject.Name)
if !strings.EqualFold(utils.Config.DefaultPermission, "") {
GenerateDefaultRoleBinding(newProject.Name)
}
}
func projectCreated(obj interface{}) {
project := obj.(*v12.Project)
utils.Log.Info().Msgf("Operator: the project %v has been created, generating associated resources: namespace, networkpolicies.", project.Name)
generateNamespace(project.Name)
if utils.Config.NetworkPolicy {
generateNetworkPolicy(project.Name, nil)
}
// TODO: Refactor with a non static list of roles
GenerateUserRoleBinding(project.Name, "admin")
GenerateAppServiceAccount(project.Name)
GenerateAppRoleBinding(project.Name)
if !strings.EqualFold(utils.Config.DefaultPermission, "") {
GenerateDefaultRoleBinding(project.Name)
}
}
func projectDelete(obj interface{}) {
project := obj.(*v12.Project)
utils.Log.Info().Msgf("Operator: the project %v has been deleted, Kubi won't delete anything, please delete the namespace %v manualy", project.Name, project.Name)
}
// Watch NetworkPolicyConfig, which is a config object for namespace network bubble
// This CRD allow user to deploy global configuration for network configuration
// for update, the default network config is updated
// for deletion, it is automatically recreated
// for create, just create it
func WatchNetPolConfig() cache.Store {
kconfig, _ := rest.InClusterConfig()
v3, _ := versioned.NewForConfig(kconfig)
watchlist := cache.NewFilteredListWatchFromClient(v3.CagipV1().RESTClient(), "networkpolicyconfigs", metav1.NamespaceAll, utils.DefaultWatchOptionModifier)
resyncPeriod := 30 * time.Minute
store, controller := cache.NewInformer(watchlist, &v12.NetworkPolicyConfig{}, resyncPeriod, cache.ResourceEventHandlerFuncs{
AddFunc: networkPolicyConfigCreated,
DeleteFunc: networkPolicyConfigDelete,
UpdateFunc: networkPolicyConfigUpdate,
})
go controller.Run(wait.NeverStop)
return store
}
func networkPolicyConfigUpdate(old interface{}, new interface{}) {
netpolconfig := new.(*v12.NetworkPolicyConfig)
utils.Log.Info().Msgf("Operator: the network config %v has changed, refreshing associated resources: networkpolicies, for all kubi's namespaces.", netpolconfig.Name)
kconfig, _ := rest.InClusterConfig()
clientSet, _ := versioned.NewForConfig(kconfig)
projects, err := clientSet.CagipV1().Projects().List(metav1.ListOptions{})
if err != nil {
utils.Log.Error().Msg(err.Error())
return
}
for _, project := range projects.Items {
utils.Log.Info().Msgf("Operator: refresh network policy for %v", project.Name)
if utils.Config.NetworkPolicy {
generateNetworkPolicy(project.Name, netpolconfig)
}
}
}
func networkPolicyConfigCreated(obj interface{}) {
netpolconfig := obj.(*v12.NetworkPolicyConfig)
utils.Log.Info().Msgf("Operator: the network config %v has been created, refreshing associated resources: networkpolicies, for all kubi's namespaces.", netpolconfig.Name)
kconfig, _ := rest.InClusterConfig()
clientSet, _ := versioned.NewForConfig(kconfig)
projects, err := clientSet.CagipV1().Projects().List(metav1.ListOptions{})
if err != nil {
utils.Log.Error().Msg(err.Error())
return
}
for _, project := range projects.Items {
utils.Log.Info().Msgf("Operator: refresh network policy for %v", project.Name)
if utils.Config.NetworkPolicy {
generateNetworkPolicy(project.Name, netpolconfig)
}
}
}
func networkPolicyConfigDelete(obj interface{}) {
netpolconfig := obj.(*v12.NetworkPolicyConfig)
utils.Log.Info().Msgf("Operator: the network config %v has been deleted, please delete networkpolicies for all kubi's namespaces. Be careful !", netpolconfig.Name)
}
// Generate a NetworkPolicy based on NetworkPolicyConfig
// If exists, the existing netpol is updated else it is created
func generateNetworkPolicy(namespace string, networkPolicyConfig *v12.NetworkPolicyConfig) {
kconfig, _ := rest.InClusterConfig()
if networkPolicyConfig == nil {
extendedClientSet, _ := versioned.NewForConfig(kconfig)
existingNetworkPolicyConfig, err := extendedClientSet.CagipV1().NetworkPolicyConfigs().Get(utils.KubiDefaultNetworkPolicyName, metav1.GetOptions{})
networkPolicyConfig = existingNetworkPolicyConfig
if err != nil {
utils.Log.Info().Msgf("Operator: No default network policy config \"%v\" found, cannot create/update namespace security !, Error: %v", utils.KubiDefaultNetworkPolicyName, err.Error())
utils.NetworkPolicyCreation.WithLabelValues("error", namespace, utils.KubiDefaultNetworkPolicyName).Inc()
}
}
clientSet, _ := kubernetes.NewForConfig(kconfig)
api := clientSet.NetworkingV1()
_, errNetpol := api.NetworkPolicies(namespace).Get(utils.KubiDefaultNetworkPolicyName, metav1.GetOptions{})
UDP := corev1.ProtocolUDP
TCP := corev1.ProtocolTCP
var ingressRules []v1n.NetworkPolicyPeer
// Add default intra namespace communication
ingressRules = append(ingressRules, v1n.NetworkPolicyPeer{
PodSelector: &metav1.LabelSelector{MatchLabels: nil},
})
// Add default whitelisted namespace ingress rules
for _, namespace := range networkPolicyConfig.Spec.Ingress.Namespaces {
ingressRules = append(ingressRules, v1n.NetworkPolicyPeer{
NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"name": namespace}},
PodSelector: &metav1.LabelSelector{MatchLabels: nil},
})
}
var netpolPorts []v1n.NetworkPolicyPort
if len(networkPolicyConfig.Spec.Egress.Ports) > 0 {
for _, port := range networkPolicyConfig.Spec.Egress.Ports {
netpolPorts = append(netpolPorts, v1n.NetworkPolicyPort{Port: &intstr.IntOrString{IntVal: int32(port)}, Protocol: &UDP})
netpolPorts = append(netpolPorts, v1n.NetworkPolicyPort{Port: &intstr.IntOrString{IntVal: int32(port)}, Protocol: &TCP})
}
}
netpolPorts = append(netpolPorts, v1n.NetworkPolicyPort{Port: &intstr.IntOrString{IntVal: 53}, Protocol: &UDP})
policyPeers := []v1n.NetworkPolicyPeer{
{PodSelector: &metav1.LabelSelector{MatchLabels: nil}},
{NamespaceSelector: &metav1.LabelSelector{MatchLabels: nil}},
}
for _, cidr := range networkPolicyConfig.Spec.Egress.Cidrs {
policyPeers = append(policyPeers, v1n.NetworkPolicyPeer{IPBlock: &v1n.IPBlock{CIDR: cidr}})
}
networkpolicy := &v1n.NetworkPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: utils.KubiDefaultNetworkPolicyName,
Namespace: namespace,
},
Spec: v1n.NetworkPolicySpec{
PodSelector: metav1.LabelSelector{
MatchLabels: nil,
},
Ingress: []v1n.NetworkPolicyIngressRule{
{
From: ingressRules,
},
},
Egress: []v1n.NetworkPolicyEgressRule{
{Ports: netpolPorts},
{
To: policyPeers,
},
},
PolicyTypes: []v1n.PolicyType{
v1n.PolicyTypeIngress, v1n.PolicyTypeEgress,
},
},
}
if errNetpol != nil {
_, err := api.NetworkPolicies(namespace).Create(networkpolicy)
if err != nil {
utils.NetworkPolicyCreation.WithLabelValues("error", namespace, utils.KubiDefaultNetworkPolicyName).Inc()
} else {
utils.NetworkPolicyCreation.WithLabelValues("created", namespace, utils.KubiDefaultNetworkPolicyName).Inc()
}
utils.Check(err)
return
} else {
_, err := api.NetworkPolicies(namespace).Update(networkpolicy)
if err != nil {
utils.NetworkPolicyCreation.WithLabelValues("error", namespace, utils.KubiDefaultNetworkPolicyName).Inc()
} else {
utils.NetworkPolicyCreation.WithLabelValues("updated", namespace, utils.KubiDefaultNetworkPolicyName).Inc()
}
utils.Check(err)
return
}
}