From 4426962ec85142e3254de8ccbd57cb5d49a1d9c9 Mon Sep 17 00:00:00 2001 From: t-falconnet Date: Fri, 11 Feb 2022 15:06:39 +0100 Subject: [PATCH] ethtool_linux: add mutex around entries access Signed-off-by: t-falconnet --- collector/ethtool_linux.go | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/collector/ethtool_linux.go b/collector/ethtool_linux.go index c68b3e9f..99995960 100644 --- a/collector/ethtool_linux.go +++ b/collector/ethtool_linux.go @@ -27,6 +27,7 @@ import ( "regexp" "sort" "strings" + "sync" "syscall" "github.com/go-kit/log" @@ -73,6 +74,7 @@ func (e *ethtoolLibrary) LinkInfo(intf string) (ethtool.EthtoolCmd, error) { type ethtoolCollector struct { fs sysfs.FS entries map[string]*prometheus.Desc + entriesMutex sync.Mutex ethtool Ethtool deviceFilter netDevFilter infoDesc *prometheus.Desc @@ -420,15 +422,7 @@ func (c *ethtoolCollector) Update(ch chan<- prometheus.Metric) error { val := stats[metric] // Check to see if this metric exists; if not then create it and store it in c.entries. - entry, exists := c.entries[metric] - if !exists { - entry = prometheus.NewDesc( - metricFQName, - fmt.Sprintf("Network interface %s", metric), - []string{"device"}, nil, - ) - c.entries[metric] = entry - } + entry := c.entries(metric) ch <- prometheus.MustNewConstMetric( entry, prometheus.UntypedValue, float64(val), device) } @@ -436,3 +430,18 @@ func (c *ethtoolCollector) Update(ch chan<- prometheus.Metric) error { return nil } + +func (c *ethtoolCollector) entries(key string) *prometheus.Desc { + c.entriesMutex.Lock() + defer c.entriesMutex.Unlock() + + if _, ok := c.entries[key]; !ok { + c.entries[key] = prometheus.NewDesc( + metricFQName, + fmt.Sprintf("Network interface %s", metric), + []string{"device"}, nil, + ) + } + + return c.entries[key] +}