-
Notifications
You must be signed in to change notification settings - Fork 69
CNV-87535: k8s: add orphan AlertRelabelConfig GC #1174
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sradco
wants to merge
2
commits into
openshift:main-alerts-management-api
Choose a base branch
from
sradco:alert-mgmt-restructured-11-orphan-gc
base: main-alerts-management-api
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+870
−17
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| package k8s | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "github.com/openshift/monitoring-plugin/pkg/managementlabels" | ||
| ) | ||
|
|
||
| // gcOrphanedARCs deletes AlertRelabelConfigs whose associated alert rule no | ||
| // longer exists. This handles the case where an operator (or manual action) | ||
| // removes rules from a PrometheusRule or deletes the CR entirely — the | ||
| // AlertRelabelConfigs that were created by the plugin for | ||
| // classification/drop/stamp become orphans. | ||
| // | ||
| // Only AlertRelabelConfigs carrying the plugin's alertRuleId annotation | ||
| // are considered. GitOps-managed configs are never deleted automatically; | ||
| // scrapeable metrics surface them so cluster-monitoring-operator can alert. | ||
| // | ||
| // liveRuleIDs must include every alerting-rule ID still present on a | ||
| // PrometheusRule, including platform rules dropped by relabel configs. | ||
| // IDs are recorded in collectAlerts before the drop continue, so a Drop | ||
| // AlertRelabelConfig for a disabled rule is not treated as an orphan. | ||
| func (rrm *relabeledRulesManager) gcOrphanedARCs(ctx context.Context, liveRuleIDs map[string]struct{}) { | ||
| if rrm.alertRelabelConfigs == nil { | ||
| return | ||
| } | ||
|
|
||
| metrics := rrm.gcMetrics | ||
| arcs, err := rrm.alertRelabelConfigs.List(ctx, "") | ||
| if err != nil { | ||
| metrics.observeListError() | ||
| log.Errorf("orphan AlertRelabelConfig cleanup: failed to list AlertRelabelConfigs: %v", err) | ||
| return | ||
| } | ||
|
|
||
| gitOpsOrphans := 0 | ||
| for i := range arcs { | ||
| arc := &arcs[i] | ||
|
|
||
| ruleID, ok := arc.Annotations[managementlabels.ARCAnnotationAlertRuleIDKey] | ||
| if !ok || ruleID == "" { | ||
| continue | ||
| } | ||
|
|
||
| if _, alive := liveRuleIDs[ruleID]; alive { | ||
| continue | ||
| } | ||
|
|
||
| if IsManagedByGitOps(arc.Annotations, arc.Labels) { | ||
| gitOpsOrphans++ | ||
| log.Warnf("orphan AlertRelabelConfig cleanup: AlertRelabelConfig %s/%s (ruleId=%s) is orphaned but GitOps-managed — skipping deletion, manual cleanup required", arc.Namespace, arc.Name, ruleID) | ||
| continue | ||
| } | ||
|
|
||
| if err := rrm.alertRelabelConfigs.Delete(ctx, arc.Namespace, arc.Name); err != nil { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same question here about the ability to know that something failed.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed |
||
| metrics.observeDeleteError() | ||
| log.Errorf("orphan AlertRelabelConfig cleanup: failed to delete AlertRelabelConfig %s/%s: %v", arc.Namespace, arc.Name, err) | ||
| continue | ||
| } | ||
|
|
||
| log.Infof("orphan AlertRelabelConfig cleanup: deleted orphaned AlertRelabelConfig %s/%s (ruleId=%s)", arc.Namespace, arc.Name, ruleID) | ||
| } | ||
| metrics.setGitOpsOrphans(float64(gitOpsOrphans)) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| package k8s | ||
|
|
||
| import ( | ||
| "net/http" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/prometheus/client_golang/prometheus/promhttp" | ||
| ) | ||
|
|
||
| const ( | ||
| MetricAlertRelabelConfigGCListErrorsTotal = "monitoring_plugin_alert_relabel_config_gc_list_errors_total" | ||
| MetricAlertRelabelConfigGCDeleteErrorsTotal = "monitoring_plugin_alert_relabel_config_gc_delete_errors_total" | ||
| MetricAlertRelabelConfigGitOpsOrphans = "monitoring_plugin_alert_relabel_config_gitops_orphans" | ||
| ) | ||
|
|
||
| type alertRelabelConfigGCMetrics struct { | ||
| listErrors prometheus.Counter | ||
| deleteErrors prometheus.Counter | ||
| gitopsOrphans prometheus.Gauge | ||
| } | ||
|
|
||
| func newAlertRelabelConfigGCMetrics() *alertRelabelConfigGCMetrics { | ||
| return &alertRelabelConfigGCMetrics{ | ||
| listErrors: prometheus.NewCounter(prometheus.CounterOpts{ | ||
| Name: MetricAlertRelabelConfigGCListErrorsTotal, | ||
| Help: "Count of failed List calls while cleaning up orphaned AlertRelabelConfigs.", | ||
| }), | ||
| deleteErrors: prometheus.NewCounter(prometheus.CounterOpts{ | ||
| Name: MetricAlertRelabelConfigGCDeleteErrorsTotal, | ||
| Help: "Count of failed Delete calls while cleaning up orphaned AlertRelabelConfigs.", | ||
| }), | ||
| gitopsOrphans: prometheus.NewGauge(prometheus.GaugeOpts{ | ||
| Name: MetricAlertRelabelConfigGitOpsOrphans, | ||
| Help: "Number of GitOps-managed AlertRelabelConfigs that are orphaned and were not deleted.", | ||
| }), | ||
| } | ||
| } | ||
|
|
||
| func (m *alertRelabelConfigGCMetrics) mustRegister(reg prometheus.Registerer) { | ||
| reg.MustRegister(m.listErrors, m.deleteErrors, m.gitopsOrphans) | ||
| } | ||
|
|
||
| func (m *alertRelabelConfigGCMetrics) observeListError() { | ||
| if m == nil { | ||
| return | ||
| } | ||
| m.listErrors.Inc() | ||
| } | ||
|
|
||
| func (m *alertRelabelConfigGCMetrics) observeDeleteError() { | ||
| if m == nil { | ||
| return | ||
| } | ||
| m.deleteErrors.Inc() | ||
| } | ||
|
|
||
| func (m *alertRelabelConfigGCMetrics) setGitOpsOrphans(n float64) { | ||
| if m == nil { | ||
| return | ||
| } | ||
| m.gitopsOrphans.Set(n) | ||
| } | ||
|
|
||
| var ( | ||
| alertRelabelConfigGCMetricsRegistry = prometheus.NewRegistry() | ||
| defaultAlertRelabelConfigGCMetrics = newAlertRelabelConfigGCMetrics() | ||
| ) | ||
|
|
||
| func init() { | ||
| defaultAlertRelabelConfigGCMetrics.mustRegister(alertRelabelConfigGCMetricsRegistry) | ||
| } | ||
|
|
||
| // AlertRelabelConfigGCMetricsRegistry is the registry served at /metrics | ||
| // when alert-management-api is enabled. Additional collectors should | ||
| // register here so a single scrape endpoint exposes all series. | ||
| func AlertRelabelConfigGCMetricsRegistry() *prometheus.Registry { | ||
| return alertRelabelConfigGCMetricsRegistry | ||
| } | ||
|
|
||
| // AlertRelabelConfigGCMetricsHandler serves the GC metrics registry. | ||
| func AlertRelabelConfigGCMetricsHandler() http.Handler { | ||
| return promhttp.HandlerFor(alertRelabelConfigGCMetricsRegistry, promhttp.HandlerOpts{}) | ||
| } | ||
|
|
||
| // EmptyMetricsHandler serves an empty Prometheus registry so /metrics | ||
| // still returns 200 when alert-management-api is off. | ||
| func EmptyMetricsHandler() http.Handler { | ||
| return promhttp.HandlerFor(prometheus.NewRegistry(), promhttp.HandlerOpts{}) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| package k8s | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus/testutil" | ||
|
|
||
| osmv1 "github.com/openshift/api/monitoring/v1" | ||
| ) | ||
|
|
||
| func TestGCOrphanedARCs_ListErrorIncrementsMetric(t *testing.T) { | ||
| metrics := newAlertRelabelConfigGCMetrics() | ||
| mock := &mockARCInterface{listErr: errors.New("list failed")} | ||
| rrm := &relabeledRulesManager{alertRelabelConfigs: mock, gcMetrics: metrics} | ||
|
|
||
| rrm.gcOrphanedARCs(context.Background(), map[string]struct{}{}) | ||
|
|
||
| if got := testutil.ToFloat64(metrics.listErrors); got != 1 { | ||
| t.Fatalf("list errors = %v, want 1", got) | ||
| } | ||
| if got := testutil.ToFloat64(metrics.deleteErrors); got != 0 { | ||
| t.Fatalf("delete errors = %v, want 0", got) | ||
| } | ||
| } | ||
|
|
||
| func TestGCOrphanedARCs_DeleteErrorIncrementsMetric(t *testing.T) { | ||
| metrics := newAlertRelabelConfigGCMetrics() | ||
| mock := &mockARCInterface{ | ||
| arcs: map[string]*osmv1.AlertRelabelConfig{ | ||
| "openshift-monitoring/arc-orphan": newARC("openshift-monitoring", "arc-orphan", "rule-gone", nil, nil), | ||
| }, | ||
| deleteErr: errors.New("delete failed"), | ||
| } | ||
| rrm := &relabeledRulesManager{alertRelabelConfigs: mock, gcMetrics: metrics} | ||
|
|
||
| rrm.gcOrphanedARCs(context.Background(), map[string]struct{}{}) | ||
|
|
||
| if got := testutil.ToFloat64(metrics.deleteErrors); got != 1 { | ||
| t.Fatalf("delete errors = %v, want 1", got) | ||
| } | ||
| if len(mock.deleted) != 0 { | ||
| t.Fatalf("expected no deletions, got %v", mock.deleted) | ||
| } | ||
| } | ||
|
|
||
| func TestGCOrphanedARCs_GitOpsOrphanSetsGauge(t *testing.T) { | ||
| metrics := newAlertRelabelConfigGCMetrics() | ||
| mock := &mockARCInterface{ | ||
| arcs: map[string]*osmv1.AlertRelabelConfig{ | ||
| "openshift-monitoring/arc-gitops": newARC("openshift-monitoring", "arc-gitops", "rule-gone", | ||
| map[string]string{"argocd.argoproj.io/tracking-id": "some-id"}, nil), | ||
| "openshift-monitoring/arc-live": newARC("openshift-monitoring", "arc-live", "rule-alive", nil, nil), | ||
| }, | ||
| } | ||
| rrm := &relabeledRulesManager{alertRelabelConfigs: mock, gcMetrics: metrics} | ||
|
|
||
| rrm.gcOrphanedARCs(context.Background(), map[string]struct{}{"rule-alive": {}}) | ||
|
|
||
| if got := testutil.ToFloat64(metrics.gitopsOrphans); got != 1 { | ||
| t.Fatalf("gitops orphans = %v, want 1", got) | ||
| } | ||
| } | ||
|
|
||
| func TestAlertRelabelConfigGCMetricsHandlerExposesSeries(t *testing.T) { | ||
| req := httptest.NewRequest(http.MethodGet, "/metrics", nil) | ||
| rec := httptest.NewRecorder() | ||
| AlertRelabelConfigGCMetricsHandler().ServeHTTP(rec, req) | ||
| if rec.Code != http.StatusOK { | ||
| t.Fatalf("status %d", rec.Code) | ||
| } | ||
| body := rec.Body.String() | ||
| for _, name := range []string{ | ||
| MetricAlertRelabelConfigGCListErrorsTotal, | ||
| MetricAlertRelabelConfigGCDeleteErrorsTotal, | ||
| MetricAlertRelabelConfigGitOpsOrphans, | ||
| } { | ||
| if !strings.Contains(body, name) { | ||
| t.Errorf("handler body missing metric %s:\n%s", name, body) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestEmptyMetricsHandlerHasNoGCSeries(t *testing.T) { | ||
| req := httptest.NewRequest(http.MethodGet, "/metrics", nil) | ||
| rec := httptest.NewRecorder() | ||
| EmptyMetricsHandler().ServeHTTP(rec, req) | ||
| if rec.Code != http.StatusOK { | ||
| t.Fatalf("status %d", rec.Code) | ||
| } | ||
| body := rec.Body.String() | ||
| if strings.Contains(body, MetricAlertRelabelConfigGCListErrorsTotal) { | ||
| t.Fatalf("empty handler unexpectedly exposed GC metrics: %s", body) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
how will cluster admins know that something's not going correctly? e.g. can we add metrics + alerting rule?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed