-
Notifications
You must be signed in to change notification settings - Fork 719
/
elasticsearch_controller.go
308 lines (269 loc) · 11 KB
/
elasticsearch_controller.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.
package elasticsearch
import (
"context"
"sync/atomic"
pkgerrors "github.com/pkg/errors"
"go.elastic.co/apm"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
esv1 "github.com/elastic/cloud-on-k8s/pkg/apis/elasticsearch/v1"
"github.com/elastic/cloud-on-k8s/pkg/controller/association"
"github.com/elastic/cloud-on-k8s/pkg/controller/common"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/certificates"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/events"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/expectations"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/finalizer"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/keystore"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/license"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/operator"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/reconciler"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/tracing"
commonversion "github.com/elastic/cloud-on-k8s/pkg/controller/common/version"
"github.com/elastic/cloud-on-k8s/pkg/controller/common/watches"
"github.com/elastic/cloud-on-k8s/pkg/controller/elasticsearch/certificates/transport"
"github.com/elastic/cloud-on-k8s/pkg/controller/elasticsearch/driver"
"github.com/elastic/cloud-on-k8s/pkg/controller/elasticsearch/label"
"github.com/elastic/cloud-on-k8s/pkg/controller/elasticsearch/observer"
esreconcile "github.com/elastic/cloud-on-k8s/pkg/controller/elasticsearch/reconcile"
"github.com/elastic/cloud-on-k8s/pkg/controller/elasticsearch/user"
"github.com/elastic/cloud-on-k8s/pkg/controller/elasticsearch/validation"
esversion "github.com/elastic/cloud-on-k8s/pkg/controller/elasticsearch/version"
"github.com/elastic/cloud-on-k8s/pkg/utils/k8s"
ulog "github.com/elastic/cloud-on-k8s/pkg/utils/log"
)
const name = "elasticsearch-controller"
var log = ulog.Log.WithName(name)
// Add creates a new Elasticsearch Controller and adds it to the Manager with default RBAC. The Manager will set fields
// on the Controller and Start it when the Manager is Started.
// this is also called by cmd/main.go
func Add(mgr manager.Manager, params operator.Parameters) error {
reconciler := newReconciler(mgr, params)
c, err := common.NewController(mgr, name, reconciler, params)
if err != nil {
return err
}
return addWatches(c, reconciler)
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager, params operator.Parameters) *ReconcileElasticsearch {
client := mgr.GetClient()
return &ReconcileElasticsearch{
Client: client,
recorder: mgr.GetEventRecorderFor(name),
licenseChecker: license.NewLicenseChecker(client, params.OperatorNamespace),
esObservers: observer.NewManager(params.Tracer),
dynamicWatches: watches.NewDynamicWatches(),
expectations: expectations.NewClustersExpectations(client),
Parameters: params,
}
}
func addWatches(c controller.Controller, r *ReconcileElasticsearch) error {
// Watch for changes to Elasticsearch
if err := c.Watch(
&source.Kind{Type: &esv1.Elasticsearch{}}, &handler.EnqueueRequestForObject{},
); err != nil {
return err
}
// Watch StatefulSets
if err := c.Watch(
&source.Kind{Type: &appsv1.StatefulSet{}}, &handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &esv1.Elasticsearch{},
},
); err != nil {
return err
}
// Watch pods belonging to ES clusters
if err := watches.WatchPods(c, label.ClusterNameLabelName); err != nil {
return err
}
// Watch services
if err := c.Watch(&source.Kind{Type: &corev1.Service{}}, &handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &esv1.Elasticsearch{},
}); err != nil {
return err
}
// Watch owned and soft-owned secrets
if err := c.Watch(&source.Kind{Type: &corev1.Secret{}}, r.dynamicWatches.Secrets); err != nil {
return err
}
if err := r.dynamicWatches.Secrets.AddHandler(&watches.OwnerWatch{
EnqueueRequestForOwner: handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &esv1.Elasticsearch{},
},
}); err != nil {
return err
}
if err := watches.WatchSoftOwnedSecrets(c, esv1.Kind); err != nil {
return err
}
// Trigger a reconciliation when observers report a cluster health change
return c.Watch(observer.WatchClusterHealthChange(r.esObservers), reconciler.GenericEventHandler())
}
var _ reconcile.Reconciler = &ReconcileElasticsearch{}
// ReconcileElasticsearch reconciles an Elasticsearch object
type ReconcileElasticsearch struct {
k8s.Client
operator.Parameters
recorder record.EventRecorder
licenseChecker license.Checker
esObservers *observer.Manager
dynamicWatches watches.DynamicWatches
// expectations help dealing with inconsistencies in our client cache,
// by marking resources updates as expected, and skipping some operations if the cache is not up-to-date.
expectations *expectations.ClustersExpectation
// iteration is the number of times this controller has run its Reconcile method
iteration uint64
}
// Reconcile reads the state of the cluster for an Elasticsearch object and makes changes based on the state read and
// what is in the Elasticsearch.Spec
func (r *ReconcileElasticsearch) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
defer common.LogReconciliationRun(log, request, "es_name", &r.iteration)()
tx, ctx := tracing.NewTransaction(ctx, r.Tracer, request.NamespacedName, "elasticsearch")
defer tracing.EndTransaction(tx)
// Fetch the Elasticsearch instance
var es esv1.Elasticsearch
requeue, err := r.fetchElasticsearchWithAssociations(ctx, request, &es)
if err != nil || requeue {
return reconcile.Result{}, tracing.CaptureError(ctx, err)
}
if common.IsUnmanaged(&es) {
log.Info("Object is currently not managed by this controller. Skipping reconciliation", "namespace", es.Namespace, "es_name", es.Name)
return reconcile.Result{}, nil
}
// Remove any previous Finalizers
if err := finalizer.RemoveAll(r.Client, &es); err != nil {
return reconcile.Result{}, tracing.CaptureError(ctx, err)
}
state := esreconcile.NewState(es)
results := r.internalReconcile(ctx, es, state)
err = r.updateStatus(ctx, es, state)
if err != nil {
if apierrors.IsConflict(err) {
log.V(1).Info("Conflict while updating status", "namespace", es.Namespace, "es_name", es.Name)
return reconcile.Result{Requeue: true}, nil
}
k8s.EmitErrorEvent(r.recorder, err, &es, events.EventReconciliationError, "Reconciliation error: %v", err)
}
return results.WithError(err).Aggregate()
}
func (r *ReconcileElasticsearch) fetchElasticsearchWithAssociations(ctx context.Context, request reconcile.Request, es *esv1.Elasticsearch) (bool, error) {
span, _ := apm.StartSpan(ctx, "fetch_elasticsearch", tracing.SpanTypeApp)
defer span.End()
err := association.FetchWithAssociations(ctx, r.Client, request, es)
if err != nil {
if apierrors.IsNotFound(err) {
// Object not found, cleanup in-memory state. Children resources are garbage-collected either by
// the operator (see `onDelete`), either by k8s through the ownerReference mechanism.
return true, r.onDelete(types.NamespacedName{
Namespace: request.Namespace,
Name: request.Name,
})
}
// Error reading the object - requeue the request.
return true, err
}
return false, nil
}
func (r *ReconcileElasticsearch) internalReconcile(
ctx context.Context,
es esv1.Elasticsearch,
reconcileState *esreconcile.State,
) *reconciler.Results {
results := reconciler.NewResult(ctx)
if es.IsMarkedForDeletion() {
// resource will be deleted, nothing to reconcile
return results.WithError(r.onDelete(k8s.ExtractNamespacedName(&es)))
}
span, ctx := apm.StartSpan(ctx, "validate", tracing.SpanTypeApp)
// this is the same validation as the webhook, but we run it again here in case the webhook has not been configured
err := validation.ValidateElasticsearch(es, r.ExposedNodeLabels)
span.End()
if err != nil {
log.Error(
err,
"Elasticsearch manifest validation failed",
"namespace", es.Namespace,
"es_name", es.Name,
)
reconcileState.UpdateElasticsearchInvalid(err)
return results
}
err = validation.CheckForWarnings(es)
if err != nil {
log.Info(
"Elasticsearch manifest has warnings. Proceed at your own risk. "+err.Error(),
"namespace", es.Namespace,
"es_name", es.Name,
)
reconcileState.AddEvent(corev1.EventTypeWarning, events.EventReasonValidation, err.Error())
}
ver, err := commonversion.Parse(es.Spec.Version)
if err != nil {
return results.WithError(err)
}
supported := esversion.SupportedVersions(ver)
if supported == nil {
return results.WithError(pkgerrors.Errorf("unsupported version: %s", ver))
}
return driver.NewDefaultDriver(driver.DefaultDriverParameters{
OperatorParameters: r.Parameters,
ES: es,
ReconcileState: reconcileState,
Client: r.Client,
Recorder: r.recorder,
Version: ver,
Expectations: r.expectations.ForCluster(k8s.ExtractNamespacedName(&es)),
Observers: r.esObservers,
DynamicWatches: r.dynamicWatches,
SupportedVersions: *supported,
LicenseChecker: r.licenseChecker,
}).Reconcile(ctx)
}
func (r *ReconcileElasticsearch) updateStatus(
ctx context.Context,
es esv1.Elasticsearch,
reconcileState *esreconcile.State,
) error {
span, _ := apm.StartSpan(ctx, "update_status", tracing.SpanTypeApp)
defer span.End()
events, cluster := reconcileState.Apply()
for _, evt := range events {
log.V(1).Info("Recording event", "event", evt)
r.recorder.Event(&es, evt.EventType, evt.Reason, evt.Message)
}
if cluster == nil {
return nil
}
log.V(1).Info("Updating status",
"iteration", atomic.LoadUint64(&r.iteration),
"namespace", es.Namespace,
"es_name", es.Name,
"status", cluster.Status,
)
return common.UpdateStatus(r.Client, cluster)
}
// onDelete garbage collect resources when an Elasticsearch cluster is deleted
func (r *ReconcileElasticsearch) onDelete(es types.NamespacedName) error {
r.expectations.RemoveCluster(es)
r.esObservers.StopObserving(es)
r.dynamicWatches.Secrets.RemoveHandlerForKey(keystore.SecureSettingsWatchName(es))
r.dynamicWatches.Secrets.RemoveHandlerForKey(certificates.CertificateWatchKey(esv1.ESNamer, es.Name))
r.dynamicWatches.Secrets.RemoveHandlerForKey(transport.CustomTransportCertsWatchKey(es))
r.dynamicWatches.Secrets.RemoveHandlerForKey(user.UserProvidedRolesWatchName(es))
r.dynamicWatches.Secrets.RemoveHandlerForKey(user.UserProvidedFileRealmWatchName(es))
return reconciler.GarbageCollectSoftOwnedSecrets(r.Client, es, esv1.Kind)
}