Skip to content

Commit

Permalink
chore: concurrent map write in internal/metric test. (#4141)
Browse files Browse the repository at this point in the history
* chore: concurrent map write in internal/metric test.

Signed-off-by: qicz <[email protected]>

* fix lint

Signed-off-by: qicz <[email protected]>

---------

Signed-off-by: qicz <[email protected]>
  • Loading branch information
qicz authored Sep 4, 2024
1 parent 8b6b268 commit 301eedd
Showing 1 changed file with 37 additions and 18 deletions.
55 changes: 37 additions & 18 deletions internal/metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"os"
"reflect"
"strings"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -95,24 +96,7 @@ func TestGauge(t *testing.T) {

// simulate a function that builds an indicator and changes its value
metricsFunc := []func(){
func() {
metricName := "current_irs_queue_num"
description := "current number of ir in queue, by ir type"

currentIRsNum := NewGauge(
metricName,
description,
)

// only the last recorded value (2) will be exported for this gauge
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(1)
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(3)
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(2)

currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(1)
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(3)
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(2)
},
metricFunc,
}
for _, f := range metricsFunc {
f()
Expand All @@ -125,6 +109,25 @@ func TestGauge(t *testing.T) {
loadMetricsFile(t, name, writer)
}

func metricFunc() {
metricName := "current_irs_queue_num"
description := "current number of ir in queue, by ir type"

currentIRsNum := NewGauge(
metricName,
description,
)

// only the last recorded value (2) will be exported for this gauge
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(1)
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(3)
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(2)

currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(1)
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(3)
currentIRsNum.With(NewLabel("ir-type").Value("xds")).Record(2)
}

func TestHistogram(t *testing.T) {
name := "histogram_metric"

Expand Down Expand Up @@ -165,6 +168,22 @@ func TestHistogram(t *testing.T) {
loadMetricsFile(t, name, writer)
}

func TestConcurrentMetricAccess(t *testing.T) {
var wg sync.WaitGroup
const concurrency = 100

for i := 0; i < concurrency; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
t.Logf("concurrency metric access at %d", idx)
metricFunc()
}(i)
}

wg.Wait()
}

// newTestMetricsProvider Create an OTEL Metrics Provider for testing use only
func newTestMetricsProvider(metricType string, writer io.Writer) (*metric.MeterProvider, error) {
enc := json.NewEncoder(writer)
Expand Down

0 comments on commit 301eedd

Please sign in to comment.