-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathnexus_exporter.py
executable file
·270 lines (247 loc) · 11.2 KB
/
nexus_exporter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python
import os
import json
import time
import base64
import logging
import urllib.request as urllib2
from urllib.parse import urlparse
from urllib.error import URLError, HTTPError
from prometheus_client import start_http_server
from prometheus_client.core import GaugeMetricFamily, REGISTRY
import argparse
LOG = logging.getLogger('nexus-exporter')
logging.basicConfig(level=logging.INFO)
def valid_url(string):
"""Validate url input argument.
Takes a string. Return valid url or raise URLError.
"""
try:
if not getattr(urlparse(string), "scheme") or \
not getattr(urlparse(string), "netloc"):
raise URLError("""Invalid URL: %s.
Don't forget including the scheme (usually http)
Example: http://localhost:8081""" % string)
return string
except AttributeError:
raise URLError("""Invalid URL: %s.
Don't forget including the scheme (usually http)
Example: http://localhost:8081""" % string)
def parse():
parser = argparse.ArgumentParser(
description='Export Prometheus metrics for Sonatype Nexus > 3.6')
parser.add_argument(
'--host',
metavar='HOST',
type=valid_url,
help='address with port where Nexus is available. Defaults to\
http://localhost:8081',
default=os.environ.get("NEXUS_HOST", "http://localhost:8081"))
parser.add_argument("--password",
"-p",
help="admin password",
default=os.environ.get("NEXUS_ADMIN_PASSWORD",
"admin123"))
parser.add_argument("--user",
"-u",
help="Nexus user name, defaults to admin",
default=os.environ.get("NEXUS_USERNAME", "admin"))
parser.add_argument("--port",
type=int,
help="Exporter port: default 9184",
default=9184)
return parser.parse_args()
class NexusCollector(object):
def __init__(self, target, user, password):
self._target = target.rstrip("/")
auth_string = '%s:%s' % (user, password)
self._auth = base64.standard_b64encode(auth_string.encode()).decode('utf8')
self._info = {}
self._data = {}
def collect(self):
# make requests
nexus_up = True
try:
self._request_data()
except HTTPError as err:
if err.code == 401:
LOG.error('Authentication failure, please check \
username/password')
nexus_up = False
except URLError as e:
LOG.error('unable to fetch data from metric endpoint: %s', e)
nexus_up = False
yield GaugeMetricFamily('nexus_up',
'Whether the Nexus server is up.',
value=nexus_up)
if not nexus_up:
return
i = self._info['system-runtime']
yield GaugeMetricFamily('nexus_processors_available',
'Available Processors',
value=i['availableProcessors'])
yield GaugeMetricFamily('nexus_free_memory_bytes',
'Free Memory (bytes)',
value=i['freeMemory'])
yield GaugeMetricFamily('nexus_total_memory_bytes',
'Total Memory (bytes)',
value=i['totalMemory'])
yield GaugeMetricFamily('nexus_max_memory_bytes',
'Max Memory (bytes)',
value=i['maxMemory'])
yield GaugeMetricFamily('nexus_threads_used',
'Threads Used',
value=i['threads'])
i = self._info['system-filestores']
for fsname, details in i.items():
mount = self._mount_point(details['description'])
fts = GaugeMetricFamily(
'nexus_filestore_total_space_bytes',
'Total Filestore Space (%s)' % details['description'],
labels=["mount_point", "fsname", "fstype", "readonly"])
fts.add_metric(
[mount, fsname, details['type'],
str(details['readOnly'])], details['totalSpace'])
yield fts
fus = GaugeMetricFamily(
'nexus_filestore_usable_space_bytes',
'Usable Filestore Space (%s)' % details['description'],
labels=["mount_point", "fsname", "fstype", "readonly"])
fus.add_metric(
[mount, fsname, details['type'],
str(details['readOnly'])], details['usableSpace'])
yield fus
fas = GaugeMetricFamily(
'nexus_filestore_unallocated_space_bytes',
'Unallocated Filestore Space (%s)' % details['description'],
labels=["mount_point", "fsname", "fstype", "readonly"])
fas.add_metric(
[mount, fsname, details['type'],
str(details['readOnly'])], details['unallocatedSpace'])
yield fas
i = self._data['gauges']
yield GaugeMetricFamily('nexus_jvm_memory_heap_committed_bytes',
'',
value=i['jvm.memory.heap.committed']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_heap_init_bytes',
'',
value=i['jvm.memory.heap.init']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_heap_max_bytes',
'',
value=i['jvm.memory.heap.max']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_heap_used_bytes',
'',
value=i['jvm.memory.heap.used']['value'])
yield GaugeMetricFamily(
'nexus_jvm_memory_nonheap_committed_bytes',
'',
value=i['jvm.memory.non-heap.committed']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_nonheap_init_bytes',
'',
value=i['jvm.memory.non-heap.init']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_nonheap_max_bytes',
'',
value=i['jvm.memory.non-heap.max']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_nonheap_used_bytes',
'',
value=i['jvm.memory.non-heap.used']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_total_committed_bytes',
'',
value=i['jvm.memory.total.committed']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_total_init_bytes',
'',
value=i['jvm.memory.total.init']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_total_max_bytes',
'',
value=i['jvm.memory.total.max']['value'])
yield GaugeMetricFamily('nexus_jvm_memory_total_used_bytes',
'',
value=i['jvm.memory.total.used']['value'])
yield GaugeMetricFamily('nexus_jvm_uptime_seconds',
'',
value=i['jvm.vm.uptime']['value'] / 1000.0)
i = self._data['meters']
et = GaugeMetricFamily('nexus_events_total',
'Nexus Events Count',
labels=['level'])
et.add_metric(['trace'], i['metrics.trace']['count'])
et.add_metric(['debug'], i['metrics.debug']['count'])
et.add_metric(['info'], i['metrics.info']['count'])
et.add_metric(['warn'], i['metrics.warn']['count'])
et.add_metric(['error'], i['metrics.error']['count'])
yield et
hr = GaugeMetricFamily('nexus_webapp_http_response_total',
'Nexus Webapp HTTP Response Count',
labels=['code'])
hr.add_metric(
['1xx'],
i['org.eclipse.jetty.webapp.WebAppContext.1xx-responses']['count'])
hr.add_metric(
['2xx'],
i['org.eclipse.jetty.webapp.WebAppContext.2xx-responses']['count'])
hr.add_metric(
['3xx'],
i['org.eclipse.jetty.webapp.WebAppContext.3xx-responses']['count'])
hr.add_metric(
['4xx'],
i['org.eclipse.jetty.webapp.WebAppContext.4xx-responses']['count'])
hr.add_metric(
['5xx'],
i['org.eclipse.jetty.webapp.WebAppContext.5xx-responses']['count'])
yield hr
i = self._data['timers']
hq = GaugeMetricFamily('nexus_webapp_http_request_total',
'Nexus Webapp HTTP Request Count',
labels=['method'])
hq.add_metric(
['connect'],
i['org.eclipse.jetty.webapp.WebAppContext.connect-requests']
['count'])
hq.add_metric(
['delete'],
i['org.eclipse.jetty.webapp.WebAppContext.delete-requests']
['count'])
hq.add_metric(
['get'],
i['org.eclipse.jetty.webapp.WebAppContext.get-requests']['count'])
hq.add_metric(
['head'],
i['org.eclipse.jetty.webapp.WebAppContext.head-requests']['count'])
hq.add_metric(
['move'],
i['org.eclipse.jetty.webapp.WebAppContext.move-requests']['count'])
hq.add_metric(
['options'],
i['org.eclipse.jetty.webapp.WebAppContext.options-requests']
['count'])
hq.add_metric([
'other'
], i['org.eclipse.jetty.webapp.WebAppContext.other-requests']['count'])
hq.add_metric(
['post'],
i['org.eclipse.jetty.webapp.WebAppContext.post-requests']['count'])
hq.add_metric(
['put'],
i['org.eclipse.jetty.webapp.WebAppContext.put-requests']['count'])
hq.add_metric([
'trace'
], i['org.eclipse.jetty.webapp.WebAppContext.trace-requests']['count'])
yield hq
def _mount_point(self, description):
return description.split('(')[0].strip()
def _request_data(self):
info_request = urllib2.Request(
"{0}/service/rest/atlas/system-information".format(self._target))
info_request.add_header("Authorization", "Basic %s" % self._auth)
self._info = json.loads(urllib2.urlopen(info_request).read())
data_request = urllib2.Request("{0}/service/metrics/data".format(
self._target))
data_request.add_header("Authorization", "Basic %s" % self._auth)
self._data = json.loads(urllib2.urlopen(data_request).read())
if __name__ == "__main__":
args = parse()
LOG.info('starting nexus exporter on port %s' % args.port)
REGISTRY.register(NexusCollector(args.host, args.user, args.password))
start_http_server(args.port)
while True:
time.sleep(1)