From 395cace69fc30f249ca95aef4723914cf49b5e20 Mon Sep 17 00:00:00 2001 From: mmetc <92726601+mmetc@users.noreply.github.com> Date: Tue, 25 Jul 2023 12:19:26 +0200 Subject: [PATCH] fix double push of metrics by properly handling tickers (#2374) --- pkg/apiserver/apic_metrics.go | 11 +++++++---- pkg/apiserver/apic_metrics_test.go | 8 ++++---- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/pkg/apiserver/apic_metrics.go b/pkg/apiserver/apic_metrics.go index 4befcf50c..7305dfcd6 100644 --- a/pkg/apiserver/apic_metrics.go +++ b/pkg/apiserver/apic_metrics.go @@ -81,7 +81,7 @@ func (a *apic) SendMetrics(stop chan (bool)) { const checkInt = 20 * time.Second // intervals must always be > 0 - metInts := []time.Duration{1, a.metricsIntervalFirst, a.metricsInterval} + metInts := []time.Duration{1*time.Millisecond, a.metricsIntervalFirst, a.metricsInterval} log.Infof("Start send metrics to CrowdSec Central API (interval: %s once, then %s)", metInts[1].Round(time.Second), metInts[2]) @@ -94,8 +94,6 @@ func (a *apic) SendMetrics(stop chan (bool)) { return metInts[count] } - // store the list of machine IDs to compare - // with the next list machineIDs := []string{} reloadMachineIDs := func() { @@ -107,6 +105,10 @@ func (a *apic) SendMetrics(stop chan (bool)) { machineIDs = ids } + // store the list of machine IDs to compare + // with the next list + reloadMachineIDs() + checkTicker := time.NewTicker(checkInt) metTicker := time.NewTicker(nextMetInt()) @@ -121,9 +123,10 @@ func (a *apic) SendMetrics(stop chan (bool)) { reloadMachineIDs() if !slices.Equal(oldIDs, machineIDs) { log.Infof("capi metrics: machines changed, immediate send") - metTicker.Reset(1) + metTicker.Reset(1*time.Millisecond) } case <-metTicker.C: + metTicker.Stop() metrics, err := a.GetMetrics() if err != nil { log.Errorf("unable to get metrics (%s), will retry", err) diff --git a/pkg/apiserver/apic_metrics_test.go b/pkg/apiserver/apic_metrics_test.go index 7e37ea1e9..fdb94f4e2 100644 --- a/pkg/apiserver/apic_metrics_test.go +++ b/pkg/apiserver/apic_metrics_test.go @@ -26,15 +26,15 @@ func TestAPICSendMetrics(t *testing.T) { }{ { name: "basic", - duration: time.Millisecond * 30, - metricsInterval: time.Millisecond * 5, + duration: time.Millisecond * 60, + metricsInterval: time.Millisecond * 10, expectedCalls: 5, setUp: func(api *apic) {}, }, { name: "with some metrics", - duration: time.Millisecond * 30, - metricsInterval: time.Millisecond * 5, + duration: time.Millisecond * 60, + metricsInterval: time.Millisecond * 10, expectedCalls: 5, setUp: func(api *apic) { api.dbClient.Ent.Machine.Delete().ExecX(context.Background())