From 6196875dab8826c42021bb805ac77237397d194d Mon Sep 17 00:00:00 2001 From: Waschndolos Date: Fri, 6 Dec 2024 07:16:21 +0100 Subject: [PATCH] Avoiding deadlock when jenkins updates the build iterator while accessing the build to count the number of builds --- .../prometheus/collectors/jobs/NbBuildsGauge.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jenkinsci/plugins/prometheus/collectors/jobs/NbBuildsGauge.java b/src/main/java/org/jenkinsci/plugins/prometheus/collectors/jobs/NbBuildsGauge.java index fcfae1c4f..29af287e2 100644 --- a/src/main/java/org/jenkinsci/plugins/prometheus/collectors/jobs/NbBuildsGauge.java +++ b/src/main/java/org/jenkinsci/plugins/prometheus/collectors/jobs/NbBuildsGauge.java @@ -5,10 +5,12 @@ import io.prometheus.client.SimpleCollector; import org.jenkinsci.plugins.prometheus.collectors.CollectorType; import org.jenkinsci.plugins.prometheus.collectors.builds.BuildsMetricCollector; - +import java.util.concurrent.locks.ReentrantReadWriteLock; public class NbBuildsGauge extends BuildsMetricCollector, Gauge> { + private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + protected NbBuildsGauge(String[] labelNames, String namespace, String subsystem) { super(labelNames, namespace, subsystem); } @@ -30,7 +32,12 @@ protected SimpleCollector.Builder getCollectorBuilder() { @Override public void calculateMetric(Job jenkinsObject, String[] labelValues) { - int nbBuilds = jenkinsObject.getBuildsAsMap().size(); - this.collector.labels(labelValues).set(nbBuilds); + lock.readLock().lock(); + try { + int nbBuilds = jenkinsObject.getBuildsAsMap().size(); + this.collector.labels(labelValues).set(nbBuilds); + } finally { + lock.readLock().unlock(); + } } }