forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
embedded.go
645 lines (595 loc) · 18.4 KB
/
embedded.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
package utils
import (
"fmt"
"github.com/pkg/errors"
rv1beta2 "github.com/rancher/types/apis/apps/v1beta2"
rv1 "github.com/rancher/types/apis/core/v1"
"github.com/rancher/types/apis/management.cattle.io/v3"
rrbacv1 "github.com/rancher/types/apis/rbac.authorization.k8s.io/v1"
"golang.org/x/sync/errgroup"
v1beta2 "k8s.io/api/apps/v1beta2"
v1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/intstr"
loggingconfig "github.com/rancher/rancher/pkg/controllers/user/logging/config"
)
const (
running = "Running"
)
func CreateEmbeddedTarget(dep rv1beta2.DeploymentInterface, sa rv1.ServiceAccountInterface, se rv1.ServiceInterface, ro rrbacv1.RoleInterface, rb rrbacv1.RoleBindingInterface, namespace string) error {
// create es deployment
_, err := dep.Controller().Lister().Get(loggingconfig.EmbeddedESName, loggingconfig.EmbeddedESName)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrapf(err, "get deployment %s fail", loggingconfig.EmbeddedESName)
}
// create service account, role and rolebinding
sc := newESServiceAccount(namespace)
role := newESRole(namespace)
roleBind := newESRoleBinding(namespace)
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
sa.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{})
}
}()
_, err = sa.Create(sc)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create service account %s fail", loggingconfig.EmbeddedESName)
}
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
ro.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{})
}
}()
_, err = ro.Create(role)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create role %s fail", loggingconfig.EmbeddedESName)
}
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
rb.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{})
}
}()
_, err = rb.Create(roleBind)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create role %s fail", loggingconfig.EmbeddedESName)
}
// create service and deployment
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
se.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{})
}
}()
newService := newESService(namespace)
_, err = se.Create(newService)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create service %s fail", loggingconfig.EmbeddedESName)
}
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
dep.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{})
}
}()
esDeployment := NewESDeployment(namespace)
_, err = dep.Create(esDeployment)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create deployment %s fail", loggingconfig.EmbeddedESName)
}
}
// create kibana deployment
_, err = dep.Controller().Lister().Get(loggingconfig.LoggingNamespace, loggingconfig.EmbeddedKibanaName)
if err != nil {
if !apierrors.IsNotFound(err) {
return errors.Wrapf(err, "get deployment %s fail", loggingconfig.EmbeddedKibanaName)
}
// create service account, role and rolebinding
sc := newKibanaServiceAccount(namespace)
role := newKibanaRole(namespace)
roleBind := newKibanaRoleBinding(namespace)
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
sa.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{})
}
}()
_, err = sa.Create(sc)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create service account %s fail", loggingconfig.EmbeddedKibanaName)
}
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
ro.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{})
}
}()
_, err = ro.Create(role)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create role %s fail", loggingconfig.EmbeddedKibanaName)
}
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
rb.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{})
}
}()
_, err = rb.Create(roleBind)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create role %s fail", loggingconfig.EmbeddedKibanaName)
}
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
se.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{})
}
}()
newService := newKibanaService(namespace)
_, err = se.Create(newService)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create service %s fail", loggingconfig.EmbeddedKibanaName)
}
defer func() {
if err != nil && !apierrors.IsAlreadyExists(err) {
dep.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{})
}
}()
kibanaDeployment := newKibanaDeployment(namespace)
_, err = dep.Create(kibanaDeployment)
if err != nil && !apierrors.IsAlreadyExists(err) {
return errors.Wrapf(err, "create deployment %s fail", loggingconfig.EmbeddedKibanaName)
}
}
return nil
}
func RemoveEmbeddedTarget(dep rv1beta2.DeploymentInterface, sa rv1.ServiceAccountInterface, se rv1.ServiceInterface, ro rrbacv1.RoleInterface, rb rrbacv1.RoleBindingInterface) error {
//service account
var errgrp errgroup.Group
errgrp.Go(func() error {
return se.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{})
})
errgrp.Go(func() error {
return sa.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{})
})
//role
errgrp.Go(func() error {
return ro.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{})
})
errgrp.Go(func() error {
return ro.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{})
})
//rolebinding
errgrp.Go(func() error {
return rb.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{})
})
errgrp.Go(func() error {
return rb.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{})
})
//service
errgrp.Go(func() error {
return se.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{})
})
errgrp.Go(func() error {
return se.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{})
})
//deployment
deleteOp := metav1.DeletePropagationBackground
errgrp.Go(func() error {
return dep.Delete(loggingconfig.EmbeddedESName, &metav1.DeleteOptions{PropagationPolicy: &deleteOp})
})
errgrp.Go(func() error {
return dep.Delete(loggingconfig.EmbeddedKibanaName, &metav1.DeleteOptions{PropagationPolicy: &deleteOp})
})
if err := errgrp.Wait(); err != nil && !apierrors.IsNotFound(err) {
return err
}
return nil
}
func UpdateEmbeddedEndpoint(podLister rv1.PodLister, serviceLister rv1.ServiceLister, clusterLoggings v3.ClusterLoggingInterface) error {
cls, err := clusterLoggings.List(metav1.ListOptions{})
if err != nil {
return fmt.Errorf("get cluterlogging failed, %v", err)
}
if len(cls.Items) == 0 {
return fmt.Errorf("not clusterlogging found")
}
cl := cls.Items[0]
if cl.Spec.EmbeddedConfig == nil {
return fmt.Errorf("embedded configuration should not be nil when update embedded endpoint")
}
updated := false
esEndpoint, err := getEmbeddedESEndpoint(podLister, serviceLister)
if err != nil {
return fmt.Errorf("get elasticsearch endpoint failed, %v", err)
}
if cl.Spec.EmbeddedConfig.ElasticsearchEndpoint != esEndpoint {
updated = true
cl.Spec.EmbeddedConfig.ElasticsearchEndpoint = esEndpoint
}
kibanaEndpoint, err := getEmbeddedKibanaEndpoint(podLister, serviceLister)
if err != nil {
return fmt.Errorf("get kibana endpoint failed, %v", err)
}
if cl.Spec.EmbeddedConfig.KibanaEndpoint != kibanaEndpoint {
updated = true
cl.Spec.EmbeddedConfig.KibanaEndpoint = kibanaEndpoint
}
if !updated {
return nil
}
if _, err = clusterLoggings.Update(&cl); err != nil {
return fmt.Errorf("update embedded logging endpoint failed, %v", err)
}
if esEndpoint == "" || kibanaEndpoint == "" {
return fmt.Errorf("embedded endpoint not set completely")
}
return nil
}
func getEmbeddedESEndpoint(podLister rv1.PodLister, serviceLister rv1.ServiceLister) (esEndpoint string, err error) {
selector := labels.NewSelector()
requirement, err := labels.NewRequirement(loggingconfig.LabelK8sApp, selection.Equals, []string{loggingconfig.EmbeddedESName})
if err != nil {
return "", err
}
espods, err := podLister.List(loggingconfig.LoggingNamespace, selector.Add(*requirement))
if err != nil {
return "", err
}
esservice, err := serviceLister.Get(loggingconfig.LoggingNamespace, loggingconfig.EmbeddedESName)
if err != nil {
return "", err
}
if len(esservice.Spec.Ports) == 0 {
return "", fmt.Errorf("get service %s node port failed", loggingconfig.EmbeddedESName)
}
var esPort int32
for _, v := range esservice.Spec.Ports {
if v.Name == "http" {
esPort = v.NodePort
break
}
}
if len(espods) == 0 {
return "", fmt.Errorf("deploying %s", loggingconfig.EmbeddedESName)
}
espod := espods[0]
if espod.Status.Phase == running {
return fmt.Sprintf("http://%s:%v", espod.Status.HostIP, esPort), nil
}
return "", fmt.Errorf("got embedded elasticsearch pod status %s", espod.Status.Phase)
}
func getEmbeddedKibanaEndpoint(podLister rv1.PodLister, serviceLister rv1.ServiceLister) (kibanaEndpoint string, err error) {
selector := labels.NewSelector()
requirement, err := labels.NewRequirement(loggingconfig.LabelK8sApp, selection.Equals, []string{loggingconfig.EmbeddedKibanaName})
if err != nil {
return "", err
}
kibanapods, err := podLister.List(loggingconfig.LoggingNamespace, selector.Add(*requirement))
if err != nil {
return "", err
}
kibanaservice, err := serviceLister.Get(loggingconfig.LoggingNamespace, loggingconfig.EmbeddedKibanaName)
if err != nil {
return "", err
}
if len(kibanaservice.Spec.Ports) == 0 {
return "", fmt.Errorf("get service %s node port failed", loggingconfig.EmbeddedKibanaName)
}
if len(kibanapods) == 0 {
return "", fmt.Errorf("deploying %s", loggingconfig.EmbeddedKibanaName)
}
kibanapod := kibanapods[0]
if kibanapod.Status.Phase == running {
return fmt.Sprintf("http://%s:%v", kibanapod.Status.HostIP, kibanaservice.Spec.Ports[0].NodePort), nil
}
return "", fmt.Errorf("got embedded kibana pod status %s", kibanapod.Status.Phase)
}
func newESServiceAccount(namespace string) *v1.ServiceAccount {
return &v1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: loggingconfig.EmbeddedESName,
Namespace: namespace,
},
}
}
func newKibanaServiceAccount(namespace string) *v1.ServiceAccount {
return &v1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: loggingconfig.EmbeddedKibanaName,
Namespace: namespace,
},
}
}
func newESRole(namespace string) *rbacv1.Role {
return &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Name: loggingconfig.EmbeddedESName,
Namespace: namespace,
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{rbacv1.APIGroupAll},
Resources: []string{"endpoints"},
Verbs: []string{rbacv1.VerbAll},
},
},
}
}
func newKibanaRole(namespace string) *rbacv1.Role {
return &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Name: loggingconfig.EmbeddedKibanaName,
Namespace: namespace,
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{rbacv1.APIGroupAll},
Resources: []string{"endpoints"},
Verbs: []string{rbacv1.VerbAll},
},
},
}
}
func newESRoleBinding(namespace string) *rbacv1.RoleBinding {
return &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: loggingconfig.EmbeddedESName,
Namespace: namespace,
},
RoleRef: rbacv1.RoleRef{
Name: loggingconfig.EmbeddedESName,
Kind: "Role",
APIGroup: rbacv1.GroupName,
},
Subjects: []rbacv1.Subject{
{
Kind: rbacv1.ServiceAccountKind,
Name: loggingconfig.EmbeddedESName,
Namespace: namespace,
},
},
}
}
func newKibanaRoleBinding(namespace string) *rbacv1.RoleBinding {
return &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: loggingconfig.EmbeddedKibanaName,
Namespace: namespace,
},
RoleRef: rbacv1.RoleRef{
Name: loggingconfig.EmbeddedKibanaName,
Kind: "Role",
APIGroup: rbacv1.GroupName,
},
Subjects: []rbacv1.Subject{
{
Kind: rbacv1.ServiceAccountKind,
Name: loggingconfig.EmbeddedKibanaName,
Namespace: namespace,
},
},
}
}
func newESService(namespace string) *v1.Service {
return &v1.Service{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: loggingconfig.EmbeddedESName,
Labels: map[string]string{
loggingconfig.LabelK8sApp: loggingconfig.EmbeddedESName,
},
},
Spec: v1.ServiceSpec{
Type: v1.ServiceTypeNodePort,
Ports: []v1.ServicePort{
v1.ServicePort{
Name: "http",
Port: 9200,
TargetPort: intstr.FromInt(9200),
},
v1.ServicePort{
Name: "tcp",
Port: 9300,
TargetPort: intstr.FromInt(9300),
},
},
Selector: map[string]string{
loggingconfig.LabelK8sApp: loggingconfig.EmbeddedESName,
},
},
}
}
func newKibanaService(namespace string) *v1.Service {
return &v1.Service{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: loggingconfig.EmbeddedKibanaName,
Labels: map[string]string{
loggingconfig.LabelK8sApp: loggingconfig.EmbeddedKibanaName,
},
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{
v1.ServicePort{
Name: "http",
Port: 5601,
TargetPort: intstr.FromInt(5601),
},
},
Type: v1.ServiceTypeNodePort,
Selector: map[string]string{
loggingconfig.LabelK8sApp: loggingconfig.EmbeddedKibanaName,
},
},
}
}
func NewESDeployment(namespace string) *v1beta2.Deployment {
deployment := &v1beta2.Deployment{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: loggingconfig.EmbeddedESName,
Labels: map[string]string{
loggingconfig.LabelK8sApp: loggingconfig.EmbeddedESName,
},
},
Spec: v1beta2.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
loggingconfig.LabelK8sApp: loggingconfig.EmbeddedESName,
},
},
Replicas: int32Ptr(1),
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Labels: map[string]string{
loggingconfig.LabelK8sApp: loggingconfig.EmbeddedESName,
},
},
Spec: v1.PodSpec{
ServiceAccountName: loggingconfig.EmbeddedESName,
InitContainers: []v1.Container{
{
Name: "init-sysctl",
Image: loggingconfig.BusyboxImage,
ImagePullPolicy: v1.PullIfNotPresent,
Command: []string{"sysctl", "-w", "vm.max_map_count=262144"},
SecurityContext: &v1.SecurityContext{
Privileged: boolPtr(true),
},
},
},
Containers: []v1.Container{
{
Name: loggingconfig.EmbeddedESName,
SecurityContext: &v1.SecurityContext{
Capabilities: &v1.Capabilities{
Add: []v1.Capability{"IPC_LOCK"},
},
},
Image: loggingconfig.ESImage,
Env: []v1.EnvVar{
{
Name: "KUBERNETES_CA_CERTIFICATE_FILE",
Value: "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt",
},
{
Name: "NAMESPACE",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
FieldPath: "metadata.namespace",
},
},
},
{
Name: "CLUSTER_NAME",
Value: "myesdb",
},
{
Name: "DISCOVERY_SERVICE",
Value: loggingconfig.EmbeddedESName,
},
{
Name: "NODE_MASTER",
Value: "true",
},
{
Name: "NODE_DATA",
Value: "true",
},
{
Name: "HTTP_ENABLE",
Value: "true",
},
},
Ports: []v1.ContainerPort{
{
Name: "http",
Protocol: v1.ProtocolTCP,
ContainerPort: 9200,
},
{
Name: "tcp",
Protocol: v1.ProtocolTCP,
ContainerPort: 9300,
},
},
Resources: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
//CPU is always requested as an absolute quantity, never as a relative quantity; 0.1 is the same amount of CPU on a single-core, dual-core, or 48-core machine
v1.ResourceCPU: *resource.NewMilliQuantity(int64(1000), resource.DecimalSI),
//Limits and requests for memory are measured in bytes.
v1.ResourceMemory: *resource.NewQuantity(int64(500*1024*1024), resource.DecimalSI), // unit is byte
},
},
VolumeMounts: []v1.VolumeMount{
{
MountPath: "/data",
Name: "storage",
},
},
},
},
Volumes: []v1.Volume{
{
Name: "storage",
VolumeSource: v1.VolumeSource{
EmptyDir: &v1.EmptyDirVolumeSource{},
},
},
},
RestartPolicy: v1.RestartPolicyAlways,
},
},
},
}
return deployment
}
func newKibanaDeployment(namespace string) *v1beta2.Deployment {
deployment := &v1beta2.Deployment{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: loggingconfig.EmbeddedKibanaName,
},
Spec: v1beta2.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
loggingconfig.LabelK8sApp: loggingconfig.EmbeddedKibanaName,
},
},
Replicas: int32Ptr(1),
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Labels: map[string]string{
loggingconfig.LabelK8sApp: loggingconfig.EmbeddedKibanaName,
},
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: loggingconfig.EmbeddedKibanaName,
Image: loggingconfig.KibanaImage,
Ports: []v1.ContainerPort{
{
Name: "http",
Protocol: v1.ProtocolTCP,
ContainerPort: 5601,
},
},
Env: []v1.EnvVar{
{
Name: "ELASTICSEARCH_URL",
Value: "http://" + loggingconfig.EmbeddedESName + "." + namespace + ":9200",
},
},
},
},
RestartPolicy: v1.RestartPolicyAlways,
},
},
},
}
return deployment
}
func int32Ptr(i int32) *int32 { return &i }
func boolPtr(b bool) *bool { return &b }