/
statefulset.go
694 lines (641 loc) · 24.9 KB
/
statefulset.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
package k8sutils
import (
"context"
"fmt"
"path"
"sort"
"strconv"
"strings"
commonapi "github.com/cafe24-dhkim05/redis-operator/api"
redisv1beta2 "github.com/cafe24-dhkim05/redis-operator/api/v1beta2"
"github.com/banzaicloud/k8s-objectmatcher/patch"
"github.com/go-logr/logr"
"github.com/pkg/errors"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
)
const (
redisExporterContainer = "redis-exporter"
)
// statefulSetParameters will define statefulsets input params
type statefulSetParameters struct {
Replicas *int32
ClusterMode bool
NodeConfVolume bool
Metadata metav1.ObjectMeta
NodeSelector map[string]string
PodSecurityContext *corev1.PodSecurityContext
PriorityClassName string
Affinity *corev1.Affinity
Tolerations *[]corev1.Toleration
EnableMetrics bool
PersistentVolumeClaim corev1.PersistentVolumeClaim
NodeConfPersistentVolumeClaim corev1.PersistentVolumeClaim
ImagePullSecrets *[]corev1.LocalObjectReference
ExternalConfig *string
ServiceAccountName *string
UpdateStrategy appsv1.StatefulSetUpdateStrategy
RecreateStatefulSet bool
InitContainers *[]redisv1beta2.InitContainer
TerminationGracePeriodSeconds *int64
}
// containerParameters will define container input params
type containerParameters struct {
Image string
ImagePullPolicy corev1.PullPolicy
Resources *corev1.ResourceRequirements
SecurityContext *corev1.SecurityContext
RedisExporterImage string
RedisExporterImagePullPolicy corev1.PullPolicy
RedisExporterResources *corev1.ResourceRequirements
RedisExporterEnv *[]corev1.EnvVar
Role string
EnabledPassword *bool
SecretName *string
SecretKey *string
PersistenceEnabled *bool
TLSConfig *redisv1beta2.TLSConfig
ACLConfig *redisv1beta2.ACLConfig
ReadinessProbe *commonapi.Probe
LivenessProbe *commonapi.Probe
AdditionalEnvVariable *[]corev1.EnvVar
AdditionalVolume []corev1.Volume
AdditionalMountPath []corev1.VolumeMount
}
type initContainerParameters struct {
Enabled *bool
Image string
ImagePullPolicy corev1.PullPolicy
Resources *corev1.ResourceRequirements
Role string
Command []string
Arguments []string
PersistenceEnabled *bool
AdditionalEnvVariable *[]corev1.EnvVar
AdditionalVolume []corev1.Volume
AdditionalMountPath []corev1.VolumeMount
}
// CreateOrUpdateStateFul method will create or update Redis service
func CreateOrUpdateStateFul(namespace string, stsMeta metav1.ObjectMeta, params statefulSetParameters, ownerDef metav1.OwnerReference, initcontainerParams initContainerParameters, containerParams containerParameters, sidecars *[]redisv1beta2.Sidecar) error {
logger := statefulSetLogger(namespace, stsMeta.Name)
storedStateful, err := GetStatefulSet(namespace, stsMeta.Name)
statefulSetDef := generateStatefulSetsDef(stsMeta, params, ownerDef, initcontainerParams, containerParams, getSidecars(sidecars))
if err != nil {
if err := patch.DefaultAnnotator.SetLastAppliedAnnotation(statefulSetDef); err != nil {
logger.Error(err, "Unable to patch redis statefulset with comparison object")
return err
}
if apierrors.IsNotFound(err) {
return createStatefulSet(namespace, statefulSetDef)
}
return err
}
return patchStatefulSet(storedStateful, statefulSetDef, namespace, params.RecreateStatefulSet)
}
// patchStateFulSet will patch Redis Kubernetes StateFulSet
func patchStatefulSet(storedStateful *appsv1.StatefulSet, newStateful *appsv1.StatefulSet, namespace string, recreateStateFulSet bool) error {
logger := statefulSetLogger(namespace, storedStateful.Name)
// We want to try and keep this atomic as possible.
newStateful.ResourceVersion = storedStateful.ResourceVersion
newStateful.CreationTimestamp = storedStateful.CreationTimestamp
newStateful.ManagedFields = storedStateful.ManagedFields
patchResult, err := patch.DefaultPatchMaker.Calculate(storedStateful, newStateful,
patch.IgnoreStatusFields(),
patch.IgnoreVolumeClaimTemplateTypeMetaAndStatus(),
patch.IgnoreField("kind"),
patch.IgnoreField("apiVersion"),
)
if err != nil {
logger.Error(err, "Unable to patch redis statefulset with comparison object")
return err
}
if !patchResult.IsEmpty() {
logger.V(1).Info("Changes in statefulset Detected, Updating...", "patch", string(patchResult.Patch))
if len(newStateful.Spec.VolumeClaimTemplates) >= 1 && len(newStateful.Spec.VolumeClaimTemplates) == len(storedStateful.Spec.VolumeClaimTemplates) {
// Field is immutable therefore we MUST keep it as is.
if !apiequality.Semantic.DeepEqual(newStateful.Spec.VolumeClaimTemplates[0].Spec, storedStateful.Spec.VolumeClaimTemplates[0].Spec) {
// resize pvc
// 1.Get the data already stored internally
// 2.Get the desired data
// 3.Start querying the pvc list when you find data inconsistencies
// 3.1 Comparison using real pvc capacity and desired data
// 3.1.1 Update if you find inconsistencies
// 3.2 Writing successful updates to internal
// 4. Set to old VolumeClaimTemplates to update.Prevent update error reporting
// 5. Set to old annotations to update
annotations := storedStateful.Annotations
if annotations == nil {
annotations = map[string]string{
"storageCapacity": "0",
}
}
storedCapacity, _ := strconv.ParseInt(annotations["storageCapacity"], 0, 64)
if len(newStateful.Spec.VolumeClaimTemplates) != 0 {
stateCapacity := newStateful.Spec.VolumeClaimTemplates[0].Spec.Resources.Requests.Storage().Value()
if storedCapacity != stateCapacity {
listOpt := metav1.ListOptions{
LabelSelector: labels.FormatLabels(
map[string]string{
"app": storedStateful.Name,
"app.kubernetes.io/component": "redis",
"app.kubernetes.io/name": storedStateful.Name,
},
),
}
pvcs, err := generateK8sClient().CoreV1().PersistentVolumeClaims(storedStateful.Namespace).List(context.Background(), listOpt)
if err != nil {
return err
}
updateFailed := false
realUpdate := false
for _, pvc := range pvcs.Items {
realCapacity := pvc.Spec.Resources.Requests.Storage().Value()
if realCapacity != stateCapacity {
realUpdate = true
pvc.Spec.Resources.Requests = newStateful.Spec.VolumeClaimTemplates[0].Spec.Resources.Requests
_, err = generateK8sClient().CoreV1().PersistentVolumeClaims(storedStateful.Namespace).Update(context.Background(), &pvc, metav1.UpdateOptions{})
if err != nil {
if !updateFailed {
updateFailed = true
}
logger.Error(fmt.Errorf("redis:%s resize pvc failed:%s", storedStateful.Name, err.Error()), "")
}
}
}
if !updateFailed && len(pvcs.Items) != 0 {
annotations["storageCapacity"] = fmt.Sprintf("%d", stateCapacity)
storedStateful.Annotations = annotations
if realUpdate {
logger.Info(fmt.Sprintf("redis:%s resize pvc from %d to %d", storedStateful.Name, storedCapacity, stateCapacity))
} else {
logger.Info(fmt.Sprintf("redis:%s resize noting,just set annotations", storedStateful.Name))
}
}
}
}
}
newStateful.Annotations["storageCapacity"] = storedStateful.Annotations["storageCapacity"]
// set stored.volumeClaimTemplates
newStateful.Spec.VolumeClaimTemplates = storedStateful.Spec.VolumeClaimTemplates
}
for key, value := range storedStateful.Annotations {
if _, present := newStateful.Annotations[key]; !present {
newStateful.Annotations[key] = value
}
}
if err := patch.DefaultAnnotator.SetLastAppliedAnnotation(newStateful); err != nil {
logger.Error(err, "Unable to patch redis statefulset with comparison object")
return err
}
return updateStatefulSet(namespace, newStateful, recreateStateFulSet)
}
logger.V(1).Info("Reconciliation Complete, no Changes required.")
return nil
}
// generateStatefulSetsDef generates the statefulsets definition of Redis
func generateStatefulSetsDef(stsMeta metav1.ObjectMeta, params statefulSetParameters, ownerDef metav1.OwnerReference, initcontainerParams initContainerParameters, containerParams containerParameters, sidecars []redisv1beta2.Sidecar) *appsv1.StatefulSet {
statefulset := &appsv1.StatefulSet{
TypeMeta: generateMetaInformation("StatefulSet", "apps/v1"),
ObjectMeta: stsMeta,
Spec: appsv1.StatefulSetSpec{
Selector: LabelSelectors(stsMeta.GetLabels()),
ServiceName: fmt.Sprintf("%s-headless", stsMeta.Name),
Replicas: params.Replicas,
UpdateStrategy: params.UpdateStrategy,
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: stsMeta.GetLabels(),
Annotations: generateStatefulSetsAnots(stsMeta),
},
Spec: corev1.PodSpec{
Containers: generateContainerDef(
stsMeta.GetName(),
containerParams,
params.ClusterMode,
params.NodeConfVolume,
params.EnableMetrics,
params.ExternalConfig,
containerParams.AdditionalMountPath,
sidecars,
),
NodeSelector: params.NodeSelector,
SecurityContext: params.PodSecurityContext,
PriorityClassName: params.PriorityClassName,
Affinity: params.Affinity,
TerminationGracePeriodSeconds: params.TerminationGracePeriodSeconds,
},
},
},
}
if initcontainerParams.Enabled != nil && *initcontainerParams.Enabled {
statefulset.Spec.Template.Spec.InitContainers = generateInitContainerDef(stsMeta.GetName(), initcontainerParams, initcontainerParams.AdditionalMountPath)
}
if params.Tolerations != nil {
statefulset.Spec.Template.Spec.Tolerations = *params.Tolerations
}
if params.ImagePullSecrets != nil {
statefulset.Spec.Template.Spec.ImagePullSecrets = *params.ImagePullSecrets
}
if containerParams.PersistenceEnabled != nil && params.ClusterMode && params.NodeConfVolume {
statefulset.Spec.VolumeClaimTemplates = append(statefulset.Spec.VolumeClaimTemplates, createPVCTemplate("node-conf", stsMeta, params.NodeConfPersistentVolumeClaim))
}
if containerParams.PersistenceEnabled != nil && *containerParams.PersistenceEnabled {
statefulset.Spec.VolumeClaimTemplates = append(statefulset.Spec.VolumeClaimTemplates, createPVCTemplate(stsMeta.GetName(), stsMeta, params.PersistentVolumeClaim))
}
if params.ExternalConfig != nil {
statefulset.Spec.Template.Spec.Volumes = getExternalConfig(*params.ExternalConfig)
}
if containerParams.AdditionalVolume != nil {
statefulset.Spec.Template.Spec.Volumes = append(statefulset.Spec.Template.Spec.Volumes, containerParams.AdditionalVolume...)
}
if containerParams.TLSConfig != nil {
statefulset.Spec.Template.Spec.Volumes = append(statefulset.Spec.Template.Spec.Volumes,
corev1.Volume{
Name: "tls-certs",
VolumeSource: corev1.VolumeSource{
Secret: &containerParams.TLSConfig.Secret,
},
})
}
if containerParams.ACLConfig != nil && containerParams.ACLConfig.Secret != nil {
statefulset.Spec.Template.Spec.Volumes = append(statefulset.Spec.Template.Spec.Volumes,
corev1.Volume{
Name: "acl-secret",
VolumeSource: corev1.VolumeSource{
Secret: containerParams.ACLConfig.Secret,
},
})
}
if params.ServiceAccountName != nil {
statefulset.Spec.Template.Spec.ServiceAccountName = *params.ServiceAccountName
}
AddOwnerRefToObject(statefulset, ownerDef)
return statefulset
}
// getExternalConfig will return the redis external configuration
func getExternalConfig(configMapName string) []corev1.Volume {
return []corev1.Volume{
{
Name: "external-config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: configMapName,
},
},
},
},
}
}
// createPVCTemplate will create the persistent volume claim template
func createPVCTemplate(volumeName string, stsMeta metav1.ObjectMeta, storageSpec corev1.PersistentVolumeClaim) corev1.PersistentVolumeClaim {
pvcTemplate := storageSpec
pvcTemplate.CreationTimestamp = metav1.Time{}
pvcTemplate.Name = volumeName
pvcTemplate.Labels = stsMeta.GetLabels()
// We want the same annoations as the StatefulSet here
pvcTemplate.Annotations = generateStatefulSetsAnots(stsMeta)
if storageSpec.Spec.AccessModes == nil {
pvcTemplate.Spec.AccessModes = []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}
} else {
pvcTemplate.Spec.AccessModes = storageSpec.Spec.AccessModes
}
pvcVolumeMode := corev1.PersistentVolumeFilesystem
if storageSpec.Spec.VolumeMode != nil {
pvcVolumeMode = *storageSpec.Spec.VolumeMode
}
pvcTemplate.Spec.VolumeMode = &pvcVolumeMode
pvcTemplate.Spec.Resources = storageSpec.Spec.Resources
pvcTemplate.Spec.Selector = storageSpec.Spec.Selector
return pvcTemplate
}
// generateContainerDef generates container definition for Redis
func generateContainerDef(name string, containerParams containerParameters, clusterMode, nodeConfVolume, enableMetrics bool, externalConfig *string, mountpath []corev1.VolumeMount, sidecars []redisv1beta2.Sidecar) []corev1.Container {
containerDefinition := []corev1.Container{
{
Name: name,
Image: containerParams.Image,
ImagePullPolicy: containerParams.ImagePullPolicy,
SecurityContext: containerParams.SecurityContext,
Env: getEnvironmentVariables(
containerParams.Role,
false,
containerParams.EnabledPassword,
containerParams.SecretName,
containerParams.SecretKey,
containerParams.PersistenceEnabled,
containerParams.RedisExporterEnv,
containerParams.TLSConfig,
containerParams.ACLConfig,
),
ReadinessProbe: getProbeInfo(containerParams.ReadinessProbe),
LivenessProbe: getProbeInfo(containerParams.LivenessProbe),
VolumeMounts: getVolumeMount(name, containerParams.PersistenceEnabled, clusterMode, nodeConfVolume, externalConfig, mountpath, containerParams.TLSConfig, containerParams.ACLConfig),
},
}
if containerParams.Resources != nil {
containerDefinition[0].Resources = *containerParams.Resources
}
if enableMetrics {
containerDefinition = append(containerDefinition, enableRedisMonitoring(containerParams))
}
for _, sidecar := range sidecars {
container := corev1.Container{
Name: sidecar.Name,
Image: sidecar.Image,
ImagePullPolicy: sidecar.ImagePullPolicy,
}
if sidecar.Command != nil {
container.Command = sidecar.Command
}
if sidecar.Ports != nil {
container.Ports = append(container.Ports, *sidecar.Ports...)
}
if sidecar.Volumes != nil {
container.VolumeMounts = *sidecar.Volumes
}
if sidecar.Resources != nil {
container.Resources = *sidecar.Resources
}
if sidecar.EnvVars != nil {
container.Env = *sidecar.EnvVars
}
containerDefinition = append(containerDefinition, container)
}
if containerParams.AdditionalEnvVariable != nil {
containerDefinition[0].Env = append(containerDefinition[0].Env, *containerParams.AdditionalEnvVariable...)
}
return containerDefinition
}
func generateInitContainerDef(name string, initcontainerParams initContainerParameters, mountpath []corev1.VolumeMount) []corev1.Container {
initcontainerDefinition := []corev1.Container{
{
Name: "init" + name,
Image: initcontainerParams.Image,
ImagePullPolicy: initcontainerParams.ImagePullPolicy,
Command: initcontainerParams.Command,
Args: initcontainerParams.Arguments,
VolumeMounts: getVolumeMount(name, initcontainerParams.PersistenceEnabled, false, false, nil, mountpath, nil, nil),
},
}
if initcontainerParams.Resources != nil {
initcontainerDefinition[0].Resources = *initcontainerParams.Resources
}
if initcontainerParams.AdditionalEnvVariable != nil {
initcontainerDefinition[0].Env = append(initcontainerDefinition[0].Env, *initcontainerParams.AdditionalEnvVariable...)
}
return initcontainerDefinition
}
func GenerateTLSEnvironmentVariables(tlsconfig *redisv1beta2.TLSConfig) []corev1.EnvVar {
var envVars []corev1.EnvVar
root := "/tls/"
// get and set Defaults
caCert := "ca.crt"
tlsCert := "tls.crt"
tlsCertKey := "tls.key"
if tlsconfig.CaKeyFile != "" {
caCert = tlsconfig.CaKeyFile
}
if tlsconfig.CertKeyFile != "" {
tlsCert = tlsconfig.CertKeyFile
}
if tlsconfig.KeyFile != "" {
tlsCertKey = tlsconfig.KeyFile
}
envVars = append(envVars, corev1.EnvVar{
Name: "TLS_MODE",
Value: "true",
})
envVars = append(envVars, corev1.EnvVar{
Name: "REDIS_TLS_CA_KEY",
Value: path.Join(root, caCert),
})
envVars = append(envVars, corev1.EnvVar{
Name: "REDIS_TLS_CERT",
Value: path.Join(root, tlsCert),
})
envVars = append(envVars, corev1.EnvVar{
Name: "REDIS_TLS_CERT_KEY",
Value: path.Join(root, tlsCertKey),
})
return envVars
}
// enableRedisMonitoring will add Redis Exporter as sidecar container
func enableRedisMonitoring(params containerParameters) corev1.Container {
exporterDefinition := corev1.Container{
Name: redisExporterContainer,
Image: params.RedisExporterImage,
ImagePullPolicy: params.RedisExporterImagePullPolicy,
Env: getEnvironmentVariables(
params.Role,
true,
params.EnabledPassword,
params.SecretName,
params.SecretKey,
params.PersistenceEnabled,
params.RedisExporterEnv,
params.TLSConfig,
params.ACLConfig,
),
VolumeMounts: getVolumeMount("", nil, false, false, nil, params.AdditionalMountPath, params.TLSConfig, params.ACLConfig), // We need/want the tls-certs but we DON'T need the PVC (if one is available)
Ports: []corev1.ContainerPort{
{
Name: redisExporterPortName,
ContainerPort: redisExporterPort,
Protocol: corev1.ProtocolTCP,
},
},
}
if params.RedisExporterResources != nil {
exporterDefinition.Resources = *params.RedisExporterResources
}
return exporterDefinition
}
// getVolumeMount gives information about persistence mount
func getVolumeMount(name string, persistenceEnabled *bool, clusterMode bool, nodeConfVolume bool, externalConfig *string, mountpath []corev1.VolumeMount, tlsConfig *redisv1beta2.TLSConfig, aclConfig *redisv1beta2.ACLConfig) []corev1.VolumeMount {
var VolumeMounts []corev1.VolumeMount
if persistenceEnabled != nil && clusterMode && nodeConfVolume {
VolumeMounts = append(VolumeMounts, corev1.VolumeMount{
Name: "node-conf",
MountPath: "/node-conf",
})
}
if persistenceEnabled != nil && *persistenceEnabled {
VolumeMounts = append(VolumeMounts, corev1.VolumeMount{
Name: name,
MountPath: "/data",
})
}
if tlsConfig != nil {
VolumeMounts = append(VolumeMounts, corev1.VolumeMount{
Name: "tls-certs",
ReadOnly: true,
MountPath: "/tls",
})
}
if aclConfig != nil {
VolumeMounts = append(VolumeMounts, corev1.VolumeMount{
Name: "acl-secret",
MountPath: "/etc/redis/user.acl",
SubPath: "user.acl",
})
}
if externalConfig != nil {
VolumeMounts = append(VolumeMounts, corev1.VolumeMount{
Name: "external-config",
MountPath: "/etc/redis/external.conf.d",
})
}
VolumeMounts = append(VolumeMounts, mountpath...)
return VolumeMounts
}
// getProbeInfo generate probe for Redis StatefulSet
func getProbeInfo(probe *commonapi.Probe) *corev1.Probe {
return &corev1.Probe{
InitialDelaySeconds: probe.InitialDelaySeconds,
PeriodSeconds: probe.PeriodSeconds,
FailureThreshold: probe.FailureThreshold,
TimeoutSeconds: probe.TimeoutSeconds,
SuccessThreshold: probe.SuccessThreshold,
ProbeHandler: corev1.ProbeHandler{
Exec: &corev1.ExecAction{
Command: []string{
"bash",
"/usr/bin/healthcheck.sh",
},
},
},
}
}
// getEnvironmentVariables returns all the required Environment Variables
func getEnvironmentVariables(role string, enabledMetric bool, enabledPassword *bool, secretName *string, secretKey *string, persistenceEnabled *bool, exporterEnvVar *[]corev1.EnvVar, tlsConfig *redisv1beta2.TLSConfig, aclConfig *redisv1beta2.ACLConfig) []corev1.EnvVar {
envVars := []corev1.EnvVar{
{Name: "SERVER_MODE", Value: role},
{Name: "SETUP_MODE", Value: role},
}
var redisHost string
if role == "sentinel" {
redisHost = "redis://localhost:" + strconv.Itoa(sentinelPort)
} else {
redisHost = "redis://localhost:" + strconv.Itoa(redisPort)
}
if tlsConfig != nil {
envVars = append(envVars, GenerateTLSEnvironmentVariables(tlsConfig)...)
if enabledMetric {
envVars = append(envVars, corev1.EnvVar{
Name: "REDIS_EXPORTER_TLS_CLIENT_KEY_FILE",
Value: "/tls/tls.key",
})
envVars = append(envVars, corev1.EnvVar{
Name: "REDIS_EXPORTER_TLS_CLIENT_CERT_FILE",
Value: "/tls/tls.crt",
})
envVars = append(envVars, corev1.EnvVar{
Name: "REDIS_EXPORTER_TLS_CA_CERT_FILE",
Value: "/tls/ca.crt",
})
envVars = append(envVars, corev1.EnvVar{
Name: "REDIS_EXPORTER_SKIP_TLS_VERIFICATION",
Value: "true",
})
}
}
if aclConfig != nil {
envVars = append(envVars, corev1.EnvVar{
Name: "ACL_MODE",
Value: "true",
})
}
envVars = append(envVars, corev1.EnvVar{
Name: "REDIS_ADDR",
Value: redisHost,
})
if enabledPassword != nil && *enabledPassword {
envVars = append(envVars, corev1.EnvVar{
Name: "REDIS_PASSWORD",
ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{
Name: *secretName,
},
Key: *secretKey,
},
},
})
}
if persistenceEnabled != nil && *persistenceEnabled {
envVars = append(envVars, corev1.EnvVar{Name: "PERSISTENCE_ENABLED", Value: "true"})
}
if exporterEnvVar != nil {
envVars = append(envVars, *exporterEnvVar...)
}
sort.SliceStable(envVars, func(i, j int) bool {
return envVars[i].Name < envVars[j].Name
})
return envVars
}
// createStatefulSet is a method to create statefulset in Kubernetes
func createStatefulSet(namespace string, stateful *appsv1.StatefulSet) error {
logger := statefulSetLogger(namespace, stateful.Name)
_, err := generateK8sClient().AppsV1().StatefulSets(namespace).Create(context.TODO(), stateful, metav1.CreateOptions{})
if err != nil {
logger.Error(err, "Redis stateful creation failed")
return err
}
logger.V(1).Info("Redis stateful successfully created")
return nil
}
// updateStatefulSet is a method to update statefulset in Kubernetes
func updateStatefulSet(namespace string, stateful *appsv1.StatefulSet, recreateStateFulSet bool) error {
logger := statefulSetLogger(namespace, stateful.Name)
_, err := generateK8sClient().AppsV1().StatefulSets(namespace).Update(context.TODO(), stateful, metav1.UpdateOptions{})
if recreateStateFulSet {
sErr, ok := err.(*apierrors.StatusError)
if ok && sErr.ErrStatus.Code == 422 && sErr.ErrStatus.Reason == metav1.StatusReasonInvalid {
failMsg := make([]string, len(sErr.ErrStatus.Details.Causes))
for messageCount, cause := range sErr.ErrStatus.Details.Causes {
failMsg[messageCount] = cause.Message
}
logger.V(1).Info("recreating StatefulSet because the update operation wasn't possible", "reason", strings.Join(failMsg, ", "))
propagationPolicy := metav1.DeletePropagationForeground
if err := generateK8sClient().AppsV1().StatefulSets(namespace).Delete(context.TODO(), stateful.GetName(), metav1.DeleteOptions{PropagationPolicy: &propagationPolicy}); err != nil {
return errors.Wrap(err, "failed to delete StatefulSet to avoid forbidden action")
}
}
}
if err != nil {
logger.Error(err, "Redis statefulset update failed")
return err
}
logger.V(1).Info("Redis statefulset successfully updated ")
return nil
}
// GetStateFulSet is a method to get statefulset in Kubernetes
func GetStatefulSet(namespace string, stateful string) (*appsv1.StatefulSet, error) {
logger := statefulSetLogger(namespace, stateful)
getOpts := metav1.GetOptions{
TypeMeta: generateMetaInformation("StatefulSet", "apps/v1"),
}
statefulInfo, err := generateK8sClient().AppsV1().StatefulSets(namespace).Get(context.TODO(), stateful, getOpts)
if err != nil {
logger.Info("Redis statefulset get action failed")
return nil, err
}
logger.V(1).Info("Redis statefulset get action was successful")
return statefulInfo, nil
}
// statefulSetLogger will generate logging interface for Statfulsets
func statefulSetLogger(namespace string, name string) logr.Logger {
reqLogger := log.WithValues("Request.StatefulSet.Namespace", namespace, "Request.StatefulSet.Name", name)
return reqLogger
}
func getSidecars(sidecars *[]redisv1beta2.Sidecar) []redisv1beta2.Sidecar {
if sidecars == nil {
return []redisv1beta2.Sidecar{}
}
return *sidecars
}