Skip to content

Instantly share code, notes, and snippets.

@pradeepfn
Created November 25, 2012 12:50
Show Gist options
  • Select an option

  • Save pradeepfn/4143374 to your computer and use it in GitHub Desktop.

Select an option

Save pradeepfn/4143374 to your computer and use it in GitHub Desktop.
Simple JMX client to monitor Carbon Server/any other server
import com.sun.management.OperatingSystemMXBean;
import javax.management.*;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Hashtable;
public class JMXClient {
private static final String USER_NAME= "admin"; //hard coded
private static final String PASSWORD = "admin"; //hard coded
private static final Long POLLING_TIME= 5*1000L;// 5 sec
private static final String HEAP_MEMORY_USAGE = "HeapMemoryUsage";
private static final String THREAD_COUNT = "ThreadCount";
private static final String SYSTEM_LOAD_AVERAGE = "SystemLoadAverage";
/* For simplicity, we declare "throws Exception".
Real programs will usually want finer-grained exception handling. */
public static void main(String[] args) throws Exception {
String outputFileName = null;
String remoteServerJMXUrl = null;
if (args[0] != null && args[1] != null) {
outputFileName = args[0];
remoteServerJMXUrl = args[1];
}
else {
System.out.println("No fileName/Remote JMX URL provided: please see the usage..");
}
System.out.println("Using the remote JMX URL :" + remoteServerJMXUrl);
System.out.println("Output will be written to :" + outputFileName);
JMXServiceURL url = new JMXServiceURL(remoteServerJMXUrl);
Hashtable<String, String[]> environment = new Hashtable<String, String[]>();
String[] credentials = new String[]{USER_NAME, PASSWORD};
environment.put(JMXConnector.CREDENTIALS, credentials);
boolean connected = false; // tracking the connection status
JMXConnector jmxConnection = null;
do {
try {
jmxConnection = JMXConnectorFactory.connect(url, environment);
connected = true;
} catch (IOException e) { //re-trying the connection while the remote server become available..o
System.out.println("Error while connecting to the remote server : re-trying...");
Thread.sleep(5*1000); // 5 sec sleep
}
} while (!connected);
MBeanServerConnection mBeanServerConnection = jmxConnection.getMBeanServerConnection();
CPUMonitor performanceMonitor = new CPUMonitor();
performanceMonitor.init(mBeanServerConnection);
// creating a file to write to output
File file = new File(outputFileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("Error while creating the output file");
}
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try {
while (true) {
//we are doing a flush at each wrie. Not closing the stream however
writeToFileAsCsv(bw, getDataString(mBeanServerConnection, performanceMonitor));
}
} finally {
bw.close();
fw.close();
jmxConnection.close();
}
}
private static String[] getDataString(MBeanServerConnection mBeanServerConnection, CPUMonitor performanceMonitor) throws Exception {
String heapMemUsage = getComplexProperty(mBeanServerConnection, ManagementFactory.MEMORY_MXBEAN_NAME, HEAP_MEMORY_USAGE, "used").toString();
String threadCount = mBeanServerConnection.getAttribute(
new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME), THREAD_COUNT).toString();
Thread.sleep(POLLING_TIME);
String cpuUsage = String.valueOf(performanceMonitor.getCpuUsage(mBeanServerConnection) * 100);
String systemLoadAverage = mBeanServerConnection.getAttribute(
new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME), SYSTEM_LOAD_AVERAGE).toString();
String[] tempArray = {heapMemUsage,
threadCount,
cpuUsage,systemLoadAverage};
System.out.println(heapMemUsage + " , " + threadCount + " , " + cpuUsage+" , "+ systemLoadAverage);
return tempArray;
}
public static String getComplexProperty(MBeanServerConnection mbsc, String mbeanName, String prop1, String prop2) throws AttributeNotFoundException, InstanceNotFoundException, MalformedObjectNameException, MBeanException, ReflectionException, NullPointerException, IOException {
CompositeDataSupport ds1 = (CompositeDataSupport) mbsc.getAttribute(
new ObjectName(mbeanName), prop1);
return ds1.get(prop2).toString();
}
public static void writeToFileAsCsv( BufferedWriter writer, String[] array) {
String content = null;
//create csvString
for (String s : array) {
if (content == null) {
content = s;
}
content = content + "," + s;
}
try {
writer.write(content+"\n");
writer.flush();
} catch (IOException e) {
System.out.println("Error while writing to file");
}
}
}
//Original version generously taken from a Stack-Overflow forum post
class CPUMonitor {
private static final String AVAILABLE_PROCESSORS = "AvailableProcessors";
private static final String PROCESS_CPU_TIME = "ProcessCpuTime";
private int availableProcessors = 0;
private long lastSystemTime = 0;
private long lastProcessCpuTime = 0;
public void init(MBeanServerConnection mBeanServerConnection) throws Exception {
availableProcessors = (Integer) mBeanServerConnection.getAttribute(
new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME),AVAILABLE_PROCESSORS);
baselineCounters(mBeanServerConnection);
}
public synchronized double getCpuUsage(MBeanServerConnection mBeanServerConnection) throws Exception {
long systemTime = System.nanoTime();
long processCpuTime = 0;
if (ManagementFactory.getOperatingSystemMXBean() instanceof OperatingSystemMXBean) {
processCpuTime = (Long) mBeanServerConnection.getAttribute(
new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME),PROCESS_CPU_TIME );
}
double cpuUsage = (double) (processCpuTime - lastProcessCpuTime) / (systemTime - lastSystemTime);
lastSystemTime = systemTime;
lastProcessCpuTime = processCpuTime;
return cpuUsage / availableProcessors;
}
private void baselineCounters(MBeanServerConnection mBeanServerConnection) throws Exception {
lastSystemTime = System.nanoTime();
if (ManagementFactory.getOperatingSystemMXBean() instanceof OperatingSystemMXBean) {
lastProcessCpuTime = (Long) mBeanServerConnection.getAttribute(
new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME), PROCESS_CPU_TIME);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment