-
Notifications
You must be signed in to change notification settings - Fork 460
/
agent_jolokia
executable file
·426 lines (368 loc) · 17.1 KB
/
agent_jolokia
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import urllib2, sys, os, socket, pprint, base64, ssl
import getopt
from httplib import HTTPConnection, HTTPSConnection
try:
from simplejson import json
except ImportError:
try:
import json
except ImportError:
sys.stdout.write("<<<jolokia_info>>>\n")
sys.stdout.write("Error: Missing JSON library for Agent Plugin mk_jolokia\n")
exit()
# assigned in parse_arguments
opt_verbose = False
opt_debug = False
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
"""
sends basic authentication with the first request,
before the server even asks for it
"""
def http_request(self, req):
url = req.get_full_url()
realm = None
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
global_vars = [
( "java.lang:type=Memory/NonHeapMemoryUsage/used", "NonHeapMemoryUsage", [] ),
( "java.lang:type=Memory/NonHeapMemoryUsage/max", "NonHeapMemoryMax", [] ),
( "java.lang:type=Memory/HeapMemoryUsage/used", "HeapMemoryUsage", [] ),
( "java.lang:type=Memory/HeapMemoryUsage/max", "HeapMemoryMax", [] ),
( "java.lang:type=Threading/ThreadCount", "ThreadCount", [] ),
( "java.lang:type=Threading/DaemonThreadCount", "DeamonThreadCount", [] ),
( "java.lang:type=Threading/PeakThreadCount", "PeakThreadCount", [] ),
( "java.lang:type=Threading/TotalStartedThreadCount", "TotalStartedThreadCount", [] ),
( "java.lang:type=Runtime/Uptime", "Uptime", [] ),
( "java.lang:type=GarbageCollector,name=*/CollectionCount", "", [] ),
( "java.lang:type=GarbageCollector,name=*/CollectionTime", "", [] ),
( "java.lang:name=CMS%20Perm%20Gen,type=MemoryPool/Usage/used", "PermGenUsage", [] ),
( "java.lang:name=CMS%20Perm%20Gen,type=MemoryPool/Usage/max", "PermGenMax", [] ),
]
specific_vars = {
"weblogic" : [
( "*:*/CompletedRequestCount", None, [ "ServerRuntime" ] ),
( "*:*/QueueLength", None, [ "ServerRuntime" ] ),
( "*:*/StandbyThreadCount", None, [ "ServerRuntime" ] ),
( "*:*/PendingUserRequestCount", None, [ "ServerRuntime" ] ),
( "*:Name=ThreadPoolRuntime,*/ExecuteThreadTotalCount", None, [ "ServerRuntime" ] ),
( "*:*/ExecuteThreadIdleCount", None, [ "ServerRuntime" ] ),
( "*:*/HoggingThreadCount", None, [ "ServerRuntime" ] ),
( "*:Type=WebAppComponentRuntime,*/OpenSessionsCurrentCount", None, [ "ServerRuntime", "ApplicationRuntime" ] ),
],
"tomcat" : [
( "*:type=Manager,*/activeSessions,maxActiveSessions", None, [ "path", "context" ] ),
( "*:j2eeType=Servlet,name=default,*/stateName", None, [ "WebModule" ] ),
# Check not yet working
( "*:j2eeType=Servlet,name=default,*/requestCount", None, [ "WebModule" ]),
( "*:name=*,type=ThreadPool/maxThreads", None, []),
( "*:name=*,type=ThreadPool/currentThreadCount", None, []),
( "*:name=*,type=ThreadPool/currentThreadsBusy", None, []),
# too wide location for addressing the right info
# ( "*:j2eeType=Servlet,*/requestCount", None, [ "WebModule" ] ),
],
"jboss" : [
( "*:type=Manager,*/activeSessions,maxActiveSessions", None, [ "path", "context" ] ),
],
}
class HTTPSValidatingConnection(HTTPSConnection):
def __init__(self, host, ca_file, key_file, cert_file):
HTTPSConnection.__init__(self, host, key_file=key_file, cert_file=cert_file)
self.__ca_file = ca_file
self.__key_file = key_file
self.__cert_file = cert_file
def connect(self):
HTTPConnection.connect(self)
if self.__ca_file:
self.sock = ssl.wrap_socket(self.sock, keyfile=self.key_file, certfile=self.cert_file,
ca_certs=self.__ca_file, cert_reqs=ssl.CERT_REQUIRED)
else:
self.sock = ssl.wrap_socket(self.sock, keyfile=self.key_file, certfile=self.cert_file,
ca_certs=self.__ca_file, cert_reqs=ssl.CERT_NONE)
class HTTPSAuthHandler(urllib2.HTTPSHandler):
def __init__(self, ca_file, key, cert):
urllib2.HTTPSHandler.__init__(self)
self.__ca_file = ca_file
self.__key = key
self.__cert = cert
def https_open(self, req):
# do_open expects a class as the first parameter but getConnection will act
# as a facotry function
return self.do_open(self.getConnection, req)
def getConnection(self, host, timeout):
return HTTPSValidatingConnection(host, ca_file=self.__ca_file,
key_file=self.__key, cert_file=self.__cert)
def fetch_var(protocol, server, port, path, suburi, cert_path, itemspec):
url = "%s://%s:%d/%s/%s" % (protocol, server, port, suburi, path)
if opt_verbose:
sys.stderr.write("Fetching: %s\n" % url)
try:
conn = urllib2.urlopen(url)
data = conn.read()
if opt_verbose:
sys.stderr.write("Result: %s\n\n" % data)
except Exception, e:
if opt_debug:
raise
sys.stderr.write("ERROR: %s\n" % e)
return []
try:
obj = json.loads(json_data)
except Exception, e:
sys.stderr.write('ERROR: Invalid json code (%s)\n' % e)
sys.stderr.write(' Response %s\n' % json_data)
return []
if obj.get('status', 200) != 200:
sys.stderr.write('ERROR: Invalid response when fetching url %s\n' % url)
sys.stderr.write(' Response: %s\n' % json_data)
return []
# Only take the value of the object. If the value is an object
# take the first items first value.
# {'Catalina:host=localhost,path=\\/test,type=Manager': {'activeSessions': 0}}
if 'value' not in obj:
if opt_verbose:
sys.stderr.write("ERROR: not found: %s\n" % path)
return []
val = obj.get('value', None)
return make_item_list((), val, itemspec)
# convert single values into lists of items in
# case value is a 1-levelled or 2-levelled dict
def make_item_list(path, value, itemspec):
if type(value) != dict:
if type(value) == str:
value = value.replace(r'\/', '/')
return [(path, value)]
else:
result = []
for key, subvalue in value.items():
# Handle filtering via itemspec
miss = False
while itemspec and '=' in itemspec[0]:
if itemspec[0] not in key:
miss = True
break
itemspec = itemspec[1:]
if miss:
continue
item = extract_item(key, itemspec)
if not item:
item = (key,)
result += make_item_list(path + item, subvalue, [])
return result
# Example:
# key = 'Catalina:host=localhost,path=\\/,type=Manager'
# itemsepc = [ "path" ]
# --> "/"
def extract_item(key, itemspec):
path = key.split(":", 1)[-1]
components = path.split(",")
item = ()
comp_dict = {}
for comp in components:
parts = comp.split("=")
if len(parts) == 2:
left, right = parts
comp_dict[left] = right
for pathkey in itemspec:
if pathkey in comp_dict:
right = comp_dict[pathkey]
right = right.replace(r'\/', '/')
if '/' in right:
right = '/' + right.split('/')[-1]
item = item + (right,)
return item
def query_instance(inst):
# Prepare user/password authentication via HTTP Auth
password_mngr = urllib2.HTTPPasswordMgrWithDefaultRealm()
if inst.get("password"):
password_mngr.add_password(None, "%s://%s:%d/" %
(inst["protocol"], inst["server"], inst["port"]), inst["user"], inst["password"])
handlers = []
if inst["protocol"] == "https":
if inst["mode"] == 'https' and (inst["client_key"] is None or
inst["client_cert"] is None):
sys.stdout.write('<<<jolokia_info>>>\n')
sys.stderr.write("ERROR: https set up as authentication method but certificate "
"wasn't provided\n")
return
handlers.append(HTTPSAuthHandler(inst["cert_path"],
inst["client_key"], inst["client_cert"]))
if inst["mode"] == 'digest':
handlers.append(urllib2.HTTPDigestAuthHandler(password_mngr))
elif inst["mode"] == "basic_preemptive":
handlers.append(PreemptiveBasicAuthHandler(password_mngr))
elif inst["mode"] == "basic" and inst["protocol"] != "https":
handlers.append(urllib2.HTTPBasicAuthHandler(password_mngr))
if handlers:
opener = urllib2.build_opener(*handlers)
urllib2.install_opener(opener)
# Determine type of server
server_info = fetch_var(inst["protocol"], inst["server"], inst["port"], "", inst["suburi"],
inst["cert_path"], "")
sys.stdout.write('<<<jolokia_info>>>\n')
if server_info:
d = dict(server_info)
version = d.get(('info', 'version'), "unknown")
product = d.get(('info', 'product'), "unknown")
if inst.has_key("product"):
product = inst["product"]
agentversion = d.get(('agent',), "unknown")
sys.stdout.write("%s %s %s %s\n" % (inst["instance"], product, version, agentversion))
else:
sys.stdout.write("%s ERROR\n" % (inst["instance"],))
sys.stdout.write('<<<jolokia_metrics>>>\n')
sys.stdout.write("%s ERROR\n" % (inst["instance"],))
return
sys.stdout.write('<<<jolokia_metrics>>>\n')
# Fetch the general information first
for path, title, itemspec in global_vars + specific_vars.get(product, []):
try:
values = fetch_var(inst["protocol"], inst["server"], inst["port"], "read/" + path,
inst["suburi"], inst["cert_path"], itemspec)
# In case of network errors skip this server
except IOError:
return
except socket.timeout:
return
except:
if opt_debug:
raise
# Simply ignore exceptions. Need to be removed for debugging
continue
for subinstance, value in values:
if not subinstance and not title:
print "INTERNAL ERROR: %s" % value
continue
if "threadStatus" in subinstance or "threadParam" in subinstance:
continue
if len(subinstance) > 1:
item = ",".join((inst["instance"],) + subinstance[:-1])
else:
item = inst["instance"]
if title:
if subinstance:
tit = title + "." + subinstance[-1]
else:
tit = title
else:
tit = subinstance[-1]
sys.stdout.write("%s %s %s\n" % (item.replace(" ", "_"), tit, value))
def usage():
sys.stderr.write(
"""Check_MK Jolokia Agent
USAGE: mk_jolokia [OPTIONS]
mk_jolokia --help
OPTIONS:
--help Show this help message and exit
--server=SERVER Host name or IP address of the Jolokia server. Default: localhost
--port=PORT TCP Port of the Jolokia server. Default: 8080
--user=USER Username to use for the connection. Default: monitoring
--password=PASSWORD Password to use for connecting. Default: none
--mode=MODE Authentication mode. Can be "basic" or "digest". Default: digest
--suburi=SUBURI Path-component of the URI to query. Default: jolokia
--instance=INSTANCE Name of the instance in the monitoring
--debug Debug mode: let Python exceptions come through
--verbose Output some more detailed information
""")
def parse_arguments():
short_options = ''
long_options = [
'help', 'verbose', 'server=', 'port=', 'user=', 'password=', 'mode=', 'suburi=', 'instance=',
'protocol=', 'cert_path=', 'client_cert=', 'client_key='
]
try:
opts, args = getopt.getopt(sys.argv[1:], short_options, long_options)
except getopt.GetoptError, err:
sys.stderr.write("%s\n" % err)
sys.exit(1)
opts = dict([(o.replace("--", ""), a) for o, a in opts])
if 'help' in opts:
return None
global opt_debug
opt_debug = 'debug' in opts
global opt_verbose
opt_verbose = 'verbose' in opts
for optional, default in [('server', "localhost"),
('user', "monitoring"),
('password', None),
('mode', "digest"),
('suburi', "jolokia"),
('port', 8080),
('instance', lambda: str(opts['port'])),
('protocol', "http"),
('cert_path', None),
('client_cert', None),
('client_key', None)]:
if optional not in opts:
if callable(default):
opts[optional] = default()
else:
opts[optional] = default
return opts
def main():
opts = parse_arguments()
if not opts:
usage()
return 0
# List of instances to monitor. Each instance is a dict where
# the global configuration values can be overridden.
instances = [{}]
# We have to deal with socket timeouts. Python > 2.6
# supports timeout parameter for the urllib2.urlopen method
# but we are on a python 2.5 system here which seem to use the
# default socket timeout. We are local here so set it to 1 second.
socket.setdefaulttimeout(1.0)
print("<<<jolokia>>>")
# Compute list of instances to monitor. If the user has defined
# instances in his configuration, we will use this (a list
# of dicts).
for inst in instances:
for varname, value in [("server", opts['server']),
("port", int(opts['port'])),
("user", opts['user']),
("password", opts['password']),
("mode", opts['mode']),
("suburi", opts['suburi']),
("instance", opts['instance']),
("protocol", opts['protocol']),
("cert_path", opts['cert_path']),
("client_cert", opts['client_cert']),
("client_key", opts['client_key'])]:
if varname not in inst:
inst[varname] = value
if not inst["instance"]:
inst["instance"] = str(inst["port"])
inst["instance"] = inst["instance"].replace(" ", "_")
query_instance(inst)
return 0
if __name__ == "__main__":
main()