JmxMon.java 15.8 KB
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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
package se.lil.jm;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.management.InstanceNotFoundException;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;

public class JmxMon {
	String conUser = "system";
	String conPass = "passw0rd";
	String domainName = null;
	String serverName = null;
	String runtimeName = null;
	
	int gcType = 0;
	public static final int Unknown = 0;
	public static final int CMS = 1;
	public static final int PS = 2;
	
	public boolean isGCType(int type) {
		return (gcType == type);
	}
	
	private void setGCType(int type) {
		gcType = type;
	}
	
	JMXServiceURL url = null;
	JMXConnector jmxc = null;
	MBeanServerConnection mbsc = null;
	
	Thread myThread = null;
	ClassLoader myCL = null;
	
	int getDataCalls = 0;
	int getDataSucess = 0;
	
	HashMap<String, LongDelta> longDeltaMap = new HashMap<String, LongDelta>();
	HashMap<String, DoubleDelta> doubleDeltaMap = new HashMap<String, DoubleDelta>();
	
	HashSet<String> blocked = new HashSet<String>();
	
	public void dumpDeltas() {
		System.out.println("\nLong Deltas:");
		for(String key : longDeltaMap.keySet()) {
			System.out.println("\"" + key + "\" " + longDeltaMap.get(key).getCurrentValue());
		}
		System.out.println("\nDouble Deltas:");
		for(String key : doubleDeltaMap.keySet()) {
			System.out.println("\"" + key + "\" " + doubleDeltaMap.get(key).getCurrentValue());
		}
	}
	
	private void updateLongDelta (Long timestamp, String name, Long value) {
		LongDelta ld = longDeltaMap.get(name);
		if(ld == null) {
			ld = new LongDelta();
			longDeltaMap.put(name, ld);	
		}
		ld.update(timestamp, value);
	}
	
	private LongDelta getAttributeLongDelta(String name, String attribute) {
		return longDeltaMap.get(name + ":" + attribute);
	}
	
	public LongDelta getLongDelta(String key) {
		return longDeltaMap.get(key);
	}
	
	private void updateDoubleDelta (Long timestamp, String name, Double value) {
		DoubleDelta dd = doubleDeltaMap.get(name);
		if(dd == null) {
			dd = new DoubleDelta();
			doubleDeltaMap.put(name, dd);
		}
		dd.update(timestamp, value);
	}
	
	private DoubleDelta getAttributeDoubleDelta(String name, String attribute) {
		return doubleDeltaMap.get(name + ":" + attribute);
	}
	
	public DoubleDelta getDoubleDelta(String key) {
		return doubleDeltaMap.get(key);
	}
	
	private Object getAttributeValue(String name, String attribute) {
		Object ro = null;
		if(mbsc != null) {
			try {
				if(!blocked.contains(name))	ro = mbsc.getAttribute(new ObjectName(name), attribute);
			} catch (InstanceNotFoundException ie) {
				blocked.add(name);
			} catch (Exception e) {
			}
		}
		return ro;
	}
	
	String lastKeyName = "";
	
	private void updateCompositeDelta (Long timestamp, String name, CompositeData data) {
		for(String key : data.getCompositeType().keySet()) {
			String fullName;
			if(key.equals("value")) fullName = name + ":" + lastKeyName;
			else fullName = name + ":" + key;
			Object obj = data.get(key);
			updateDelta(timestamp, fullName, obj);
		}
	}
	
	private void updateTabularDelta (Long timestamp, String name, TabularData data) {
		for(Object obj : data.values()) {
			CompositeData cd = (CompositeData)obj;
			updateCompositeDelta(timestamp, name, cd);
		}
	}
	
	private void updateDelta(Long timestamp, String fullName, Object data) {
		if(data != null) {
			if(data.getClass().equals(java.lang.String.class)) {
				lastKeyName = (String)data;
			} else
			if(data.getClass().equals(java.lang.Long.class)) {
				updateLongDelta(timestamp, fullName, (Long)data);
			} else
			if(data.getClass().equals(java.lang.Integer.class)) {
				Integer i = (Integer)data;
				updateLongDelta(timestamp, fullName, i.longValue());
			} else
			if(data.getClass().equals(java.lang.Double.class)) {
				updateDoubleDelta(timestamp, fullName, (Double)data);
			} else
			if(data.getClass().equals(java.lang.Float.class)) {
				Float f = (Float)data;
				updateDoubleDelta(timestamp, fullName, f.doubleValue());
			} else
			if(data.getClass().equals(javax.management.openmbean.CompositeDataSupport.class)) {
				updateCompositeDelta(timestamp, fullName, (CompositeData)data);
			} else
			if(data.getClass().equals(javax.management.openmbean.TabularDataSupport.class)) {
				updateTabularDelta(timestamp, fullName, (TabularData)data);
			} else {
				System.out.println("Received Unknown Object: " + data.getClass());
			}
		}
	}
	
	private void fetchUpdateAttribute(String name, String attribute) {
		String fullName = name + ":" + attribute;
		Object obj = getAttributeValue(name, attribute);
		if(obj != null) {
			Long ts = (Long)getAttributeValue("java.lang:type=Runtime", "Uptime");
			updateDelta(ts, fullName, obj);
		}
	}
	
	public int getDataCalled() {
		return getDataCalls;
	}
	
	public int getDataSucceeded() {
		return getDataSucess;
	}
	
	public int getDataFailed() {
		return getDataCalls - getDataSucess;
	}
	
	public String getConString() {
		if(this.url != null) return this.url.toString();
		else return null;
	}
	
	public String getServerName() {
		return serverName;
	}
	
	public String getDomainName() {
		return domainName;
	}
	
	public String getRuntimeName() {
		return runtimeName;
	}
	
	public void open() throws IOException {
		if(url != null) {
			jmxc = JMXConnectorFactory.connect(url);
			mbsc = jmxc.getMBeanServerConnection();
			domainName = mbsc.getDefaultDomain();
			Object obj = getAttributeValue("java.lang:type=Runtime", "Name");
			if(obj.getClass().equals(java.lang.String.class)) {
				runtimeName = (String)obj;
			}
			obj = getAttributeValue("java.lang:type=Runtime", "SystemProperties");
			TabularData td = (TabularData)obj;
			for (Object o : td.values()) {
				CompositeData d = (CompositeData)o;
				if(d.get("key").toString().equals("weblogic.Name")) serverName = d.get("value").toString();
			}
		}
	}
	
	public void open(String serviceURL) throws IOException, MalformedURLException {
		url = new JMXServiceURL(serviceURL);
		open();
	}
	
	public void close() throws IOException {
		if(jmxc != null) jmxc.close();
		jmxc = null;
		mbsc = null;
	}
	
	long lastRTns = 0;
	public long getLastRTms() {
		return lastRTns / (1000 * 1000);
	}
	
	long lastFetchTSns = 0;
	public boolean getData(long ageTs) throws Throwable {
		if (getAgeTs() > ageTs ) return getData();
		else return false;
	}
	
	public long getAgeTs() {
		if(lastFetchTSns > 0) return (System.nanoTime() - lastFetchTSns)/(1000*1000*1000);
		else return 0;
	}
	
	Lock lock = new ReentrantLock();
	
	public boolean getData() throws Throwable {
		// Start thread safe
 		// Try to get a lock
 		boolean haveLock = lock.tryLock();
		if( haveLock == false) {
			// We could not get the lock, someone else is updating. Wait for it to complete by waiting for a lock, then unlock and return.
			try {
				lock.lock();
			} finally {
				lock.unlock();
			}
			return false;
		}
		// We do have the lock. Do the rest in a try catch everything and if we catch anything, re throw the catch but always release the lock.
		try {
			long startTSns = System.nanoTime();
	 		getDataCalls++;
	 		// Do the update of data
	 		numCpus = (Integer)getAttributeValue("java.lang:type=OperatingSystem", "AvailableProcessors");
	 		fetchUpdateAttribute("java.lang:type=OperatingSystem", "ProcessCpuTime");
	 		fetchUpdateAttribute("java.lang:type=OperatingSystem", "OpenFileDescriptorCount");
	 		fetchUpdateAttribute("java.lang:type=OperatingSystem", "MaxFileDescriptorCount");
	 		fetchUpdateAttribute("java.lang:type=OperatingSystem", "TotalSwapSpaceSize");
	 		fetchUpdateAttribute("java.lang:type=OperatingSystem", "FreeSwapSpaceSize");
	 		fetchUpdateAttribute("java.lang:type=OperatingSystem", "FreePhysicalMemorySize");
	 		fetchUpdateAttribute("java.lang:type=OperatingSystem", "TotalPhysicalMemorySize");
	 		fetchUpdateAttribute("java.lang:type=OperatingSystem", "SystemLoadAverage");
	 		fetchUpdateAttribute("java.lang:type=Threading", "ThreadCount");
	 		fetchUpdateAttribute("java.lang:type=ClassLoading", "LoadedClassCount");
	 		fetchUpdateAttribute("java.lang:type=Memory", "HeapMemoryUsage");
	 		
	 		// Only get theese if we have the right GC type
	 		if(isGCType(JmxMon.Unknown) || isGCType(JmxMon.PS)) {
		 		fetchUpdateAttribute("java.lang:type=GarbageCollector,name=PS MarkSweep", "LastGcInfo");
		 		fetchUpdateAttribute("java.lang:type=GarbageCollector,name=PS MarkSweep", "CollectionTime");
		 		fetchUpdateAttribute("java.lang:type=GarbageCollector,name=PS Scavenge", "CollectionTime");
		 		fetchUpdateAttribute("java.lang:type=MemoryPool,name=PS Old Gen", "Usage");
	 		}
	 		if(isGCType(JmxMon.Unknown) || isGCType(JmxMon.CMS)) {
		 		fetchUpdateAttribute("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep", "LastGcInfo");
		 		fetchUpdateAttribute("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep", "CollectionTime");
		 		fetchUpdateAttribute("java.lang:type=GarbageCollector,name=ParNew", "CollectionTime");
		 		fetchUpdateAttribute("java.lang:type=MemoryPool,name=CMS Old Gen", "Usage");
	 		}
	 		// Finished updating data
	 		getDataSucess++;
			lastFetchTSns = System.nanoTime();
			lastRTns = lastFetchTSns - startTSns;
			
			// Check the GC type if not known
			if(isGCType(JmxMon.Unknown)) {
				if(longDeltaMap.containsKey("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep:CollectionTime")) setGCType(JmxMon.CMS);
				if(longDeltaMap.containsKey("java.lang:type=GarbageCollector,name=PS MarkSweep:CollectionTime")) setGCType(JmxMon.PS);
			}
			return true;
		} catch (Throwable e) {
			throw (e);
		} finally {
			lock.unlock();
		}
		// End thread safe
	}
	
	//NUM_CPUS
	int numCpus = 0;
	public long getNumberOfCPUs() {
		return numCpus;
	}
	
	public long getLoadedClassCount() {
		LongDelta ld = getAttributeLongDelta("java.lang:type=ClassLoading", "LoadedClassCount");
		return ld.getCurrentValue();
	}
	
	public double getCPUPercent() {
		LongDelta ld = getAttributeLongDelta("java.lang:type=OperatingSystem", "ProcessCpuTime");
		double cpuDeltaMS = (double)ld.getDelta() / (1000D*1000D);
		double spentMS = ld.getMilliSeconds();
		double perCPUMS = cpuDeltaMS / (double)numCpus;
		double cpuPct = (perCPUMS / spentMS) * 100D;
		return cpuPct;
	}
	
	public double getAverageLoad() {
		DoubleDelta dd = getAttributeDoubleDelta("java.lang:type=OperatingSystem", "SystemLoadAverage");
		return dd.getCurrentValue();
	}
	
	public double getAverageLoadPerCpu() {
		DoubleDelta dd = getAttributeDoubleDelta("java.lang:type=OperatingSystem", "SystemLoadAverage");
		return dd.getCurrentValue()/(double)numCpus;
	}
	
	public long getThreads() {
		LongDelta ld = getAttributeLongDelta("java.lang:type=Threading", "ThreadCount");
		return ld.getCurrentValue();
	}
	
	public double getSystemMemoryPercentUsed() {
		LongDelta ldf = getAttributeLongDelta("java.lang:type=OperatingSystem", "FreePhysicalMemorySize");
		LongDelta ldt = getAttributeLongDelta("java.lang:type=OperatingSystem", "TotalPhysicalMemorySize");
		double free = ldf.getCurrentValue();
		double total = ldt.getCurrentValue();
		return ((total - free)/(total)) * 100D;
	}
	
	public double getSystemSwapPercentUsed() {
		LongDelta ldf = getAttributeLongDelta("java.lang:type=OperatingSystem", "FreeSwapSpaceSize");
		LongDelta ldt = getAttributeLongDelta("java.lang:type=OperatingSystem", "TotalSwapSpaceSize");
		double free = ldf.getCurrentValue();
		double total = ldt.getCurrentValue();
		return ((total - free)/(total)) * 100D;
	}
	
	public double getSystemFileDescriptorsPercentUsed() {
		LongDelta ldo = getAttributeLongDelta("java.lang:type=OperatingSystem", "OpenFileDescriptorCount");
		LongDelta ldm = getAttributeLongDelta("java.lang:type=OperatingSystem", "MaxFileDescriptorCount");
		double open = ldo.getCurrentValue();
		double max = ldm.getCurrentValue();
		return (open/max) * 100D;
	}
	
	public double getHeapUsedMB() {
		LongDelta ld = getLongDelta("java.lang:type=Memory:HeapMemoryUsage:used");
		if(ld != null) {
			return (double)ld.getCurrentValue() / (1024D*1024D);
		} else {
			return 0;
		}
	}
	
	public double getHeapCommittedMB() {
		LongDelta ld = getLongDelta("java.lang:type=Memory:HeapMemoryUsage:committed");
		if(ld != null) {
			return (double)ld.getCurrentValue() / (1024D*1024D);
		} else {
			return 0;
		}
	}
	
	public double getHeapUsedPercent() {
		LongDelta ldu = getLongDelta("java.lang:type=Memory:HeapMemoryUsage:used");
		LongDelta ldm = getLongDelta("java.lang:type=Memory:HeapMemoryUsage:max");
		if(ldu != null && ldm != null) {
			return ((double)ldu.getCurrentValue()/(double)ldm.getCurrentValue()) * 100D;
		} else {
			return 0;
		}
	}
	
	public double getGCOverhead() {
		LongDelta ld1 = null;
		LongDelta ld2 = null;
		if(isGCType(JmxMon.PS)) {
			ld1 = getLongDelta("java.lang:type=GarbageCollector,name=PS MarkSweep:CollectionTime");
			ld2 = getLongDelta("java.lang:type=GarbageCollector,name=PS Scavenge:CollectionTime");
		}
		if(isGCType(JmxMon.CMS)) {
			ld1 = getLongDelta("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep:CollectionTime");
			ld2 = getLongDelta("java.lang:type=GarbageCollector,name=ParNew:CollectionTime");
		}
		if(ld1 != null && ld2 != null) {
			return (ld1.getPerSecondValue() + ld2.getPerSecondValue())/10D;
		} else {
			return 0;
		}
	}
	
	public double getOldGenUsedMB() {
		LongDelta ld = null;
		if(isGCType(JmxMon.PS))
			ld = getLongDelta("java.lang:type=MemoryPool,name=PS Old Gen:Usage:used");
		if(isGCType(JmxMon.CMS))
			ld = getLongDelta("java.lang:type=MemoryPool,name=CMS Old Gen:Usage:used");
		if(ld != null) {
			return (double)ld.getCurrentValue() / (1024D*1024D);
		} else {
			return 0;
		}
	}
	
	public double getOldGenUsedPercent() {
		LongDelta ldu = null;
		LongDelta ldm = null;
		
		if(isGCType(JmxMon.PS)) {
			ldu = getLongDelta("java.lang:type=MemoryPool,name=PS Old Gen:Usage:used");
			ldm = getLongDelta("java.lang:type=MemoryPool,name=PS Old Gen:Usage:max");
		}
		if(isGCType(JmxMon.CMS)) {
			ldu = getLongDelta("java.lang:type=MemoryPool,name=CMS Old Gen:Usage:used");
			ldm = getLongDelta("java.lang:type=MemoryPool,name=CMS Old Gen:Usage:max");
		}
		if(ldu != null && ldm != null) {
			return ((double)ldu.getCurrentValue()/(double)ldm.getCurrentValue()) * 100D;
		} else {
			return 0;
		}
	}
	
	public double getOldGenAfterGCMB() {
		LongDelta ld = null;
		if(isGCType(JmxMon.PS))
			ld = getLongDelta("java.lang:type=GarbageCollector,name=PS MarkSweep:LastGcInfo:memoryUsageAfterGc:PS Old Gen:used");
		if(isGCType(JmxMon.CMS))
			ld = getLongDelta("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep:LastGcInfo:memoryUsageAfterGc:CMS Old Gen:used");
		if(ld != null) {
			return (double)ld.getCurrentValue() / (1024D*1024D);
		} else {
			return 0;
		}
	}
	
	public double getPermGenAfterGCMB() {
		LongDelta ld = null;
		if(isGCType(JmxMon.PS))
			ld = getLongDelta("java.lang:type=GarbageCollector,name=PS MarkSweep:LastGcInfo:memoryUsageAfterGc:PS Perm Gen:used");
		if(isGCType(JmxMon.CMS))
			ld = getLongDelta("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep:LastGcInfo:memoryUsageAfterGc:CMS Perm Gen:used");
		if(ld != null) {
			return (double)ld.getCurrentValue() / (1024D*1024D);
		} else {
			return 0;
		}
	}
	
	public JmxMon() {
	}
	
	public JmxMon(String serviceURL) throws MalformedURLException {
		this.url = new JMXServiceURL(serviceURL);
	}
}