Fix race condition with Exemplar in Counter (#1146)

* Fix race condition with Exemplar in Counter

Potential fix for #1145.

Signed-off-by: Fabian Stäber <fabian@fstab.de>

* Fix race condition with Exemplar in Counter

Signed-off-by: Fabian Stäber <fabian@fstab.de>

Signed-off-by: Fabian Stäber <fabian@fstab.de>
This commit is contained in:
Fabian Stäber 2022-10-17 20:50:50 +02:00 committed by bwplotka
parent 1f93f64580
commit ddd7f0edcd
1 changed files with 3 additions and 2 deletions

View File

@ -140,12 +140,13 @@ func (c *counter) get() float64 {
} }
func (c *counter) Write(out *dto.Metric) error { func (c *counter) Write(out *dto.Metric) error {
val := c.get() // Read the Exemplar first and the value second. This is to avoid a race condition
// where users see an exemplar for a not-yet-existing observation.
var exemplar *dto.Exemplar var exemplar *dto.Exemplar
if e := c.exemplar.Load(); e != nil { if e := c.exemplar.Load(); e != nil {
exemplar = e.(*dto.Exemplar) exemplar = e.(*dto.Exemplar)
} }
val := c.get()
return populateMetric(CounterValue, val, c.labelPairs, exemplar, out) return populateMetric(CounterValue, val, c.labelPairs, exemplar, out)
} }