forked from filipealmeida/probespawner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jmxprobe.py
420 lines (390 loc) · 22.9 KB
/
jmxprobe.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
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
# Any copyright is dedicated to the Public Domain.
# http://creativecommons.org/publicdomain/zero/1.0/
#
# _____ ___ ____ ___
#|_ _/ _ \| _ \ / _ \ _
# | || | | | | | | | | (_)
# | || |_| | |_| | |_| |_
# |_| \___/|____/ \___/(_)
# Redo the JMXProbe, consider make a new one, remember cooljmxprobe?
from dummyprobe import DummyProbe
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.MBeanInfo;
import uuid
import re
from pprint import pprint
import time
import datetime
import sys
from array import array
import com.xhaus.jyson.JysonCodec as json
import logging
import traceback
logger = logging.getLogger(__name__)
class JMXProbe(DummyProbe):
def initialize(self):
self.attributes = []
self.operations = []
self.mbeanProbes = []
self.mbeanDict = {}
username = self.getInputProperty("username")
password = self.getInputProperty("password")
host = self.getInputProperty("host")
port = self.getInputProperty("port")
self.queries = None
if self.getInputProperty("alias") != None:
self.alias = self.getInputProperty("alias")
else:
self.alias = host + "_" + str(port)
#connect to JMX server
ad=array(java.lang.String,[username,password])
self.n = java.util.HashMap()
self.n.put (javax.management.remote.JMXConnector.CREDENTIALS, ad);
#Jboss initial context: jndi.java.naming.provider.url=jnp://localhost:1099/
#jndi.java.naming.factory.url=org.jboss.naming:org.jnp.interfaces
#jndi.java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
if self.getInputProperty("factory") != None:
logger.info("Factory initialized %s = %s", javax.management.remote.JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, self.getInputProperty("factory"))
self.n.put(javax.management.remote.JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, self.getInputProperty("factory"))
self.n.put(javax.naming.InitialContext.SECURITY_PRINCIPAL, username);
self.n.put(javax.naming.InitialContext.SECURITY_CREDENTIALS, password);
if self.getInputProperty("url") != None:
self.urlstring = self.getInputProperty("url")
else:
self.urlstring = "service:jmx:rmi:///jndi/rmi://" + host + ":" + str(port) + "/jmxrmi"
self.initializeJMX()
def initializeJMX(self):
logger.info("Connecting to %s", self.urlstring)
self.jmxurl = javax.management.remote.JMXServiceURL(self.urlstring)
self.testme = javax.management.remote.JMXConnectorFactory.connect(self.jmxurl,self.n)
self.connection = self.testme.getMBeanServerConnection()
self.buildJMXProbesFromQueries()
self.backwardCompatibilityConfiguration()
self.computeAliases()
self.optimizeQueries()
logger.info("Got %d mbeanProbes", len(self.mbeanProbes))
def backwardCompatibilityConfiguration(self):
if self.getInputProperty("metricsfile"):
logger.info("loading %s", self.getInputProperty("metricsfile"))
stream = open(self.getInputProperty("metricsfile"))
if type(stream) is not file:
raise TypeError,'Argument should be a file object!'
# Check for the opened mode
if stream.mode != 'r':
raise ValueError,'Stream should be opened in read-only mode!'
try:
lines = stream.readlines()
lineno=0
i = iter(lines)
for line in i:
lineno += 1
line = line.strip()
# Skip null lines
if not line: continue
# Skip lines which are comments
if line[0] == '#': continue
obj = line.split("/",1)
self.mbeanProbes[len(self.mbeanProbes):] = { "name" : obj[0], "attribute" : obj[1], "type": "attribute" }
except IOError, e:
raise
else:
#TODO: cleanup here, iterate once, avoid appends, etc., maybe change datastructure to manage both getAttribute and invoke
logger.info("Loading objects from metrics field")
lineno=0
if self.getInputProperty("metrics") != None:
for line in self.getInputProperty("metrics"):
lineno += 1
obj = line.split("/")
oname = obj[0]
oattr = obj[1]
if len(obj) > 2:
oattr = obj.pop()
oname = "/".join(obj)
logger.debug("Got attribute %s from %s (%d)", oattr, oname, len(obj))
self.mbeanProbes[len(self.mbeanProbes):] = [{ "name" : oname, "attribute" : oattr, "type": "attribute" }]
logger.info("Loading objects from attributes field")
lineno=0
#TODO: parse object URI correctly, which means review above oattr/oname and apply same BETTER strategy below
if self.getInputProperty("attributes") != None:
for line in self.getInputProperty("attributes"):
lineno += 1
obj = line.split("/",1)
logger.debug("Got attribute %s from %s", obj[1], obj[0])
self.mbeanProbes[len(self.mbeanProbes):] = [{ "name" : obj[0], "attribute" : obj[1], "type": "attribute" }]
#TODO: add invoke capabilities http://docs.oracle.com/cd/E19717-01/819-7758/gcitp/index.html
logger.info("Loading objects from operations field")
if self.getInputProperty("operations") != None:
for operationObject in self.getInputProperty("operations"):
logger.debug("Got operation: %s", operationObject['name'])
obj = operationObject['name'].split("/",1)
operationObject['name'] = obj[0]
operationObject['attribute'] = obj[1]
operationObject['type'] = "operation"
if 'params' not in operationObject:
operationObject['params'] = None
if 'signatures' not in operationObject:
operationObject['signatures'] = None
objuuid = uuid.uuid1()
self.mbeanDict[objuuid] = operationObject
self.mbeanProbes[len(self.mbeanProbes):] = [operationObject]
def computeAlias(self, obj):
#TODO: UGLYYYYYYYYYYYYYY
if 'object_alias' in obj:
objtype = "${type}";
objname = "${name}";
objlocation = "${objlocation}"
match = re.search(r'type=([a-zA-Z0-9$.]+)',str(obj['name']), re.I)
if match:
objtype = match.group(1)
match = re.search(r'name=([a-zA-Z0-9$.]+)',str(obj['name']), re.I)
if match:
objname = match.group(1)
match = re.search(r'location=([a-zA-Z0-9$.]+)',str(obj['name']), re.I)
if match:
objlocation = match.group(1)
objalias = re.sub('\${type}', objtype, obj['object_alias'])
objalias = re.sub('\${name}', objname, objalias)
objalias = re.sub('\${location}', objlocation, objalias)
prefix = self.alias + "." + objalias
else:
prefix = self.alias + "." + re.sub(r'[a-zA-Z$0-9]+=','.',str(obj['name']))
prefix = re.sub(r'[:,]','',prefix)
prefix = re.sub(r'^\.','',prefix)
suffix = str(obj['attribute'])
return prefix + "." + suffix
def computeAliases(self):
#TODO: handle operations
#, "alias": str(element.getClassName()) + "." + str(attribute.getName())
i = iter(self.mbeanProbes)
for obj in i:
obj['alias'] = self.computeAlias(obj)
def optimizeQueries(self):
logger.info("Optimizing queries.")
#TODO: handle operations
#, "alias": str(element.getClassName()) + "." + str(attribute.getName())
i = iter(self.mbeanProbes)
for obj in i:
if obj['type'] == "attribute":
if obj['name'] not in self.mbeanDict:
self.mbeanDict[obj['name']] = {}
self.mbeanDict[obj['name']]['name'] = obj['name']
self.mbeanDict[obj['name']]['attributes'] = []
self.mbeanDict[obj['name']]['parts'] = {}
self.mbeanDict[obj['name']]['type'] = 'attribute'
extrakeys = re.findall(r'((\w+)=(\w+)),?', obj['name'])
for parts in extrakeys:
(group, variable, value) = parts
self.mbeanDict[obj['name']]["object_" + variable.lower()] = value
self.mbeanDict[obj['name']]['parts'][variable.lower()] = value
self.mbeanDict[obj['name']]['attributes'][len(self.mbeanDict[obj['name']]['attributes']):] = [obj['attribute']]
def buildJMXProbesFromQueries(self):
if self.getInputProperty("queries") != None:
logger.info("Processing configured queries")
for queryObject in self.getInputProperty("queries"):
self.queryObjectToMbeanProbe(queryObject)
#TODO: [{'attribute': 'ObjectPendingFinalizationCount', 'type': 'attribute', 'alias': 'sun.management.MemoryImpl.ObjectPendingFinalizationCount', 'name': 'java.lang:type=Memory'}, {'attribute': 'HeapMemoryUsage', 'type': 'attribute', 'alias': 'sun.management.MemoryImpl.HeapMemoryUsage', 'name': 'java.lang:type=Memory'}, {'attribute': 'NonHeapMemoryUsage', 'type': 'attribute', 'alias': 'sun.management.MemoryImpl.NonHeapMemoryUsage', 'name': 'java.lang:type=Memory'}, {'attribute': 'Verbose', 'type': 'attribute', 'alias': 'sun.management.MemoryImpl.Verbose', 'name': 'java.lang:type=Memory'}, {'attribute': 'ObjectName', 'type': 'attribute', 'alias': 'sun.management.MemoryImpl.ObjectName', 'name': 'java.lang:type=Memory'}, {'attribute': 'StartTime', 'type': 'attribute', 'alias': 'sun.management.RuntimeImpl.StartTime', 'name': 'java.lang:type=Runtime'}, {'attribute': 'Uptime', 'type': 'attribute', 'alias': 'sun.management.RuntimeImpl.Uptime', 'name': 'java.lang:type=Runtime'}, {'attribute': 'CollectionCount', 'type': 'attribute', 'alias': 'sun.management.GarbageCollectorImpl.CollectionCount', 'name': 'java.lang:type=GarbageCollector,name=ConcurrentMarkSweep'}, {'attribute': 'CollectionTime', 'type': 'attribute', 'alias': 'sun.management.GarbageCollectorImpl.CollectionTime', 'name': 'java.lang:type=GarbageCollector,name=ConcurrentMarkSweep'}, {'attribute': 'CollectionCount', 'type': 'attribute', 'alias': 'sun.management.GarbageCollectorImpl.CollectionCount', 'name': 'java.lang:type=GarbageCollector,name=ParNew'}, {'attribute': 'CollectionTime', 'type': 'attribute', 'alias': 'sun.management.GarbageCollectorImpl.CollectionTime', 'name': 'java.lang:type=GarbageCollector,name=ParNew'}, {'attribute': 'Count', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.Count', 'name': 'java.nio:type=BufferPool,name=direct'}, {'attribute': 'TotalCapacity', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.TotalCapacity', 'name': 'java.nio:type=BufferPool,name=direct'}, {'attribute': 'MemoryUsed', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.MemoryUsed', 'name': 'java.nio:type=BufferPool,name=direct'}, {'attribute': 'Name', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.Name', 'name': 'java.nio:type=BufferPool,name=direct'}, {'attribute': 'ObjectName', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.ObjectName', 'name': 'java.nio:type=BufferPool,name=direct'}, {'attribute': 'Count', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.Count', 'name': 'java.nio:type=BufferPool,name=mapped'}, {'attribute': 'TotalCapacity', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.TotalCapacity', 'name': 'java.nio:type=BufferPool,name=mapped'}, {'attribute': 'MemoryUsed', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.MemoryUsed', 'name': 'java.nio:type=BufferPool,name=mapped'}, {'attribute': 'Name', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.Name', 'name': 'java.nio:type=BufferPool,name=mapped'}, {'attribute': 'ObjectName', 'type': 'attribute', 'alias': 'sun.management.ManagementFactoryHelper$1.ObjectName', 'name': 'java.nio:type=BufferPool,name=mapped'}]
#TODO: duplicate code, solve
def queryObjectToMbeanProbe(self, queryObject):
logger.info("Preparing %s", queryObject['object_name'])
count = 0
objectList = self.connection.queryMBeans(javax.management.ObjectName(queryObject['object_name']), None)
for element in objectList:
info = self.connection.getMBeanInfo(element.getObjectName())
attrInfo = info.getAttributes()
for attribute in attrInfo:
try:
obj = None
if 'attributes' in queryObject:
if attribute.getName() in queryObject['attributes']:
logger.info("Match on selected attribute, adding+ %s/%s", element.getObjectName(), attribute.getName())
value = self.connection.getAttribute(element.getObjectName(), attribute.getName())
obj = { "name" : str(element.getObjectName()), "attribute" : str(attribute.getName()), "type": "attribute" }
else:
logger.info("%s::All attributes selected, adding %s/%s", self.getInputProperty("__inputname__"), element.getObjectName(), attribute.getName())
value = self.connection.getAttribute(element.getObjectName(), attribute.getName())
obj = { "name" : str(element.getObjectName()), "attribute" : str(attribute.getName()), "type": "attribute" }
if obj != None:
if 'object_alias' in queryObject:
obj['object_alias'] = queryObject['object_alias']
if 'object_value_to_jmxquery' in queryObject and queryObject['object_value_to_jmxquery'] == True:
#com.bea:ServerRuntime=box1,Name=ThreadPoolRuntime,Type=ThreadPoolRuntime
value = self.connection.getAttribute(javax.management.ObjectName(obj['name']), obj['attribute'])
newQueryObject = {}
newQueryObject['object_name'] = str(value)
if 'whitelist' in queryObject and len(queryObject['whitelist']) > 0:
newQueryObject['attributes'] = queryObject['whitelist']
if 'blacklist' in queryObject and len(queryObject['blacklist']) > 0:
logger.warning("TODO: implement blacklist")
logger.warning(value)
logger.warning("trying to add %s", newQueryObject['object_name']);
self.queryObjectToMbeanProbe(newQueryObject)
else:
self.mbeanProbes[len(self.mbeanProbes):] = [obj]
count+=1
except:
tb = traceback.format_exc()
logger.warning("%s Failure grabbing attribute %s in %s", self.getInputProperty("__inputname__"), attribute, queryObject['object_name'])
logger.warning(tb)
#value = self.connection.getAttribute(javax.management.ObjectName(obj['name']), obj['attribute'])
logger.info("Added %d queries for %s", count, queryObject['object_name'])
def cleanup(self):
self.testme.close()
def getCompositeDataSupportDict(self, value):
jsonDict = {}
for key in value.getCompositeType().keySet():
jsonDict[key] = {}
self.setupValue(jsonDict[key], value.get(key))
return jsonDict
#TODO: such ugly: rethink and redo
def setupValue(self, value, jsonDict):
if (value.__class__.__name__ == "wtf"):
return jsonDict
elif (value.__class__.__name__ == "CompositeDataSupport"):
for key in value.getCompositeType().keySet():
val = value.get(key)
if val != None:
jsonDict[str(key)] = self.setupValue(val, {})
return jsonDict
elif (value.__class__.__name__ == "array"):
data = []
dataType = "array"
i = iter(value)
for obj in i:
data.append(self.setupValue(obj, {}))
elif (value.__class__.__name__ == "float"):
dataType = "float"
data = value
elif (value.__class__.__name__ == "long"):
dataType = "long"
data = value
elif (value.__class__.__name__ == "int"):
dataType = "int"
data = value * 1
else:
dataType = "string"
data = str(value)
if len(jsonDict) == 0:
return data
try:
data
if len(jsonDict) > 0:
jsonDict[dataType] = data
if (dataType == "int") or (dataType == "long") or (dataType == "float"):
jsonDict['number'] = data + 0.0
jsonDict['value'] = str(data)
except Exception, ex:
logger.debug(ex)
return jsonDict
return jsonDict
#TODO: redo this, chaos
def queryJmx(self, key):
obj = self.mbeanDict[key]
if "attributes" in obj:
attributeValues = self.connection.getAttributes(javax.management.ObjectName(key), obj['attributes'])
for value in attributeValues:
obj['attribute'] = value.getName();
obj['alias'] = self.computeAlias(obj)
self.handleResponse(obj, value.getValue())
elif obj["type"] == "attribute":
value = self.connection.getAttribute(javax.management.ObjectName(obj['name']), obj['attribute'])
self.handleResponse(obj, value)
else:
value = self.connection.invoke(javax.management.ObjectName(obj['name']), obj['attribute'], obj['params'], obj['signatures'])
self.handleResponse(obj, value)
#TODO: redo all class, it has just reached the point where you can't distinguish this from a salad
def handleResponse(self, obj, value):
jsonDict = {}
jsonDict['jmxurl'] = self.urlstring
jsonDict['@timestamp'] = self.cycle["startdt"]
jsonDict['name'] = obj['name']
jsonDict['attribute'] = obj['attribute']
jsonDict['alias'] = obj['alias']
if 'parts' in self.mbeanDict[obj['name']]:
for key in self.mbeanDict[obj['name']]['parts']:
jsonDict[key] = self.mbeanDict[obj['name']]['parts'][key]
#TODO: such crap, this class shoul not import re
if isinstance(self.getInputProperty("replaceInValue"), list):
for i in self.getInputProperty("replaceInValue"):
(pattern, repl) = i
for key in jsonDict:
if isinstance(jsonDict[key], str) or isinstance(jsonDict[key], unicode):
jsonDict[key] = re.sub(pattern, repl, jsonDict[key])
if self.getInputProperty("compositeDataToManyRecords") == True and value.__class__.__name__ == "CompositeDataSupport":
for key in value.getCompositeType().keySet():
val = value.get(key)
if val != None:
jsonDict['attribute'] = obj['attribute'] + "." + key
jsonDict['alias'] = obj['alias'] + "." + key
self.setupValue(val, jsonDict)
self.processData(jsonDict)
return True
else:
self.setupValue(value, jsonDict)
if self.getInputProperty("arrayElementsToRecord"):
if 'array' in jsonDict:
i = iter(jsonDict['array'])
for aobj in i:
if isinstance(aobj, dict):
aobj['jmxurl'] = self.urlstring
aobj['@timestamp'] = self.cycle["startdt"]
aobj['name'] = obj['name']
aobj['attribute'] = obj['attribute']
aobj['alias'] = obj['alias']
self.processData(aobj)
elif isinstance(aobj, str) or isinstance(aobj, unicode):
oobj = {}
oobj['jmxurl'] = self.urlstring
oobj['@timestamp'] = self.cycle["startdt"]
oobj['name'] = obj['name']
oobj['attribute'] = obj['attribute']
oobj['alias'] = obj['alias']
oobj['string'] = aobj
self.processData(oobj)
return True
else:
self.processData(jsonDict)
return False
return self.processData(jsonDict)
def tick(self):
#TODO: this thing with operations and attributes is a messup, repeated code everywhere: REDO whole class
#i = iter(self.mbeanDict)
for obj in self.mbeanDict:
try:
self.queryJmx(obj)
#except javax.management.InstanceNotFoundException, e:
except java.io.IOException, ex:
logger.error("java.io.IOException, retrying JMX connection %s in 30 seconds", str(self.urlstring))
logger.error(ex)
time.sleep(30);
self.initializeJMX()
pass
except Exception, ex:
logger.error("Caught exception getting value: %s", str(obj))
logger.error(ex)
try:
self.attributes.remove(obj)
logger.error("Failed to get instace of request object. Removing %s", str(obj))
sys.exit(100) #see TODO: above, handle this and try to recover is it existed sometime in the past
except ValueError:
logger.error("ValueError")
pass # or scream: thing not in some_list!
except AttributeError:
logger.error("AttributeError")
pass # call security, some_list not quacking like a list!
if (len(self.mbeanProbes) < 1):
raise "No objects left, quietly leaving work"
logger.info("tick")