From 1ebc9a82be3424eb20c3b9a74107c75e5ffc41b9 Mon Sep 17 00:00:00 2001 From: Guilherme Santos <157053549+gsantos-hc@users.noreply.github.com> Date: Thu, 12 Dec 2024 14:47:47 -0500 Subject: [PATCH] fix(metrics): sidecar injection false positives Do not increment the `injections_by_namespace` metric when no injection is performed. --- agent-inject/metrics.go | 4 ++++ agent-inject/metrics_test.go | 24 +++++++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/agent-inject/metrics.go b/agent-inject/metrics.go index b2d9c24f..97853128 100644 --- a/agent-inject/metrics.go +++ b/agent-inject/metrics.go @@ -49,6 +49,10 @@ var ( ) func incrementInjections(namespace string, res MutateResponse) { + if !res.InjectedInit && !res.InjectedSidecar { + return + } + // Injection type can be one of: init_and_sidecar (default); init_only; or sidecar_only typeLabel := metricsLabelTypeBoth if res.InjectedInit && !res.InjectedSidecar { diff --git a/agent-inject/metrics_test.go b/agent-inject/metrics_test.go index 65101877..83b420e5 100644 --- a/agent-inject/metrics_test.go +++ b/agent-inject/metrics_test.go @@ -18,6 +18,7 @@ func Test_incrementInjections(t *testing.T) { namespace string mutateResponse MutateResponse expectedLabels map[string]string + noIncrement bool }{ "init_only": { namespace: "init", @@ -52,16 +53,33 @@ func Test_incrementInjections(t *testing.T) { metricsLabelType: metricsLabelTypeBoth, }, }, + "no_injection": { + namespace: "none", + mutateResponse: MutateResponse{ + InjectedInit: false, + InjectedSidecar: false, + }, + expectedLabels: nil, + noIncrement: true, + }, } for name, test := range tests { t.Run(name, func(t *testing.T) { t.Cleanup(func() { injectionsByNamespace.Reset() }) + + expInc := 1 + if test.noIncrement { + expInc = 0 + } + incrementInjections(test.namespace, test.mutateResponse) - assert.Equal(t, 1, testutil.CollectAndCount(injectionsByNamespace)) - check := injectionsByNamespace.With(prometheus.Labels(test.expectedLabels)) - assert.Equal(t, float64(1), testutil.ToFloat64(check)) + assert.Equal(t, expInc, testutil.CollectAndCount(injectionsByNamespace)) + if !test.noIncrement { + check := injectionsByNamespace.With(prometheus.Labels(test.expectedLabels)) + assert.Equal(t, float64(1), testutil.ToFloat64(check)) + } }) } }