-
Notifications
You must be signed in to change notification settings - Fork 2
/
jolokia_discovery.py
executable file
·313 lines (241 loc) · 8.07 KB
/
jolokia_discovery.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
__version__ = '0.2.1'
import collections
import json
import optparse
import re
import sys
# pylint: disable=import-error, no-name-in-module
try:
from urlparse import urlsplit
except ImportError:
from urllib.parse import urlsplit
try:
from urlparse import urlunsplit
except ImportError:
from urllib.parse import urlunsplit
try:
from urllib2 import HTTPError
except ImportError:
from urllib.error import HTTPError
try:
from urllib2 import Request
except ImportError:
from urllib.request import Request
try:
from urllib2 import URLError
except ImportError:
from urllib.error import URLError
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
# pylint: enable=import-error, no-name-in-module
PARAMETERS = collections.namedtuple(
'PARAMETERS',
[
'jolokia_url',
'mbean_pattern',
'jmx_host',
'jmx_port',
'jmx_user',
'jmx_pass',
],
)
class JolokiaStatusError(Exception):
pass
class OptionParserError(Exception):
def __init__(self, message, status=2):
super(OptionParserError, self).__init__()
self.message = message
self.status = status
def __str__(self):
return repr(self.message)
class NonExitOptionParser(optparse.OptionParser):
#pylint: disable=too-many-public-methods
def exit(self, status=0, msg=None):
raise OptionParserError(msg, status)
def build_arguments(argv):
usage = (
'''%prog [options] "jolokia_url" "mbean_pattern"'''
)
version = '%%prog %s' % __version__
description = 'Zabbix Low Level Discovery with Jolokia.'
option_parser = NonExitOptionParser(
usage=usage,
version=version,
description=description,
)
option_parser.add_option(
'-H', '--jmx-host', help='Hostname of JMX remote',
)
option_parser.add_option(
'-P', '--jmx-port', type='int', help='Port number of JMX remote',
)
option_parser.add_option(
'-u', '--jmx-user', help='Username of JMX remote user',
)
option_parser.add_option(
'-p', '--jmx-pass', help='Password of JMX remote user',
)
arguments = option_parser.parse_args(argv)
return arguments
def build_parameters(arguments):
(option_args, positional_args) = arguments
validate_option_args(option_args)
try:
validate_jolokia_url(positional_args[0])
validate_mbean_pattern(positional_args[1])
except IndexError:
raise OptionParserError(
'Insufficient number of positional arguments was specified.'
)
parameters = PARAMETERS(
jolokia_url=positional_args[0],
mbean_pattern=positional_args[1],
jmx_host=option_args.jmx_host,
jmx_port=option_args.jmx_port,
jmx_user=option_args.jmx_user,
jmx_pass=option_args.jmx_pass,
)
return parameters
def validate_option_args(option_args):
def with_jmx_host():
if not option_args.jmx_port:
raise OptionParserError(
'Cannot specify jmx-host unless jmx-port was also specified.'
)
if option_args.jmx_user and not option_args.jmx_pass:
raise OptionParserError(
'Cannot specify jmx-user unless jmx-pass was also specified.'
)
if option_args.jmx_pass and not option_args.jmx_user:
raise OptionParserError(
'Cannot specify jmx-pass unless jmx-user was also specified.'
)
def without_jmx_host():
if option_args.jmx_port:
raise OptionParserError(
'Cannot specify jmx-port unless jmx-host was also specified.'
)
if option_args.jmx_user:
raise OptionParserError(
'Cannot specify jmx-user unless jmx-host was also specified.'
)
if option_args.jmx_pass:
raise OptionParserError(
'Cannot specify jmx-pass unless jmx-host was also specified.'
)
if option_args.jmx_host is not None:
with_jmx_host()
else:
without_jmx_host()
def validate_jolokia_url(url):
if not url:
raise OptionParserError(
'Empty string was specified for Jolokia URL.'
)
# pylint: disable=line-too-long
regex = re.compile(
r'^(?:[a-z0-9\.\-]*)://' # scheme is validated separately
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$',
re.IGNORECASE
)
# pylint: enable=line-too-long
schemes = ['http']
if url.split('://')[0].lower() not in schemes:
raise OptionParserError(
'Invalid scheme was specified for Jolokia URL.'
)
if not regex.search(url):
scheme, netloc, path, query, fragment = urlsplit(url)
try:
netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
except UnicodeError: # invalid domain part
raise OptionParserError(
'Invalid domain part was specified for Jolokia URL.'
)
url = urlunsplit((scheme, netloc, path, query, fragment))
if not regex.search(url):
raise OptionParserError(
'Invalid Jolokia URL was specified.'
)
def validate_mbean_pattern(mbean_pattern):
if not mbean_pattern:
raise OptionParserError(
'Empty string was specified for MBean pattern.'
)
def build_request(parameters):
request = Request(parameters.jolokia_url)
query_dict = {}
query_dict['type'] = 'search'
query_dict['mbean'] = parameters.mbean_pattern
if parameters.jmx_host:
query_dict['target'] = {}
query_dict['target']['url'] = (
'service:jmx:rmi:///jndi/rmi://{0}:{1}/jmxrmi'
''.format(parameters.jmx_host, parameters.jmx_port)
)
if parameters.jmx_user:
query_dict['target']['user'] = parameters.jmx_user
query_dict['target']['password'] = parameters.jmx_pass
query_json = json.dumps(query_dict).encode('utf-8')
request.add_data(query_json)
return request
def query_jolokia(request):
result = urlopen(request)
result_dict = json.load(result)
if result_dict['status'] == 200:
return result_dict
else:
raise JolokiaStatusError(
'Invalid status code returned from Jolokia.'
)
def show_lld_item(result_dict):
lld_item_dict = {}
lld_item_dict['data'] = []
for value in result_dict['value']:
lld_item = object_name_to_dictionary(value)
lld_item_dict['data'].append(lld_item)
lld_item_json = json.dumps(lld_item_dict)
print(lld_item_json)
def object_name_to_dictionary(object_name):
(domain, key_property_list) = object_name.split(':', 1)
dictionary = {}
dictionary['{#DOMAIN}'] = domain
for key_property in key_property_list.split(','):
(name, value) = key_property.split('=', 1)
name_upper = name.upper()
name_macrofied = '{{#KPL_{0}}}'.format(
re.sub('[^A-Z0-9_.]', '_', name_upper)
)
dictionary[name_macrofied] = value
return dictionary
def main(argv=None):
if argv is None:
argv = sys.argv
try:
arguments = build_arguments(argv[1:])
parameters = build_parameters(arguments)
request = build_request(parameters)
result_dict = query_jolokia(request)
show_lld_item(result_dict)
except (JolokiaStatusError, HTTPError, URLError) as error:
print(str(error), file=sys.stderr)
return 1
except OptionParserError as error:
if error.message:
print(str(error.message), file=sys.stderr)
return error.status
else:
return 0
if __name__ == '__main__':
sys.exit(main())