|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +import json |
| 4 | +import re |
| 5 | +import sys |
| 6 | +import time |
| 7 | +try: |
| 8 | + import urllib2 |
| 9 | +except: |
| 10 | + # Python 3 |
| 11 | + import urllib.request as urllib2 |
| 12 | + |
| 13 | +from prometheus_client import start_http_server |
| 14 | +from prometheus_client.core import GaugeMetricFamily, REGISTRY |
| 15 | + |
| 16 | + |
| 17 | +class JenkinsCollector(object): |
| 18 | + def __init__(self, target): |
| 19 | + self._target = target.rstrip("/") |
| 20 | + |
| 21 | + def collect(self): |
| 22 | + # The build statuses we want to export about. |
| 23 | + statuses = ["lastBuild", "lastCompletedBuild", "lastFailedBuild", |
| 24 | + "lastStableBuild", "lastSuccessfulBuild", "lastUnstableBuild", |
| 25 | + "lastUnsuccessfulBuild"] |
| 26 | + |
| 27 | + # The metrics we want to export. |
| 28 | + metrics = {} |
| 29 | + for s in statuses: |
| 30 | + snake_case = re.sub('([A-Z])', '_\\1', s).lower() |
| 31 | + metrics[s] = { |
| 32 | + 'number': |
| 33 | + GaugeMetricFamily('jenkins_job_{0}'.format(snake_case), |
| 34 | + 'Jenkins build number for {0}'.format(s), labels=["jobname"]), |
| 35 | + 'duration': |
| 36 | + GaugeMetricFamily('jenkins_job_{0}_duration_seconds'.format(snake_case), |
| 37 | + 'Jenkins build duration in seconds for {0}'.format(s), labels=["jobname"]), |
| 38 | + 'timestamp': |
| 39 | + GaugeMetricFamily('jenkins_job_{0}_timestamp_seconds'.format(snake_case), |
| 40 | + 'Jenkins build timestamp in unixtime for {0}'.format(s), labels=["jobname"]), |
| 41 | + } |
| 42 | + |
| 43 | + # Request exactly the information we need from Jenkins |
| 44 | + result = json.loads(urllib2.urlopen( |
| 45 | + "{0}/api/json?tree=jobs[name,{1}]".format( |
| 46 | + self._target, ",".join([s + "[number,timestamp,duration]" for s in statuses]))) |
| 47 | + .read().decode("utf-8")) |
| 48 | + |
| 49 | + for job in result['jobs']: |
| 50 | + name = job['name'] |
| 51 | + for s in statuses: |
| 52 | + # If there's a null result, we want to export zeros. |
| 53 | + status = job[s] or {} |
| 54 | + metrics[s]['number'].add_metric([name], status.get('number', 0)) |
| 55 | + metrics[s]['duration'].add_metric([name], status.get('duration', 0) / 1000.0) |
| 56 | + metrics[s]['timestamp'].add_metric([name], status.get('timestamp', 0) / 1000.0) |
| 57 | + |
| 58 | + for s in statuses: |
| 59 | + for m in metrics[s].values(): |
| 60 | + yield m |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + if len(sys.argv) < 2: |
| 65 | + sys.stderr.write("Usage: jenkins_exporter.py http://jenkins:8080\n") |
| 66 | + sys.exit(1) |
| 67 | + REGISTRY.register(JenkinsCollector(sys.argv[1])) |
| 68 | + start_http_server(9118) |
| 69 | + while True: time.sleep(1) |
0 commit comments