08 Nov 2010, 17:30

JMX query in Python (CPython)

Share

JMX had good intentions but the API is only implemented in Java, a Java product for Java, with no access to the outside world.

Jython was one of the solution but many times I had needed to call JMX from a CPython.

Jpype solved this problem and works extremely well.

Just install Jpype then try something like this:

The execution is really really fast, faster than a jvm run ?? and memory usage is really really slow !

#!/usr/bin/env python2.6
import jpype
from jpype import java
from jpype import javax

HOST='gf0'
PORT=8386
USER='admin'
PASS='mypass'

URL = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi" % (HOST, PORT)
#this it the path of your libjvm /usr/lib/jvm/sun-jdk-1.6/jre/lib/amd64/server/libjvm.so on linux
jpype.startJVM("/System/Library/Frameworks/JavaVM.framework/Libraries/libjvm_compat.dylib")
java.lang.System.out.println("JVM load OK")

jhash = java.util.HashMap()
jarray=jpype.JArray(java.lang.String)([USER,PASS])
jhash.put (javax.management.remote.JMXConnector.CREDENTIALS, jarray);
jmxurl = javax.management.remote.JMXServiceURL(URL)
jmxsoc = javax.management.remote.JMXConnectorFactory.connect(jmxurl,jhash)
connection = jmxsoc.getMBeanServerConnection();


object="java.lang:type=Threading"
attribute="ThreadCount"
attr=connection.getAttribute(javax.management.ObjectName(object),attribute)
print  attribute, attr

#Memory is a special case the answer is a Treemap in a CompositeDataSupport
object="java.lang:type=Memory"
attribute="HeapMemoryUsage"
attr=connection.getAttribute(javax.management.ObjectName(object),attribute)
print attr.contents.get("used")