/
reconcile.go
588 lines (511 loc) · 18.3 KB
/
reconcile.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
package indexmanagement
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/ViaQ/logerr/v2/kverrors"
"github.com/go-logr/logr"
batch "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/sets"
"sigs.k8s.io/controller-runtime/pkg/client"
apis "github.com/openshift/elasticsearch-operator/apis/logging/v1"
"github.com/openshift/elasticsearch-operator/internal/constants"
"github.com/openshift/elasticsearch-operator/internal/elasticsearch"
"github.com/openshift/elasticsearch-operator/internal/elasticsearch/esclient"
"github.com/openshift/elasticsearch-operator/internal/manifests/configmap"
"github.com/openshift/elasticsearch-operator/internal/manifests/cronjob"
"github.com/openshift/elasticsearch-operator/internal/manifests/pod"
"github.com/openshift/elasticsearch-operator/internal/manifests/rbac"
"github.com/openshift/elasticsearch-operator/internal/metrics"
esapi "github.com/openshift/elasticsearch-operator/internal/types/elasticsearch"
"github.com/openshift/elasticsearch-operator/internal/utils"
"github.com/openshift/elasticsearch-operator/internal/utils/comparators"
)
const (
indexManagementConfigmap = "indexmanagement-scripts"
defaultShardSize = int32(40)
workingDir = "/tmp/scripts"
jobHistoryLimitFailed int32 = 1
jobHistoryLimitSuccess int32 = 1
)
var (
defaultCPURequest = resource.MustParse("100m")
defaultMemoryRequest = resource.MustParse("32Mi")
millisPerSecond = uint64(1000)
millisPerMinute = uint64(60 * millisPerSecond)
millisPerHour = uint64(millisPerMinute * 60)
millisPerDay = uint64(millisPerHour * 24)
millisPerWeek = uint64(millisPerDay * 7)
// fullExecMode octal 0777
fullExecMode int32 = 0o777
imLabels = map[string]string{
"provider": "openshift",
"component": "indexManagement",
"logging-infra": "indexManagement",
}
)
type rolloverConditions struct {
MaxAge string `json:"max_age,omitempty"`
MaxDocs int32 `json:"max_docs,omitempty"`
MaxSize string `json:"max_size,omitempty"`
}
type IndexManagementRequest struct {
client client.Client
cluster *apis.Elasticsearch
esClient esclient.Client
ll logr.Logger
}
func Reconcile(log logr.Logger, req *apis.Elasticsearch, reqClient client.Client) error {
ll := log.WithValues("cluster", req.Name, "namespace", req.Namespace, "handler", "indexmanagement")
esClient := esclient.NewClient(ll, req.Name, req.Namespace, reqClient)
imr := IndexManagementRequest{
client: reqClient,
esClient: esClient,
cluster: req,
ll: ll,
}
return imr.createOrUpdateIndexManagement()
}
func (imr *IndexManagementRequest) createOrUpdateIndexManagement() error {
if imr.cluster.Spec.IndexManagement == nil {
return nil
}
spec := verifyAndNormalize(imr.cluster)
policies := spec.PolicyMap()
labels := map[string]string{
"cluster-name": imr.cluster.Name,
"component": "elasticsearch",
}
esPods, err := pod.List(context.TODO(), imr.client, imr.cluster.Namespace, labels)
if err != nil {
return err
}
running := false
for _, pod := range esPods {
if pod.Status.Phase == corev1.PodRunning {
running = true
break
}
}
if running {
imr.cullIndexManagement(spec.Mappings, policies)
for _, mapping := range spec.Mappings {
ll := imr.ll.WithValues("mapping", mapping.Name)
// create or update template
if err := imr.createOrUpdateIndexTemplate(mapping); err != nil {
ll.Error(err, "failed to create index template")
return err
}
// TODO: Can we have partial success?
if err := imr.initializeIndexIfNeeded(mapping); err != nil {
ll.Error(err, "Failed to initialize index")
return err
}
}
}
if err := createOrUpdateCurationConfigmap(imr.ll, imr.client, imr.cluster); err != nil {
return err
}
if err := imr.reconcileIndexManagmentRbac(); err != nil {
return err
}
suspend := len(esPods) == 0
primaryShards := elasticsearch.GetDataCount(imr.cluster)
for _, mapping := range spec.Mappings {
policy := policies[mapping.PolicyRef]
ll := imr.ll.WithValues("mapping", mapping.Name, "policy", policy.Name)
if err := imr.reconcileIndexManagementCronjob(policy, mapping, primaryShards, suspend); err != nil {
ll.Error(err, "could not reconcile indexmanagement cronjob")
return err
}
}
return nil
}
func (imr *IndexManagementRequest) cullIndexManagement(mappings []apis.IndexManagementPolicyMappingSpec, policies apis.PolicyMap) {
if err := imr.removeCronJobsForMappings(mappings, policies); err != nil {
imr.ll.Error(err, "Unable to cull cronjobs")
}
mappingNames := sets.NewString()
for _, mapping := range mappings {
mappingNames.Insert(formatTemplateName(mapping.Name))
}
existing, err := imr.esClient.ListTemplates()
if err != nil {
imr.ll.Error(err, "Unable to list existing templates in order to reconcile stale ones")
return
}
difference := existing.Difference(mappingNames)
for _, template := range difference.List() {
if strings.HasPrefix(template, constants.OcpTemplatePrefix) {
if err := imr.esClient.DeleteIndexTemplate(template); err != nil {
imr.ll.Error(err, "Unable to delete stale template in order to reconcile", "template", template)
}
}
}
}
func (imr *IndexManagementRequest) initializeIndexIfNeeded(mapping apis.IndexManagementPolicyMappingSpec) error {
pattern := formatWriteAlias(mapping)
indices, err := imr.esClient.ListIndicesForAlias(pattern)
if err != nil {
return err
}
if len(indices) < 1 {
indexName := fmt.Sprintf("%s-000001", mapping.Name)
primaryShards := int32(elasticsearch.CalculatePrimaryCount(imr.cluster))
replicas := int32(elasticsearch.CalculateReplicaCount(imr.cluster))
index := esapi.NewIndex(indexName, primaryShards, replicas)
index.AddAlias(mapping.Name, false)
index.AddAlias(pattern, true)
for _, alias := range mapping.Aliases {
index.AddAlias(alias, false)
}
return imr.esClient.CreateIndex(indexName, index)
}
return nil
}
func formatTemplateName(name string) string {
return fmt.Sprintf("%s-%s", constants.OcpTemplatePrefix, name)
}
func formatWriteAlias(mapping apis.IndexManagementPolicyMappingSpec) string {
return fmt.Sprintf("%s-write", mapping.Name)
}
func (imr *IndexManagementRequest) createOrUpdateIndexTemplate(mapping apis.IndexManagementPolicyMappingSpec) error {
name := formatTemplateName(mapping.Name)
pattern := fmt.Sprintf("%s*", mapping.Name)
primaryShards := int32(elasticsearch.CalculatePrimaryCount(imr.cluster))
replicas := int32(elasticsearch.CalculateReplicaCount(imr.cluster))
aliases := append(mapping.Aliases, mapping.Name)
template := esapi.NewIndexTemplate(pattern, aliases, primaryShards, replicas)
// check to compare the current index templates vs what we just generated
templates, err := imr.esClient.GetIndexTemplates()
if err != nil {
return err
}
for templateName := range templates {
if templateName == name {
return nil
}
}
return imr.esClient.CreateIndexTemplate(name, template)
}
func (imr *IndexManagementRequest) removeCronJobsForMappings(mappings []apis.IndexManagementPolicyMappingSpec, policies apis.PolicyMap) error {
expected := sets.NewString()
for _, mapping := range mappings {
expected.Insert(fmt.Sprintf("%s-im-%s", imr.cluster.Name, mapping.Name))
expected.Insert(fmt.Sprintf("%s-im-prune-%s", imr.cluster.Name, mapping.Name))
}
cronList, err := cronjob.List(context.TODO(), imr.client, imr.cluster.Namespace, imLabels)
if err != nil {
return kverrors.Wrap(err, "failed to list cron jobs",
"namespace", imr.cluster.Namespace,
"labels", imLabels,
)
}
existing := sets.NewString()
for _, cron := range cronList {
existing.Insert(cron.Name)
}
difference := existing.Difference(expected)
for _, name := range difference.List() {
key := client.ObjectKey{Name: name, Namespace: imr.cluster.Namespace}
err := cronjob.Delete(context.TODO(), imr.client, key)
if err != nil && !apierrors.IsNotFound(err) {
imr.ll.Error(err, "failed to remove cronjob", "namespace", imr.cluster.Namespace, "name", name)
}
}
return nil
}
func createOrUpdateCurationConfigmap(log logr.Logger, apiclient client.Client, cluster *apis.Elasticsearch) error {
data := scriptMap
desired := configmap.New(indexManagementConfigmap, cluster.Namespace, imLabels, data)
cluster.AddOwnerRefTo(desired)
_, err := configmap.CreateOrUpdate(context.TODO(), apiclient, desired, configmap.DataEqual, configmap.MutateDataOnly)
if err != nil {
return kverrors.Wrap(err, "failed to create or update index management configmap",
"cluster", cluster.Name,
"namespace", cluster.Namespace,
)
}
return nil
}
func (imr *IndexManagementRequest) reconcileIndexManagmentRbac() error {
cluster := imr.cluster
client := imr.client
role := rbac.NewRole(
"elasticsearch-index-management",
cluster.Namespace,
rbac.NewPolicyRules(
rbac.NewPolicyRule(
[]string{"elasticsearch.openshift.io"},
[]string{"indices"},
[]string{},
[]string{"*"},
[]string{},
),
),
)
cluster.AddOwnerRefTo(role)
err := rbac.CreateOrUpdateRole(context.TODO(), client, role)
if err != nil {
return kverrors.Wrap(err, "failed to create or update index management role",
"cluster", cluster.Name,
"namespace", cluster.Namespace,
)
}
subject := rbac.NewSubject(
"ServiceAccount",
cluster.Name,
cluster.Namespace,
)
subject.APIGroup = ""
roleBinding := rbac.NewRoleBinding(
role.Name,
role.Namespace,
role.Name,
rbac.NewSubjects(subject),
)
cluster.AddOwnerRefTo(roleBinding)
err = rbac.CreateOrUpdateRoleBinding(context.TODO(), client, roleBinding)
if err != nil {
return kverrors.Wrap(err, "failed to create or update index management rolebinding",
"cluster", cluster.Name,
"namespace", cluster.Namespace,
)
}
return nil
}
func (imr *IndexManagementRequest) reconcileIndexManagementCronjob(policy apis.IndexManagementPolicySpec, mapping apis.IndexManagementPolicyMappingSpec, primaryShards int32, suspend bool) error {
if policy.Phases.Delete == nil && policy.Phases.Hot == nil {
imr.ll.V(1).Info("Skipping indexmanagement cronjob for policymapping; no phases are defined", "policymapping", mapping.Name)
return nil
}
envvars := []corev1.EnvVar{
{Name: "POLICY_MAPPING", Value: mapping.Name},
}
if policy.Phases.Delete != nil {
var (
namespaceCount = 0
namespaceSpecs = make(map[string]string)
namespaceSpecsString = ""
)
if policy.Phases.Delete.Namespaces != nil {
for _, spec := range policy.Phases.Delete.Namespaces {
namespaceSpecs[spec.Namespace] = string(spec.MinAge)
}
namespaceCount = len(policy.Phases.Delete.Namespaces)
namespaceSpecsJSON, _ := json.Marshal(namespaceSpecs)
namespaceSpecsString = string(namespaceSpecsJSON)
}
minAgeMillis, err := calculateMillisForTimeUnit(policy.Phases.Delete.MinAge)
if err != nil {
return err
}
diskThreshold := policy.Phases.Delete.DiskThresholdPercent
if diskThreshold < 0 || diskThreshold > 100 {
err := fmt.Errorf("invalid percentage value")
return kverrors.Wrap(err, ", %d should be between 0 and 100", diskThreshold)
}
envvars = append(envvars,
corev1.EnvVar{Name: "MIN_AGE", Value: strconv.FormatUint(minAgeMillis, 10)},
corev1.EnvVar{Name: "NAMESPACE_SPECS", Value: namespaceSpecsString},
corev1.EnvVar{Name: "DISK_THRESHOLD", Value: strconv.FormatInt(diskThreshold, 10)},
)
metrics.SetIndexRetentionDocumentAge(true, mapping.Name, minAgeMillis/millisPerSecond)
metrics.SetIndexRetentionDeleteNamespaceMetrics(mapping.Name, namespaceCount)
} else {
imr.ll.V(1).Info("Skipping curation management for policymapping; delete phase not defined", "policymapping", mapping.Name)
metrics.SetIndexRetentionDocumentAge(true, mapping.Name, 0)
metrics.SetIndexRetentionDeleteNamespaceMetrics(mapping.Name, 0)
}
if policy.Phases.Hot != nil {
conditions := calculateConditions(policy, primaryShards)
payload, err := json.Marshal(map[string]rolloverConditions{"conditions": conditions})
if err != nil {
return kverrors.Wrap(err, "failed to serialize the rollover conditions to JSON")
}
envvars = append(envvars,
corev1.EnvVar{Name: "PAYLOAD", Value: base64.StdEncoding.EncodeToString(payload)},
)
if policy.Phases.Hot.Actions.Rollover != nil {
maxAgeMillis, _ := calculateMillisForTimeUnit(policy.Phases.Hot.Actions.Rollover.MaxAge)
metrics.SetIndexRetentionDocumentAge(false, mapping.Name, maxAgeMillis/millisPerSecond)
}
} else {
imr.ll.V(1).Info("Skipping rollover management for policymapping; hot phase not defined", "policymapping", mapping.Name)
metrics.SetIndexRetentionDocumentAge(false, mapping.Name, 0)
}
// prune-namespaces cron job
if policy.Phases.Delete != nil && policy.Phases.Delete.Namespaces != nil {
schedule, err := crontabScheduleFor(policy.Phases.Delete.PruneNamespacesInterval)
if err != nil {
return kverrors.Wrap(err, "failed to reconcile prune cronjob", "policymapping", mapping.Name, "namespaceSpec", policy.Phases.Delete.Namespaces)
}
name := fmt.Sprintf("%s-im-prune-%s", imr.cluster.Name, mapping.Name)
script := "./prune-namespaces"
desired := newCronJob(imr.cluster.Name, imr.cluster.Namespace, name, schedule, script, imr.cluster.Spec.Spec.NodeSelector, imr.cluster.Spec.Spec.Tolerations, envvars, suspend)
imr.cluster.AddOwnerRefTo(desired)
err = cronjob.CreateOrUpdate(context.TODO(), imr.client, desired, areCronJobsSame, cronjob.Mutate)
if err != nil {
return kverrors.Wrap(err, "failed to create or update cronjob",
"cluster", desired.Name,
"namespace", desired.Namespace,
)
}
}
// delete & rollover cron job
schedule, err := crontabScheduleFor(policy.PollInterval)
if err != nil {
return kverrors.Wrap(err, "failed to reconcile rollover cronjob", "policymapping", mapping.Name)
}
name := fmt.Sprintf("%s-im-%s", imr.cluster.Name, mapping.Name)
script := formatCmd(policy)
desired := newCronJob(imr.cluster.Name, imr.cluster.Namespace, name, schedule, script, imr.cluster.Spec.Spec.NodeSelector, imr.cluster.Spec.Spec.Tolerations, envvars, suspend)
imr.cluster.AddOwnerRefTo(desired)
err = cronjob.CreateOrUpdate(context.TODO(), imr.client, desired, areCronJobsSame, cronjob.Mutate)
if err != nil {
return kverrors.Wrap(err, "failed to create or update cronjob",
"cluster", desired.Name,
"namespace", desired.Namespace,
)
}
return nil
}
func formatCmd(policy apis.IndexManagementPolicySpec) string {
cmd := ""
if policy.Phases.Delete != nil {
cmd = "./delete"
}
if policy.Phases.Hot != nil {
cmd = "./rollover"
}
if policy.Phases.Delete != nil && policy.Phases.Hot != nil {
cmd = "./delete-then-rollover"
}
return cmd
}
func areCronJobsSame(lhs, rhs *batch.CronJob) bool {
if len(lhs.Spec.JobTemplate.Spec.Template.Spec.Containers) != len(rhs.Spec.JobTemplate.Spec.Template.Spec.Containers) {
return false
}
if !comparators.AreStringMapsSame(lhs.Spec.JobTemplate.Spec.Template.Spec.NodeSelector, rhs.Spec.JobTemplate.Spec.Template.Spec.NodeSelector) {
return false
}
if !comparators.AreTolerationsSame(lhs.Spec.JobTemplate.Spec.Template.Spec.Tolerations, rhs.Spec.JobTemplate.Spec.Template.Spec.Tolerations) {
return false
}
if lhs.Spec.Schedule != rhs.Spec.Schedule {
lhs.Spec.Schedule = rhs.Spec.Schedule
return false
}
if lhs.Spec.Suspend != nil && rhs.Spec.Suspend != nil && *lhs.Spec.Suspend != *rhs.Spec.Suspend {
return false
}
for i, container := range lhs.Spec.JobTemplate.Spec.Template.Spec.Containers {
other := rhs.Spec.JobTemplate.Spec.Template.Spec.Containers[i]
if !areContainersSame(container, other) {
return false
}
}
return true
}
func areContainersSame(container, other corev1.Container) bool {
if container.Name != other.Name {
return false
}
if container.Image != other.Image {
return false
}
if !reflect.DeepEqual(container.Command, other.Command) {
return false
}
if !reflect.DeepEqual(container.Args, other.Args) {
return false
}
if !comparators.AreResourceRequementsSame(container.Resources, other.Resources) {
return false
}
if !comparators.EnvValueEqual(container.Env, other.Env) {
return false
}
return true
}
func newContainer(clusterName, name, image, scriptPath string, envvars []corev1.EnvVar) corev1.Container {
envvars = append(envvars, corev1.EnvVar{Name: "ES_SERVICE", Value: fmt.Sprintf("https://%s:9200", clusterName)})
container := corev1.Container{
Name: name,
Image: image,
ImagePullPolicy: corev1.PullIfNotPresent,
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceMemory: defaultMemoryRequest,
corev1.ResourceCPU: defaultCPURequest,
},
},
WorkingDir: workingDir,
Env: envvars,
Command: []string{"bash"},
Args: []string{
"-c",
scriptPath,
},
VolumeMounts: []corev1.VolumeMount{
{Name: "certs", ReadOnly: true, MountPath: "/etc/indexmanagement/keys"},
{Name: "scripts", ReadOnly: false, MountPath: workingDir},
},
SecurityContext: utils.ContainerSecurityContext(),
}
return container
}
func newCronJob(clusterName, namespace, name, schedule, script string, nodeSelector map[string]string, tolerations []corev1.Toleration, envvars []corev1.EnvVar, suspend bool) *batch.CronJob {
containerName := "indexmanagement"
containers := []corev1.Container{
newContainer(clusterName, containerName, constants.PackagedCuratorImage(), script, envvars),
}
volumes := []corev1.Volume{
{
Name: "certs",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: clusterName,
},
},
},
{
Name: "scripts",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: indexManagementConfigmap,
},
DefaultMode: &fullExecMode,
},
},
},
}
podSpec := pod.NewSpec(clusterName, containers, volumes).
WithNodeSelectors(nodeSelector).
WithTolerations(tolerations...).
WithRestartPolicy(corev1.RestartPolicyNever).
WithRestartPolicy(corev1.RestartPolicyNever).
WithTerminationGracePeriodSeconds(300 * time.Second).
WithSecurityContext(utils.PodSecurityContext()).
Build()
return cronjob.New(name, namespace, imLabels).
WithSuspend(suspend).
WithConcurrencyPolicy(batch.ForbidConcurrent).
WithSuccessfulJobsHistoryLimit(jobHistoryLimitSuccess).
WithFailedJobsHistoryLimit(jobHistoryLimitFailed).
WithSchedule(schedule).
WithBackoffLimit(0).
WithParallelism(1).
WithPodSpec(containerName, podSpec).
Build()
}