-
Notifications
You must be signed in to change notification settings - Fork 200
/
componenttemplate.go
278 lines (245 loc) · 9.07 KB
/
componenttemplate.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
package reconcilers
import (
"context"
"fmt"
"time"
opsterv1 "github.com/Opster/opensearch-k8s-operator/opensearch-operator/api/v1"
"github.com/Opster/opensearch-k8s-operator/opensearch-operator/opensearch-gateway/services"
"github.com/Opster/opensearch-k8s-operator/opensearch-operator/pkg/helpers"
"github.com/Opster/opensearch-k8s-operator/opensearch-operator/pkg/reconcilers/k8s"
"github.com/Opster/opensearch-k8s-operator/opensearch-operator/pkg/reconcilers/util"
"github.com/cisco-open/operator-tools/pkg/reconciler"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"k8s.io/utils/pointer"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
)
const (
opensearchComponentTemplateExists = "component template already exists in OpenSearch; not modifying"
opensearchComponentTemplateNameMismatch = "OpensearchComponentTemplateNameMismatch"
)
type ComponentTemplateReconciler struct {
client k8s.K8sClient
ReconcilerOptions
ctx context.Context
osClient *services.OsClusterClient
recorder record.EventRecorder
instance *opsterv1.OpensearchComponentTemplate
cluster *opsterv1.OpenSearchCluster
logger logr.Logger
}
func NewComponentTemplateReconciler(
ctx context.Context,
client client.Client,
recorder record.EventRecorder,
instance *opsterv1.OpensearchComponentTemplate,
opts ...ReconcilerOption,
) *ComponentTemplateReconciler {
options := ReconcilerOptions{}
options.apply(opts...)
return &ComponentTemplateReconciler{
client: k8s.NewK8sClient(client, ctx, reconciler.WithLog(log.FromContext(ctx).WithValues("reconciler", "role"))),
ReconcilerOptions: options,
ctx: ctx,
recorder: recorder,
instance: instance,
logger: log.FromContext(ctx).WithValues("reconciler", "componenttemplate"),
}
}
func (r *ComponentTemplateReconciler) Reconcile() (result ctrl.Result, err error) {
var reason string
defer func() {
if !pointer.BoolDeref(r.updateStatus, true) {
return
}
// When the reconciler is done, figure out what the state of the resource
// is and set it in the state field accordingly.
err := r.client.UdateObjectStatus(r.instance, func(object client.Object) {
instance := object.(*opsterv1.OpensearchComponentTemplate)
instance.Status.Reason = reason
if err != nil {
instance.Status.State = opsterv1.OpensearchComponentTemplateError
}
if result.Requeue && result.RequeueAfter == 10*time.Second {
instance.Status.State = opsterv1.OpensearchComponentTemplatePending
}
if err == nil && result.RequeueAfter == 30*time.Second {
instance.Status.State = opsterv1.OpensearchComponentTemplateCreated
}
if reason == opensearchComponentTemplateExists {
instance.Status.State = opsterv1.OpensearchComponentTemplateIgnored
}
})
if err != nil {
r.logger.Error(err, "failed to update status")
}
}()
if r.instance.Spec.AllowAutoCreate {
r.recorder.Event(r.instance, "Warning", opensearchAPIUpdated, "OpenSearch Component Index template does not support allow_auto_create")
}
r.cluster, err = util.FetchOpensearchCluster(r.client, r.ctx, types.NamespacedName{
Name: r.instance.Spec.OpensearchRef.Name,
Namespace: r.instance.Namespace,
})
if err != nil {
reason = "error fetching opensearch cluster"
r.logger.Error(err, "failed to fetch opensearch cluster")
r.recorder.Event(r.instance, "Warning", opensearchError, reason)
return
}
if r.cluster == nil {
r.logger.Info("opensearch cluster does not exist, requeueing")
reason = "waiting for opensearch cluster to exist"
r.recorder.Event(r.instance, "Normal", opensearchPending, reason)
result = ctrl.Result{
Requeue: true,
RequeueAfter: 10 * time.Second,
}
return
}
// Check cluster ref has not changed
if r.instance.Status.ManagedCluster != nil {
if *r.instance.Status.ManagedCluster != r.cluster.UID {
reason = "cannot change the cluster a component template refers to"
err = fmt.Errorf("%s", reason)
r.recorder.Event(r.instance, "Warning", opensearchRefMismatch, reason)
return
}
} else {
if pointer.BoolDeref(r.updateStatus, true) {
err = r.client.UdateObjectStatus(r.instance, func(object client.Object) {
instance := object.(*opsterv1.OpensearchComponentTemplate)
instance.Status.ManagedCluster = &r.cluster.UID
})
if err != nil {
reason = fmt.Sprintf("failed to update status: %s", err)
r.recorder.Event(r.instance, "Warning", statusError, reason)
return
}
}
}
// Check cluster is ready
if r.cluster.Status.Phase != opsterv1.PhaseRunning {
r.logger.Info("opensearch cluster is not running, requeueing")
reason = "waiting for opensearch cluster status to be running"
r.recorder.Event(r.instance, "Normal", opensearchPending, reason)
result = ctrl.Result{
Requeue: true,
RequeueAfter: 10 * time.Second,
}
return
}
r.osClient, err = util.CreateClientForCluster(r.client, r.ctx, r.cluster, r.osClientTransport)
if err != nil {
reason = "error creating opensearch client"
r.recorder.Event(r.instance, "Warning", opensearchError, reason)
return
}
templateName := r.instance.Name
if r.instance.Spec.Name != "" {
templateName = r.instance.Spec.Name
}
// Check component template state to make sure we don't touch preexisting component templates
if r.instance.Status.ExistingComponentTemplate == nil {
var exists bool
exists, err = services.ComponentTemplateExists(r.ctx, r.osClient, templateName)
if err != nil {
reason = "failed to get component template status from OpenSearch API"
r.logger.Error(err, reason)
r.recorder.Event(r.instance, "Warning", opensearchAPIError, reason)
return
}
if pointer.BoolDeref(r.updateStatus, true) {
err = r.client.UdateObjectStatus(r.instance, func(object client.Object) {
instance := object.(*opsterv1.OpensearchComponentTemplate)
instance.Status.ExistingComponentTemplate = &exists
})
if err != nil {
reason = fmt.Sprintf("failed to update status: %s", err)
r.recorder.Event(r.instance, "Warning", statusError, reason)
return
}
} else {
// Emit an event for unit testing assertion
r.recorder.Event(r.instance, "Normal", "UnitTest", fmt.Sprintf("exists is %t", exists))
return
}
}
// If component template is existing do nothing
if *r.instance.Status.ExistingComponentTemplate {
reason = opensearchComponentTemplateExists
return
}
// the template name is immutable, so check the old name (r.instance.Status.ComponentTemplateName) against the new
if r.instance.Status.ComponentTemplateName != "" && templateName != r.instance.Status.ComponentTemplateName {
reason = "cannot change the component template name"
err = fmt.Errorf("%s", reason)
r.recorder.Event(r.instance, "Warning", opensearchComponentTemplateNameMismatch, reason)
return
}
// rewrite the CRD format to the gateway format
resource := helpers.TranslateComponentTemplateToRequest(r.instance.Spec)
shouldUpdate, err := services.ShouldUpdateComponentTemplate(r.ctx, r.osClient, templateName, resource)
if err != nil {
reason = "failed to get component template status from OpenSearch API"
r.logger.Error(err, reason)
r.recorder.Event(r.instance, "Warning", opensearchAPIError, reason)
return
}
if !shouldUpdate {
r.logger.V(1).Info(fmt.Sprintf("component template %s is in sync", r.instance.Name))
result = ctrl.Result{Requeue: true, RequeueAfter: 30 * time.Second}
return
}
err = services.CreateOrUpdateComponentTemplate(r.ctx, r.osClient, templateName, resource)
if err != nil {
reason = "failed to update component template with OpenSearch API"
r.logger.Error(err, reason)
r.recorder.Event(r.instance, "Warning", opensearchAPIError, reason)
}
r.recorder.Event(r.instance, "Normal", opensearchAPIUpdated, "component template updated in opensearch")
result = ctrl.Result{Requeue: true, RequeueAfter: 30 * time.Second}
return
}
func (r *ComponentTemplateReconciler) Delete() error {
// If we have never successfully reconciled we can just exit
if r.instance.Status.ExistingComponentTemplate == nil {
return nil
}
if *r.instance.Status.ExistingComponentTemplate {
r.logger.Info("component template was pre-existing; not deleting")
return nil
}
var err error
r.cluster, err = util.FetchOpensearchCluster(r.client, r.ctx, types.NamespacedName{
Name: r.instance.Spec.OpensearchRef.Name,
Namespace: r.instance.Namespace,
})
if err != nil {
return err
}
if r.cluster == nil || !r.cluster.DeletionTimestamp.IsZero() {
// If the opensearch cluster doesn't exist, we don't need to delete anything
return nil
}
r.osClient, err = util.CreateClientForCluster(r.client, r.ctx, r.cluster, r.osClientTransport)
if err != nil {
return err
}
templateName := r.instance.Name
if r.instance.Spec.Name != "" {
templateName = r.instance.Spec.Name
}
exist, err := services.ComponentTemplateExists(r.ctx, r.osClient, templateName)
if err != nil {
return err
}
if !exist {
r.logger.V(1).Info("component template already deleted from opensearch")
return nil
}
return services.DeleteComponentTemplate(r.ctx, r.osClient, templateName)
}