-
Notifications
You must be signed in to change notification settings - Fork 108
/
monitoring.go
471 lines (433 loc) · 17.1 KB
/
monitoring.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
package dscinitialization
import (
"context"
b64 "encoding/base64"
"fmt"
"path/filepath"
"strings"
operatorv1 "github.com/openshift/api/operator/v1"
routev1 "github.com/openshift/api/route/v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
dsci "github.com/opendatahub-io/opendatahub-operator/v2/apis/dscinitialization/v1"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/cluster"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/common"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/deploy"
)
// +kubebuilder:rbac:groups="route.openshift.io",resources=routers/metrics,verbs=get
// +kubebuilder:rbac:groups="route.openshift.io",resources=routers/federate,verbs=get
// +kubebuilder:rbac:groups="image.openshift.io",resources=registry/metrics,verbs=get
var (
ComponentName = "monitoring"
alertManagerPath = filepath.Join(deploy.DefaultManifestPath, ComponentName, "alertmanager")
prometheusManifestsPath = filepath.Join(deploy.DefaultManifestPath, ComponentName, "prometheus", "base")
prometheusConfigPath = filepath.Join(deploy.DefaultManifestPath, ComponentName, "prometheus", "apps")
networkpolicyPath = filepath.Join(deploy.DefaultManifestPath, ComponentName, "networkpolicy")
NameConsoleLink = "console"
NamespaceConsoleLink = "openshift-console"
)
// only when reconcile on DSCI CR, initial set to true
// if reconcile from monitoring, initial set to false, skip blackbox and rolebinding.
func (r *DSCInitializationReconciler) configureManagedMonitoring(ctx context.Context, dscInit *dsci.DSCInitialization, initial string) error {
if initial == "init" {
// configure Blackbox exporter
if err := configureBlackboxExporter(ctx, dscInit, r); err != nil {
return fmt.Errorf("error in configureBlackboxExporter: %w", err)
}
}
if initial == "revertbackup" {
// TODO: implement with a better solution
// to have - before component name is to filter out the real rules file line
// e.g line of "workbenches-recording.rules: |"
err := common.MatchLineInFile(filepath.Join(prometheusConfigPath, "prometheus-configs.yaml"),
map[string]string{
"(.*)-(.*)workbenches(.*).rules": "",
"(.*)-(.*)rhods-dashboard(.*).rules": "",
"(.*)-(.*)codeflare(.*).rules": "",
"(.*)-(.*)data-science-pipelines-operator(.*).rules": "",
"(.*)-(.*)model-mesh(.*).rules": "",
"(.*)-(.*)odh-model-controller(.*).rules": "",
"(.*)-(.*)ray(.*).rules": "",
"(.*)-(.*)trustyai(.*).rules": "",
})
if err != nil {
r.Log.Error(err, "error to remove previous enabled component rules")
return err
}
}
// configure Alertmanager
if err := configureAlertManager(ctx, dscInit, r); err != nil {
return fmt.Errorf("error in configureAlertManager: %w", err)
}
// configure Prometheus
if err := configurePrometheus(ctx, dscInit, r); err != nil {
return fmt.Errorf("error in configurePrometheus: %w", err)
}
if initial == "init" {
err := cluster.UpdatePodSecurityRolebinding(ctx, r.Client, dscInit.Spec.Monitoring.Namespace, "redhat-ods-monitoring")
if err != nil {
return fmt.Errorf("error to update monitoring security rolebinding: %w", err)
}
}
r.Log.Info("Success: finish config managed monitoring stack!")
return nil
}
func configureAlertManager(ctx context.Context, dsciInit *dsci.DSCInitialization, r *DSCInitializationReconciler) error {
// Get Deadmansnitch secret
deadmansnitchSecret, err := r.waitForManagedSecret(ctx, "redhat-rhods-deadmanssnitch", dsciInit.Spec.Monitoring.Namespace)
if err != nil {
r.Log.Error(err, "error getting deadmansnitch secret from namespace "+dsciInit.Spec.Monitoring.Namespace)
return err
}
// r.Log.Info("Success: got deadmansnitch secret")
// Get PagerDuty Secret
pagerDutySecret, err := r.waitForManagedSecret(ctx, "redhat-rhods-pagerduty", dsciInit.Spec.Monitoring.Namespace)
if err != nil {
r.Log.Error(err, "error getting pagerduty secret from namespace "+dsciInit.Spec.Monitoring.Namespace)
return err
}
// r.Log.Info("Success: got pagerduty secret")
// Get Smtp Secret
smtpSecret, err := r.waitForManagedSecret(ctx, "redhat-rhods-smtp", dsciInit.Spec.Monitoring.Namespace)
if err != nil {
r.Log.Error(err, "error getting smtp secret from namespace "+dsciInit.Spec.Monitoring.Namespace)
return err
}
// r.Log.Info("Success: got smtp secret")
// Replace variables in alertmanager configmap for the initial time
// TODO: Following variables can later be exposed by the API
err = common.ReplaceStringsInFile(filepath.Join(alertManagerPath, "alertmanager-configs.yaml"),
map[string]string{
"<snitch_url>": string(deadmansnitchSecret.Data["SNITCH_URL"]),
"<pagerduty_token>": string(pagerDutySecret.Data["PAGERDUTY_KEY"]),
"<smtp_host>": string(smtpSecret.Data["host"]),
"<smtp_port>": string(smtpSecret.Data["port"]),
"<smtp_username>": string(smtpSecret.Data["username"]),
"<smtp_password>": string(smtpSecret.Data["password"]),
})
if err != nil {
r.Log.Error(err, "error to inject data to alertmanager-configs.yaml")
return err
}
// r.Log.Info("Success: inject alertmanage-configs.yaml")
// special handling for dev-mod
consolelinkDomain, err := cluster.GetDomain(r.Client)
if err != nil {
return fmt.Errorf("error getting console route URL : %w", err)
}
if strings.Contains(consolelinkDomain, "devshift.org") {
r.Log.Info("inject alertmanage-configs.yaml for dev mode1")
err = common.ReplaceStringsInFile(filepath.Join(alertManagerPath, "alertmanager-configs.yaml"),
map[string]string{
"@devshift.net": "@rhmw.io",
})
if err != nil {
r.Log.Error(err, "error to replace data for dev mode1 to alertmanager-configs.yaml")
return err
}
}
if strings.Contains(consolelinkDomain, "aisrhods") {
r.Log.Info("inject alertmanage-configs.yaml for dev mode2")
err = common.ReplaceStringsInFile(filepath.Join(alertManagerPath, "alertmanager-configs.yaml"),
map[string]string{
"receiver: PagerDuty": "receiver: alerts-sink",
})
if err != nil {
r.Log.Error(err, "error to replace data for dev mode2 to alertmanager-configs.yaml")
return err
}
}
// r.Log.Info("Success: inject alertmanage-configs.yaml for dev mode")
operatorNs, err := cluster.GetOperatorNamespace()
if err != nil {
r.Log.Error(err, "error getting operator namespace for smtp secret")
return err
}
// Get SMTP receiver email secret (assume operator namespace for managed service is not configurable)
smtpEmailSecret, err := r.waitForManagedSecret(ctx, "addon-managed-odh-parameters", operatorNs)
if err != nil {
return fmt.Errorf("error getting smtp receiver email secret: %w", err)
}
// r.Log.Info("Success: got smpt email secret")
// replace smtpEmailSecret in alertmanager-configs.yaml
if err = common.MatchLineInFile(filepath.Join(alertManagerPath, "alertmanager-configs.yaml"),
map[string]string{
"- to: ": "- to: " + string(smtpEmailSecret.Data["notification-email"]),
},
); err != nil {
r.Log.Error(err, "error to update with new notification-email")
return err
}
// r.Log.Info("Success: update alertmanage-configs.yaml with email")
err = deploy.DeployManifestsFromPath(r.Client, dsciInit, alertManagerPath, dsciInit.Spec.Monitoring.Namespace, "alertmanager", true)
if err != nil {
r.Log.Error(err, "error to deploy manifests", "path", alertManagerPath)
return err
}
// r.Log.Info("Success: update alertmanager with manifests")
// Create alertmanager-proxy secret
if err := createMonitoringProxySecret(ctx, r.Client, "alertmanager-proxy", dsciInit); err != nil {
r.Log.Error(err, "error to create secret alertmanager-proxy")
return err
}
// r.Log.Info("Success: create alertmanager-proxy secret")
return nil
}
func configurePrometheus(ctx context.Context, dsciInit *dsci.DSCInitialization, r *DSCInitializationReconciler) error {
// Update rolebinding-viewer
err := common.ReplaceStringsInFile(filepath.Join(prometheusManifestsPath, "prometheus-rolebinding-viewer.yaml"),
map[string]string{
"<odh_monitoring_project>": dsciInit.Spec.Monitoring.Namespace,
})
if err != nil {
r.Log.Error(err, "error to inject data to prometheus-rolebinding-viewer.yaml")
return err
}
// Update prometheus-config for dashboard, dsp and workbench
consolelinkDomain, err := cluster.GetDomain(r.Client)
if err != nil {
return fmt.Errorf("error getting console route URL : %w", err)
}
err = common.ReplaceStringsInFile(filepath.Join(prometheusConfigPath, "prometheus-configs.yaml"),
map[string]string{
"<odh_application_namespace>": dsciInit.Spec.ApplicationsNamespace,
"<odh_monitoring_project>": dsciInit.Spec.Monitoring.Namespace,
"<console_domain>": consolelinkDomain,
})
if err != nil {
r.Log.Error(err, "error to inject data to prometheus-configs.yaml")
return err
}
// Deploy prometheus manifests from prometheus/apps
if err = deploy.DeployManifestsFromPath(
r.Client,
dsciInit,
prometheusConfigPath,
dsciInit.Spec.Monitoring.Namespace,
"prometheus",
dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil {
r.Log.Error(err, "error to deploy manifests for prometheus configs", "path", prometheusConfigPath)
return err
}
// r.Log.Info("Success: create prometheus configmap 'prometheus'")
// Get prometheus configmap
prometheusConfigMap := &corev1.ConfigMap{}
err = r.Client.Get(ctx, client.ObjectKey{
Namespace: dsciInit.Spec.Monitoring.Namespace,
Name: "prometheus",
}, prometheusConfigMap)
if err != nil {
r.Log.Error(err, "error to get configmap 'prometheus'")
return err
}
// r.Log.Info("Success: got prometheus configmap")
// Get encoded prometheus data from configmap 'prometheus'
prometheusData, err := common.GetMonitoringData(fmt.Sprint(prometheusConfigMap.Data))
if err != nil {
r.Log.Error(err, "error to get prometheus data")
return err
}
// r.Log.Info("Success: read encoded prometheus data from prometheus.yml in configmap")
// Get alertmanager host
alertmanagerRoute := &routev1.Route{}
err = r.Client.Get(ctx, client.ObjectKey{
Namespace: dsciInit.Spec.Monitoring.Namespace,
Name: "alertmanager",
}, alertmanagerRoute)
if err != nil {
r.Log.Error(err, "error to get alertmanager route")
return err
}
// r.Log.Info("Success: got alertmanager route")
// Get alertmanager configmap
alertManagerConfigMap := &corev1.ConfigMap{}
err = r.Client.Get(ctx, client.ObjectKey{
Namespace: dsciInit.Spec.Monitoring.Namespace,
Name: "alertmanager",
}, alertManagerConfigMap)
if err != nil {
r.Log.Error(err, "error to get configmap 'alertmanager'")
return err
}
// r.Log.Info("Success: got configmap 'alertmanager'")
alertmanagerData, err := common.GetMonitoringData(alertManagerConfigMap.Data["alertmanager.yml"])
if err != nil {
r.Log.Error(err, "error to get encoded alertmanager data from alertmanager.yml")
return err
}
// r.Log.Info("Success: read alertmanager data from alertmanage.yml")
// Update prometheus deployment with alertmanager and prometheus data
err = common.ReplaceStringsInFile(filepath.Join(prometheusManifestsPath, "prometheus-deployment.yaml"),
map[string]string{
"<set_alertmanager_host>": alertmanagerRoute.Spec.Host,
})
if err != nil {
r.Log.Error(err, "error to inject set_alertmanager_host to prometheus-deployment.yaml")
return err
}
// r.Log.Info("Success: update set_alertmanager_host in prometheus-deployment.yaml")
err = common.MatchLineInFile(filepath.Join(prometheusManifestsPath, "prometheus-deployment.yaml"),
map[string]string{
"alertmanager: ": "alertmanager: " + alertmanagerData,
"prometheus: ": "prometheus: " + prometheusData,
})
if err != nil {
r.Log.Error(err, "error to update annotations in prometheus-deployment.yaml")
return err
}
// r.Log.Info("Success: update annotations in prometheus-deployment.yaml")
// final apply prometheus manifests including prometheus deployment
// Check if Prometheus deployment from legacy version exists(check for initContainer)
// Need to delete wait-for-deployment initContainer
existingPromDep := &appsv1.Deployment{}
err = r.Client.Get(ctx, client.ObjectKey{
Namespace: dsciInit.Spec.Monitoring.Namespace,
Name: "prometheus",
}, existingPromDep)
if err != nil {
if !apierrs.IsNotFound(err) {
return err
}
}
if len(existingPromDep.Spec.Template.Spec.InitContainers) > 0 {
err = r.Client.Delete(ctx, existingPromDep)
if err != nil {
return fmt.Errorf("error deleting legacy prometheus deployment %w", err)
}
}
err = deploy.DeployManifestsFromPath(r.Client, dsciInit, prometheusManifestsPath,
dsciInit.Spec.Monitoring.Namespace, "prometheus", true)
if err != nil {
r.Log.Error(err, "error to deploy manifests for prometheus", "path", prometheusManifestsPath)
return err
}
// Create prometheus-proxy secret
if err := createMonitoringProxySecret(ctx, r.Client, "prometheus-proxy", dsciInit); err != nil {
return err
}
// r.Log.Info("Success: create prometheus-proxy secret")
return nil
}
func configureBlackboxExporter(ctx context.Context, dsciInit *dsci.DSCInitialization, r *DSCInitializationReconciler) error {
consoleRoute := &routev1.Route{}
err := r.Client.Get(ctx, client.ObjectKey{Name: "console", Namespace: "openshift-console"}, consoleRoute)
if err != nil {
if !apierrs.IsNotFound(err) {
return err
}
}
// Check if Blackbox exporter deployment from legacy version exists(check for initContainer)
// Need to delete wait-for-deployment initContainer
existingBlackboxExp := &appsv1.Deployment{}
err = r.Client.Get(ctx, client.ObjectKey{
Namespace: dsciInit.Spec.Monitoring.Namespace,
Name: "blackbox-exporter",
}, existingBlackboxExp)
if err != nil {
if !apierrs.IsNotFound(err) {
return err
}
}
if len(existingBlackboxExp.Spec.Template.Spec.InitContainers) > 0 {
err = r.Client.Delete(ctx, existingBlackboxExp)
if err != nil {
return fmt.Errorf("error deleting legacy blackbox deployment %w", err)
}
}
blackBoxPath := filepath.Join(deploy.DefaultManifestPath, "monitoring", "blackbox-exporter")
if apierrs.IsNotFound(err) || strings.Contains(consoleRoute.Spec.Host, "redhat.com") {
if err := deploy.DeployManifestsFromPath(r.Client,
dsciInit,
filepath.Join(blackBoxPath, "internal"),
dsciInit.Spec.Monitoring.Namespace,
"blackbox-exporter",
dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil {
r.Log.Error(err, "error to deploy manifests: %w", "error", err)
return err
}
} else {
if err := deploy.DeployManifestsFromPath(r.Client,
dsciInit,
filepath.Join(blackBoxPath, "external"),
dsciInit.Spec.Monitoring.Namespace,
"blackbox-exporter",
dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil {
r.Log.Error(err, "error to deploy manifests: %w", "error", err)
return err
}
}
return nil
}
func createMonitoringProxySecret(ctx context.Context, cli client.Client, name string, dsciInit *dsci.DSCInitialization) error {
sessionSecret, err := GenerateRandomHex(32)
if err != nil {
return err
}
desiredProxySecret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: dsciInit.Spec.Monitoring.Namespace,
},
Data: map[string][]byte{
"session_secret": []byte(b64.StdEncoding.EncodeToString(sessionSecret)),
},
}
foundProxySecret := &corev1.Secret{}
err = cli.Get(ctx, client.ObjectKey{Name: name, Namespace: dsciInit.Spec.Monitoring.Namespace}, foundProxySecret)
if err != nil {
if apierrs.IsNotFound(err) {
// Set Controller reference
err = ctrl.SetControllerReference(dsciInit, desiredProxySecret, cli.Scheme())
if err != nil {
return err
}
err = cli.Create(ctx, desiredProxySecret)
if err != nil && !apierrs.IsAlreadyExists(err) {
return err
}
} else {
return err
}
}
return nil
}
func (r *DSCInitializationReconciler) configureCommonMonitoring(dsciInit *dsci.DSCInitialization) error {
// configure segment.io
segmentPath := filepath.Join(deploy.DefaultManifestPath, "monitoring", "segment")
if err := deploy.DeployManifestsFromPath(
r.Client,
dsciInit,
segmentPath,
dsciInit.Spec.ApplicationsNamespace,
"segment-io",
dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil {
r.Log.Error(err, "error to deploy manifests under "+segmentPath)
return err
}
// configure monitoring base
monitoringBasePath := filepath.Join(deploy.DefaultManifestPath, "monitoring", "base")
err := common.ReplaceStringsInFile(filepath.Join(monitoringBasePath, "rhods-servicemonitor.yaml"),
map[string]string{
"<odh_monitoring_project>": dsciInit.Spec.Monitoring.Namespace,
})
if err != nil {
r.Log.Error(err, "error to inject namespace to common monitoring")
return err
}
// do not set monitoring namespace here, it is hardcoded by manifests
if err := deploy.DeployManifestsFromPath(
r.Client,
dsciInit,
monitoringBasePath,
"",
"monitoring-base",
dsciInit.Spec.Monitoring.ManagementState == operatorv1.Managed); err != nil {
r.Log.Error(err, "error to deploy manifests under "+monitoringBasePath)
return err
}
return nil
}