forked from grafana/loki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lokistack_create_or_update.go
447 lines (390 loc) · 13.4 KB
/
lokistack_create_or_update.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
package handlers
import (
"context"
"fmt"
"os"
"time"
"github.com/ViaQ/logerr/v2/kverrors"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrlutil "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
configv1 "github.com/grafana/loki/operator/apis/config/v1"
lokiv1 "github.com/grafana/loki/operator/apis/loki/v1"
"github.com/grafana/loki/operator/internal/external/k8s"
"github.com/grafana/loki/operator/internal/handlers/internal/gateway"
"github.com/grafana/loki/operator/internal/handlers/internal/openshift"
"github.com/grafana/loki/operator/internal/handlers/internal/rules"
"github.com/grafana/loki/operator/internal/handlers/internal/serviceaccounts"
"github.com/grafana/loki/operator/internal/handlers/internal/storage"
"github.com/grafana/loki/operator/internal/handlers/internal/tlsprofile"
"github.com/grafana/loki/operator/internal/manifests"
manifests_openshift "github.com/grafana/loki/operator/internal/manifests/openshift"
storageoptions "github.com/grafana/loki/operator/internal/manifests/storage"
"github.com/grafana/loki/operator/internal/metrics"
"github.com/grafana/loki/operator/internal/status"
)
const (
defaultCAKey = "service-ca.crt"
)
// CreateOrUpdateLokiStack handles LokiStack create and update events.
func CreateOrUpdateLokiStack(
ctx context.Context,
log logr.Logger,
req ctrl.Request,
k k8s.Client,
s *runtime.Scheme,
fg configv1.FeatureGates,
) error {
ll := log.WithValues("lokistack", req.NamespacedName, "event", "createOrUpdate")
var stack lokiv1.LokiStack
if err := k.Get(ctx, req.NamespacedName, &stack); err != nil {
if apierrors.IsNotFound(err) {
// maybe the user deleted it before we could react? Either way this isn't an issue
ll.Error(err, "could not find the requested loki stack", "name", req.NamespacedName)
return nil
}
return kverrors.Wrap(err, "failed to lookup lokistack", "name", req.NamespacedName)
}
img := os.Getenv(manifests.EnvRelatedImageLoki)
if img == "" {
img = manifests.DefaultContainerImage
}
gwImg := os.Getenv(manifests.EnvRelatedImageGateway)
if gwImg == "" {
gwImg = manifests.DefaultLokiStackGatewayImage
}
var storageSecret corev1.Secret
key := client.ObjectKey{Name: stack.Spec.Storage.Secret.Name, Namespace: stack.Namespace}
if err := k.Get(ctx, key, &storageSecret); err != nil {
if apierrors.IsNotFound(err) {
return &status.DegradedError{
Message: "Missing object storage secret",
Reason: lokiv1.ReasonMissingObjectStorageSecret,
Requeue: false,
}
}
return kverrors.Wrap(err, "failed to lookup lokistack storage secret", "name", key)
}
objStore, err := storage.ExtractSecret(&storageSecret, stack.Spec.Storage.Secret.Type)
if err != nil {
return &status.DegradedError{
Message: fmt.Sprintf("Invalid object storage secret contents: %s", err),
Reason: lokiv1.ReasonInvalidObjectStorageSecret,
Requeue: false,
}
}
objStore.OpenShiftEnabled = fg.OpenShift.Enabled
storageSchemas, err := storageoptions.BuildSchemaConfig(
time.Now().UTC(),
stack.Spec.Storage,
stack.Status.Storage,
)
if err != nil {
return &status.DegradedError{
Message: fmt.Sprintf("Invalid object storage schema contents: %s", err),
Reason: lokiv1.ReasonInvalidObjectStorageSchema,
Requeue: false,
}
}
objStore.Schemas = storageSchemas
if stack.Spec.Storage.TLS != nil {
tlsConfig := stack.Spec.Storage.TLS
if tlsConfig.CA == "" {
return &status.DegradedError{
Message: "Missing object storage CA config map",
Reason: lokiv1.ReasonMissingObjectStorageCAConfigMap,
Requeue: false,
}
}
var cm corev1.ConfigMap
key := client.ObjectKey{Name: tlsConfig.CA, Namespace: stack.Namespace}
if err = k.Get(ctx, key, &cm); err != nil {
if apierrors.IsNotFound(err) {
return &status.DegradedError{
Message: "Missing object storage CA config map",
Reason: lokiv1.ReasonMissingObjectStorageCAConfigMap,
Requeue: false,
}
}
return kverrors.Wrap(err, "failed to lookup lokistack object storage CA config map", "name", key)
}
caKey := defaultCAKey
if tlsConfig.CAKey != "" {
caKey = tlsConfig.CAKey
}
var caHash string
caHash, err = storage.CheckCAConfigMap(&cm, caKey)
if err != nil {
return &status.DegradedError{
Message: fmt.Sprintf("Invalid object storage CA configmap contents: %s", err),
Reason: lokiv1.ReasonInvalidObjectStorageCAConfigMap,
Requeue: false,
}
}
objStore.SecretSHA1 = fmt.Sprintf("%s;%s", objStore.SecretSHA1, caHash)
objStore.TLS = &storageoptions.TLSConfig{CA: cm.Name, Key: caKey}
}
var (
baseDomain string
tenantSecrets []*manifests.TenantSecrets
tenantConfigs map[string]manifests.TenantConfig
)
if fg.LokiStackGateway && stack.Spec.Tenants == nil {
return &status.DegradedError{
Message: "Invalid tenants configuration - TenantsSpec cannot be nil when gateway flag is enabled",
Reason: lokiv1.ReasonInvalidTenantsConfiguration,
Requeue: false,
}
} else if fg.LokiStackGateway && stack.Spec.Tenants != nil {
if err = gateway.ValidateModes(stack); err != nil {
return &status.DegradedError{
Message: fmt.Sprintf("Invalid tenants configuration: %s", err),
Reason: lokiv1.ReasonInvalidTenantsConfiguration,
Requeue: false,
}
}
switch stack.Spec.Tenants.Mode {
case lokiv1.OpenshiftLogging, lokiv1.OpenshiftNetwork:
baseDomain, err = gateway.GetOpenShiftBaseDomain(ctx, k, req)
if err != nil {
return err
}
if stack.Spec.Proxy == nil {
// If the LokiStack has no proxy set but there is a cluster-wide proxy setting,
// set the LokiStack proxy to that.
ocpProxy, proxyErr := openshift.GetProxy(ctx, k)
if proxyErr != nil {
return proxyErr
}
stack.Spec.Proxy = ocpProxy
}
default:
tenantSecrets, err = gateway.GetTenantSecrets(ctx, k, req, &stack)
if err != nil {
return err
}
}
// extract the existing tenant's id, cookieSecret if exists, otherwise create new.
tenantConfigs, err = gateway.GetTenantConfigSecretData(ctx, k, req)
if err != nil {
ll.Error(err, "error in getting tenant secret data")
}
}
var (
alertingRules []lokiv1.AlertingRule
recordingRules []lokiv1.RecordingRule
rulerConfig *lokiv1.RulerConfigSpec
rulerSecret *manifests.RulerSecret
ocpAmEnabled bool
ocpUWAmEnabled bool
)
if stack.Spec.Rules != nil && stack.Spec.Rules.Enabled {
alertingRules, recordingRules, err = rules.List(ctx, k, req.Namespace, stack.Spec.Rules)
if err != nil {
ll.Error(err, "failed to lookup rules", "spec", stack.Spec.Rules)
}
rulerConfig, err = rules.GetRulerConfig(ctx, k, req)
if err != nil {
ll.Error(err, "failed to lookup ruler config", "key", req.NamespacedName)
}
if rulerConfig != nil && rulerConfig.RemoteWriteSpec != nil && rulerConfig.RemoteWriteSpec.ClientSpec != nil {
var rs corev1.Secret
key := client.ObjectKey{Name: rulerConfig.RemoteWriteSpec.ClientSpec.AuthorizationSecretName, Namespace: stack.Namespace}
if err = k.Get(ctx, key, &rs); err != nil {
if apierrors.IsNotFound(err) {
return &status.DegradedError{
Message: "Missing ruler remote write authorization secret",
Reason: lokiv1.ReasonMissingRulerSecret,
Requeue: false,
}
}
return kverrors.Wrap(err, "failed to lookup lokistack ruler secret", "name", key)
}
rulerSecret, err = rules.ExtractRulerSecret(&rs, rulerConfig.RemoteWriteSpec.ClientSpec.AuthorizationType)
if err != nil {
return &status.DegradedError{
Message: "Invalid ruler remote write authorization secret contents",
Reason: lokiv1.ReasonInvalidRulerSecret,
Requeue: false,
}
}
}
ocpAmEnabled, err = openshift.AlertManagerSVCExists(ctx, stack.Spec, k)
if err != nil {
ll.Error(err, "failed to check OCP AlertManager")
return err
}
ocpUWAmEnabled, err = openshift.UserWorkloadAlertManagerSVCExists(ctx, stack.Spec, k)
if err != nil {
ll.Error(err, "failed to check OCP User Workload AlertManager")
return err
}
} else {
// Clean up ruler resources
err = rules.RemoveRulesConfigMap(ctx, req, k)
if err != nil {
ll.Error(err, "failed to remove rules ConfigMap")
return err
}
err = rules.RemoveRuler(ctx, req, k)
if err != nil {
ll.Error(err, "failed to remove ruler StatefulSet")
return err
}
}
certRotationRequiredAt := ""
if stack.Annotations != nil {
certRotationRequiredAt = stack.Annotations[manifests.AnnotationCertRotationRequiredAt]
}
timeoutConfig, err := manifests.NewTimeoutConfig(stack.Spec.Limits)
if err != nil {
ll.Error(err, "failed to parse query timeout")
return &status.DegradedError{
Message: fmt.Sprintf("Error parsing query timeout: %s", err),
Reason: lokiv1.ReasonQueryTimeoutInvalid,
Requeue: false,
}
}
// Here we will translate the lokiv1.LokiStack options into manifest options
opts := manifests.Options{
Name: req.Name,
Namespace: req.Namespace,
Image: img,
GatewayImage: gwImg,
GatewayBaseDomain: baseDomain,
Stack: stack.Spec,
Gates: fg,
ObjectStorage: *objStore,
CertRotationRequiredAt: certRotationRequiredAt,
AlertingRules: alertingRules,
RecordingRules: recordingRules,
Ruler: manifests.Ruler{
Spec: rulerConfig,
Secret: rulerSecret,
},
Timeouts: timeoutConfig,
Tenants: manifests.Tenants{
Secrets: tenantSecrets,
Configs: tenantConfigs,
},
OpenShiftOptions: manifests_openshift.Options{
BuildOpts: manifests_openshift.BuildOptions{
AlertManagerEnabled: ocpAmEnabled,
UserWorkloadAlertManagerEnabled: ocpUWAmEnabled,
},
},
}
ll.Info("begin building manifests")
if optErr := manifests.ApplyDefaultSettings(&opts); optErr != nil {
ll.Error(optErr, "failed to conform options to build settings")
return optErr
}
if fg.LokiStackGateway {
if optErr := manifests.ApplyGatewayDefaultOptions(&opts); optErr != nil {
ll.Error(optErr, "failed to apply defaults options to gateway settings")
return optErr
}
}
tlsProfileType := configv1.TLSProfileType(fg.TLSProfile)
// Overwrite the profile from the flags and use the profile from the apiserver instead
if fg.OpenShift.ClusterTLSPolicy {
tlsProfileType = configv1.TLSProfileType("")
}
tlsProfile, err := tlsprofile.GetTLSSecurityProfile(ctx, k, tlsProfileType)
if err != nil {
// The API server is not guaranteed to be there nor have a result.
ll.Error(err, "failed to get security profile. will use default tls profile.")
}
if optErr := manifests.ApplyTLSSettings(&opts, tlsProfile); optErr != nil {
ll.Error(optErr, "failed to conform options to tls profile settings")
return optErr
}
objects, err := manifests.BuildAll(opts)
if err != nil {
ll.Error(err, "failed to build manifests")
return err
}
ll.Info("manifests built", "count", len(objects))
// The status is updated before the objects are actually created to
// avoid the scenario in which the configmap is successfully created or
// updated and another resource is not. This would cause the status to
// be possibly misaligned with the configmap, which could lead to
// a user possibly being unable to read logs.
if err := status.SetStorageSchemaStatus(ctx, k, req, storageSchemas); err != nil {
ll.Error(err, "failed to set storage schema status")
return err
}
var errCount int32
for _, obj := range objects {
l := ll.WithValues(
"object_name", obj.GetName(),
"object_kind", obj.GetObjectKind(),
)
if isNamespacedResource(obj) {
obj.SetNamespace(req.Namespace)
if err := ctrl.SetControllerReference(&stack, obj, s); err != nil {
l.Error(err, "failed to set controller owner reference to resource")
errCount++
continue
}
}
depAnnotations, err := dependentAnnotations(ctx, k, obj)
if err != nil {
l.Error(err, "failed to set dependent annotations")
return err
}
desired := obj.DeepCopyObject().(client.Object)
mutateFn := manifests.MutateFuncFor(obj, desired, depAnnotations)
op, err := ctrl.CreateOrUpdate(ctx, k, obj, mutateFn)
if err != nil {
l.Error(err, "failed to configure resource")
errCount++
continue
}
msg := fmt.Sprintf("Resource has been %s", op)
switch op {
case ctrlutil.OperationResultNone:
l.V(1).Info(msg)
default:
l.Info(msg)
}
}
if errCount > 0 {
return kverrors.New("failed to configure lokistack resources", "name", req.NamespacedName)
}
// 1x.extra-small is used only for development, so the metrics will not
// be collected.
if opts.Stack.Size != lokiv1.SizeOneXExtraSmall && opts.Stack.Size != lokiv1.SizeOneXDemo {
metrics.Collect(&opts.Stack, opts.Name)
}
return nil
}
func dependentAnnotations(ctx context.Context, k k8s.Client, obj client.Object) (map[string]string, error) {
a := obj.GetAnnotations()
saName, ok := a[corev1.ServiceAccountNameKey]
if !ok || saName == "" {
return nil, nil
}
key := client.ObjectKey{Name: saName, Namespace: obj.GetNamespace()}
uid, err := serviceaccounts.GetUID(ctx, k, key)
if err != nil {
return nil, err
}
return map[string]string{
corev1.ServiceAccountUIDKey: uid,
}, nil
}
// isNamespacedResource determines if an object should be managed or not by a LokiStack
func isNamespacedResource(obj client.Object) bool {
switch obj.(type) {
case *rbacv1.ClusterRole, *rbacv1.ClusterRoleBinding:
return false
default:
return true
}
}