Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ababushk/13907561e4293be2d8299b8730b16961 to your computer and use it in GitHub Desktop.
Save ababushk/13907561e4293be2d8299b8730b16961 to your computer and use it in GitHub Desktop.
A groovy script that can be executed in Jenkins Script Console, it adds additional metric to regular Jenkins Prometheus plugin output
import jenkins.model.Jenkins
import io.prometheus.client.Collector;
import io.prometheus.client.GaugeMetricFamily
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Collector.MetricFamilySamples;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class BuildsCountByJobCollector extends Collector {
private static final Logger LOG = LoggerFactory.getLogger(BuildsCountByJobCollector.class)
String metricName = "jenkins_builds_in_queue_by_job_count"
String helpString = "Builds in queue count by job"
String labelName = "jenkins_job"
List<MetricFamilySamples> collect() {
List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
GaugeMetricFamily labeledGauge = new GaugeMetricFamily(metricName,
helpString,
[labelName]);
Map buildsCount = [:]
def q = Jenkins.instance.queue
q.items.each {
if (it.task.class == org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution$PlaceholderTask) {
def taskRunId = it.task?.runId
def jobName = taskRunId.substring(0, taskRunId.lastIndexOf('#'))
buildsCount[jobName] = buildsCount.get(jobName, 0) + 1
}
}
buildsCount.each {
labeledGauge.addMetric([it.key], it.value);
}
mfs.add(labeledGauge);
return mfs;
}
}
CollectorRegistry.defaultRegistry.collectors().each {
println "Found prometheus collector of ${it.class}"
if (it.class.getCanonicalName() == BuildsCountByJobCollector.class.getCanonicalName()) {
println "Found our own Collector, will delete"
// WARNING! it will delete all your custom collectors!
CollectorRegistry.defaultRegistry.unregister(it)
}
}
println "--> Registering custom prometheus collector"
BuildsCountByJobCollector col = new BuildsCountByJobCollector().register()
@ababushk
Copy link
Author

Ooops, it seems I could've created custom Collector and don't bother with Threads

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment