From 12dc32ec4ec557d83444c3ed344847587dc8dfbf Mon Sep 17 00:00:00 2001 From: Matt Whelan Date: Mon, 16 Dec 2024 08:49:06 -0800 Subject: [PATCH] metrics: address race in MetricVec collection code path The *Vec metrics employ a RWLock to control concurrent access to the set of labels they maintain, but we were reading that set without holding the lock during metric collections. Fixes: #137396 Release note: None --- pkg/util/metric/metric.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pkg/util/metric/metric.go b/pkg/util/metric/metric.go index 4ffd6706c0c2..a7162f211a81 100644 --- a/pkg/util/metric/metric.go +++ b/pkg/util/metric/metric.go @@ -1361,6 +1361,8 @@ func (gv *GaugeVec) GetType() *prometheusgo.MetricType { // ToPrometheusMetrics implements PrometheusExportable. func (gv *GaugeVec) ToPrometheusMetrics() []*prometheusgo.Metric { + gv.RLock() + defer gv.RUnlock() metrics := make([]*prometheusgo.Metric, 0, len(gv.encounteredLabelValues)) for _, labels := range gv.encounteredLabelValues { @@ -1462,6 +1464,8 @@ func (cv *CounterVec) GetType() *prometheusgo.MetricType { // ToPrometheusMetrics implements PrometheusExportable. func (cv *CounterVec) ToPrometheusMetrics() []*prometheusgo.Metric { + cv.RLock() + defer cv.RUnlock() metrics := make([]*prometheusgo.Metric, 0, len(cv.encounteredLabelValues)) for _, labels := range cv.encounteredLabelValues { @@ -1542,6 +1546,8 @@ func (hv *HistogramVec) GetType() *prometheusgo.MetricType { // ToPrometheusMetrics implements PrometheusExportable. func (hv *HistogramVec) ToPrometheusMetrics() []*prometheusgo.Metric { + hv.RLock() + defer hv.RUnlock() metrics := make([]*prometheusgo.Metric, 0, len(hv.encounteredLabelValues)) for _, labels := range hv.encounteredLabelValues {