/
fluentbit.go
496 lines (471 loc) · 12.8 KB
/
fluentbit.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
package fluentbit
import (
"bytes"
"encoding/json"
"github.com/operator-framework/operator-sdk/pkg/sdk"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/scheme"
"kubesphere.io/fluentbit-operator/cmd/fluentbit-operator/sdkdecorator"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sync"
"text/template"
)
// OwnerDeployment of the daemonset
var OwnerDeployment metav1.Object
var config *fluentBitDeploymentConfig
// ConfigLock used for AppConfig
var ConfigLock sync.Mutex
func initConfig(labels map[string]string) *fluentBitDeploymentConfig {
if config == nil {
config = &fluentBitDeploymentConfig{
Name: "fluent-bit",
Namespace: viper.GetString("fluent-bit.namespace"),
Labels: labels,
}
config.Labels["app"] = "fluent-bit"
}
return config
}
// DeployFluentBit initializes or updates fluent-bit
func DeployFluentBit(labels map[string]string) {
cfg := initConfig(labels)
if !checkIfDaemonSetExist(cfg) {
logrus.Info("Deploying fluent-bit")
if viper.GetBool("fluentbit-operator.rbac") {
sa := newServiceAccount(cfg)
err := controllerutil.SetControllerReference(OwnerDeployment, sa, scheme.Scheme)
logrus.Error(err)
sdkdecorator.CallSdkFunctionWithLogging(sdk.Create)(sa)
cr := newClusterRole(cfg)
err = controllerutil.SetControllerReference(OwnerDeployment, cr, scheme.Scheme)
logrus.Error(err)
sdkdecorator.CallSdkFunctionWithLogging(sdk.Create)(cr)
crb := newClusterRoleBinding(cfg)
err = controllerutil.SetControllerReference(OwnerDeployment, crb, scheme.Scheme)
logrus.Error(err)
sdkdecorator.CallSdkFunctionWithLogging(sdk.Create)(crb)
}
cfgMap, err := newFluentBitConfig(cfg)
if err != nil {
logrus.Error(err)
}
err = controllerutil.SetControllerReference(OwnerDeployment, cfgMap, scheme.Scheme)
logrus.Error(err)
sdkdecorator.CallSdkFunctionWithLogging(sdk.Create)(cfgMap)
CreateOrUpdateAppConfig("", "", "")
ds := newFluentBitDaemonSet(cfg)
err = controllerutil.SetControllerReference(OwnerDeployment, ds, scheme.Scheme)
logrus.Error(err)
sdkdecorator.CallSdkFunctionWithLogging(sdk.Create)(ds)
logrus.Info("Fluent-bit deployed successfully")
} else {
logrus.Info("Updating fluent-bit")
ds := newFluentBitDaemonSet(cfg)
err := controllerutil.SetControllerReference(OwnerDeployment, ds, scheme.Scheme)
logrus.Error(err)
sdkdecorator.CallSdkFunctionWithLogging(sdk.Update)(ds)
logrus.Info("Fluent-bit updated successfully")
}
}
// DeleteFluentBit deletes fluent-bit if it exists
func DeleteFluentBit(labels map[string]string) {
cfg := initConfig(labels)
if checkIfDaemonSetExist(cfg) {
logrus.Info("Deleting fluent-bit")
if viper.GetBool("fluentbit-operator.rbac") {
sdkdecorator.CallSdkFunctionWithLogging(sdk.Delete)(newServiceAccount(cfg))
sdkdecorator.CallSdkFunctionWithLogging(sdk.Delete)(newClusterRole(cfg))
sdkdecorator.CallSdkFunctionWithLogging(sdk.Delete)(newClusterRoleBinding(cfg))
}
cfgMap, err := newFluentBitConfig(cfg)
if err != nil {
logrus.Error(err)
}
sdkdecorator.CallSdkFunctionWithLogging(sdk.Delete)(cfgMap)
DeleteAppConfig()
foregroundDeletion := metav1.DeletePropagationForeground
sdkdecorator.CallSdkFunctionWithLogging(sdk.Delete)(newFluentBitDaemonSet(cfg),
sdk.WithDeleteOptions(&metav1.DeleteOptions{
PropagationPolicy: &foregroundDeletion,
}))
logrus.Info("Fluent-bit deleted successfully")
}
}
type fluentBitDeploymentConfig struct {
Name string
Namespace string
Labels map[string]string
}
type fluentBitConfig struct {
Namespace string
}
func newServiceAccount(cr *fluentBitDeploymentConfig) *corev1.ServiceAccount {
return &corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{
Kind: "ServiceAccount",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "fluentbit",
Namespace: cr.Namespace,
Labels: cr.Labels,
},
}
}
func newClusterRole(cr *fluentBitDeploymentConfig) *rbacv1.ClusterRole {
return &rbacv1.ClusterRole{
TypeMeta: metav1.TypeMeta{
Kind: "ClusterRole",
APIVersion: "rbac.authorization.k8s.io/v1beta1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "LoggingRole",
Namespace: cr.Namespace,
Labels: cr.Labels,
},
Rules: []rbacv1.PolicyRule{
{
Verbs: []string{
"get",
},
APIGroups: []string{""},
Resources: []string{
"pods",
},
},
},
}
}
func newClusterRoleBinding(cr *fluentBitDeploymentConfig) *rbacv1.ClusterRoleBinding {
return &rbacv1.ClusterRoleBinding{
TypeMeta: metav1.TypeMeta{
Kind: "ClusterRoleBinding",
APIVersion: "rbac.authorization.k8s.io/v1beta1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "fluentbit",
Namespace: cr.Namespace,
Labels: cr.Labels,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: "fluentbit",
Namespace: cr.Namespace,
},
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: "LoggingRole",
},
}
}
func generateConfig(input fluentBitConfig) (*string, error) {
output := new(bytes.Buffer)
tmpl, err := template.New("test").Parse(fluentBitConfigTemplate)
if err != nil {
return nil, err
}
err = tmpl.Execute(output, input)
if err != nil {
return nil, err
}
outputString := output.String()
return &outputString, nil
}
func generateSettings(input fluentBitConfig) (*string, error) {
output := new(bytes.Buffer)
tmpl, err := template.New("test").Parse(fluentBitSettingsTemplate)
if err != nil {
return nil, err
}
err = tmpl.Execute(output, input)
if err != nil {
return nil, err
}
outputString := output.String()
return &outputString, nil
}
// DeleteAppConfig thread safe config management
func DeleteAppConfig() {
configMap := &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "fluent-bit-app-config",
Namespace: config.Namespace,
Labels: config.Labels,
},
}
ConfigLock.Lock()
defer ConfigLock.Unlock()
sdkdecorator.CallSdkFunctionWithLogging(sdk.Delete)(configMap)
}
// CreateOrUpdateAppConfig idempotent thread safe config management
func CreateOrUpdateAppConfig(name string, appConfig string, appSettings string) {
configMap := &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "fluent-bit-app-config",
Namespace: config.Namespace,
Labels: config.Labels,
},
}
// Lock for shared fluent-bit config resource
ConfigLock.Lock()
defer ConfigLock.Unlock()
err := sdk.Get(configMap)
if err != nil && !apierrors.IsNotFound(err) {
// Something unexpected happened
logrus.Error(err)
return
}
// Do the changes
if configMap.Data == nil {
configMap.Data = map[string]string{}
}
if name != "" && appConfig != "" {
configMap.Data[name+".conf"] = appConfig
}
if name != "" && appSettings != "" {
configMap.Data["settings.json"] = appSettings
}
// The resource not Found so we create it
if err != nil {
err = controllerutil.SetControllerReference(OwnerDeployment, configMap, scheme.Scheme)
logrus.Error(err)
sdkdecorator.CallSdkFunctionWithLogging(sdk.Create)(configMap)
return
}
// No error we go for update
sdkdecorator.CallSdkFunctionWithLogging(sdk.Update)(configMap)
}
func newFluentBitConfig(cr *fluentBitDeploymentConfig) (*corev1.ConfigMap, error) {
input := fluentBitConfig{
Namespace: cr.Namespace,
}
config, err := generateConfig(input)
if err != nil {
return nil, err
}
settings, err := generateSettings(input)
if err != nil {
return nil, err
}
configMap := &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "fluent-bit-config",
Namespace: cr.Namespace,
Labels: cr.Labels,
},
Data: map[string]string{
"fluent-bit.conf": *config,
"settings.json": *settings,
},
}
return configMap, nil
}
func checkIfDaemonSetExist(cr *fluentBitDeploymentConfig) bool {
fluentbitDaemonSet := &appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{
Kind: "DaemonSet",
APIVersion: "apps/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: cr.Name,
Labels: cr.Labels,
Namespace: cr.Namespace,
},
}
if err := sdk.Get(fluentbitDaemonSet); err != nil {
logrus.Info("FluentBit DaemonSet does not exists!")
logrus.Error(err)
return false
}
logrus.Info("FluentBit DaemonSet already exists!")
return true
}
func newConfigMapReloader() *corev1.Container {
return &corev1.Container{
Name: "config-reloader",
Image: viper.GetString("configmap-reload.image"),
Args: []string{
"-volume-dir=/fluent-bit/app-config/",
"-webhook-url=http://127.0.0.1:24444/api/config.reload",
},
VolumeMounts: []corev1.VolumeMount{
{
Name: "app-config",
MountPath: "/fluent-bit/app-config/",
},
},
}
}
func generateVolumeMounts() (v []corev1.VolumeMount) {
v = []corev1.VolumeMount{
{
Name: "varlibcontainers",
ReadOnly: true,
MountPath: viper.GetString("fluent-bit.containersLogMountedPath"),
},
{
Name: "config",
MountPath: "/fluent-bit/etc/fluent-bit.conf",
SubPath: "fluent-bit.conf",
},
{
Name: "app-config",
MountPath: "/fluent-bit/app-config/",
},
{
Name: "positions",
MountPath: "/tail-db",
},
{
Name: "varlogs",
ReadOnly: true,
MountPath: "/var/log/",
},
}
return
}
func generateVolume() (v []corev1.Volume) {
v = []corev1.Volume{
{
Name: "varlibcontainers",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: viper.GetString("fluent-bit.containersLogMountedPath"),
},
},
},
{
Name: "config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: "fluent-bit-config",
},
},
},
},
{
Name: "app-config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: "fluent-bit-app-config",
},
},
},
},
{
Name: "varlogs",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/var/log",
},
},
},
{
Name: "positions",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
}
return
}
// TODO in case of rbac add created serviceAccount name
func newFluentBitDaemonSet(cr *fluentBitDeploymentConfig) *appsv1.DaemonSet {
// fluent bit image pull policy
pullPolicy := corev1.PullPolicy(viper.GetString("fluent-bit.pullPolicy"))
// bad parameter will be interpreted as IfNotPresent
if pullPolicy != corev1.PullAlways && pullPolicy != corev1.PullNever && pullPolicy != corev1.PullIfNotPresent {
pullPolicy = corev1.PullIfNotPresent
}
// fluent bit tolerations
var tolerations []corev1.Toleration
tStr, err := json.Marshal(viper.Get("fluent-bit.tolerations"))
if err != nil {
logrus.Println("error:", err)
tolerations = []corev1.Toleration{{Operator: "Exists"}}
} else {
err := json.Unmarshal(tStr, &tolerations)
if err != nil {
logrus.Println("error:", err)
tolerations = []corev1.Toleration{{Operator: "Exists"}}
}
}
return &appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{
Kind: "DaemonSet",
APIVersion: "apps/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: cr.Name,
Namespace: cr.Namespace,
Labels: cr.Labels,
},
Spec: appsv1.DaemonSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: cr.Labels,
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: cr.Labels,
// TODO Move annotations to configuration
Annotations: map[string]string{
"prometheus.io/scrape": "true",
"prometheus.io/path": "/api/v1/metrics/prometheus",
"prometheus.io/port": "2020",
},
},
Spec: corev1.PodSpec{
ServiceAccountName: "fluentbit",
Volumes: generateVolume(),
Containers: []corev1.Container{
{
// TODO move to configuration
Name: "fluent-bit",
Image: viper.GetString("fluent-bit.image"),
// TODO get from config translate to const
ImagePullPolicy: pullPolicy,
Ports: []corev1.ContainerPort{
{
Name: "monitor",
ContainerPort: 2020,
Protocol: "TCP",
},
},
// TODO Get this from config
Resources: corev1.ResourceRequirements{
Limits: nil,
Requests: nil,
},
VolumeMounts: generateVolumeMounts(),
},
*newConfigMapReloader(),
},
Tolerations: tolerations,
},
},
},
}
}