CollResinWithJMX.java 12.5 KB
package com.sitech.ismp.coll.centercoll;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.log4j.Logger;

import com.sitech.ismp.coll.CollBase;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;

public class CollResinWithJMX extends CollBase {

	private final String PRE_UNITID = "10-12-14"; // Resin的标识
	private final String PRE_UNITID_PM = PRE_UNITID+"-11"; // 性能指标
	private final String PRE_UNITID_CM = PRE_UNITID+"-10"; // 配置指标
	private final String PRE_UNITID_FM = PRE_UNITID+"-12"; // 状态指标
	
	private final static String COLL_IP = "COLL_IP"; 
	private final static String JMX_PORT = "JMX_PORT"; 
	private final static String HTTP_PORT = "HTTP_PORT"; 
	
	String hostName = "";
	MBeanServerConnection  mbsc = null;
	JMXConnector connector = null;
	public void init(HashMap params) {
		
		String collIp = (String) params.get(COLL_IP);
		String jmxPort = (String) params.get(JMX_PORT);
		
        String jmxURL = "service:jmx:rmi:///jndi/rmi://"+collIp+":"+jmxPort+"/jmxrmi";//tomcat jmx url   
        try{
        	
    		//System.out.println("connect jmx sevice");
        	System.out.println("jmxURL="+jmxURL);
        	JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);   
	        Map map = new HashMap();
	        String[] credentials = new String[] { "monitorRole" , "QED" };   
	        map.put("jmx.remote.credentials", credentials);   
	        connector = JMXConnectorFactory.connect(serviceURL, map);   
	        mbsc = connector.getMBeanServerConnection();
	        // 获取主机名称
	        ObjectName runtimeObjName = new ObjectName("java.lang:type=Runtime");   
	        hostName = (String)mbsc.getAttribute(runtimeObjName, "Name");
	        int pos = hostName.indexOf("@", 0);
	        hostName = hostName.substring(pos+1, hostName.length());

        } catch (Exception e) {   
        	logger.error(e);  
        	e.printStackTrace();
        }  
	}
	/**
	 * 采集内存使用指标
	 * @param params
	 * @return
	 */
	
	public Vector getMemory(HashMap params) {
		logger.info("begin getMemory");
		// 保存采集结果,并返回值
		CollBase collResult = new CollBase();
		try {
			init(params);
			ObjectName heapObjName = new ObjectName("java.lang:type=Memory");   
			CompositeDataSupport heapMemoryUsage =  (CompositeDataSupport)mbsc.getAttribute(heapObjName, "HeapMemoryUsage");   
			long maxMemory = ((Long)heapMemoryUsage.get("max")).longValue()/(1024*1024);//堆最大   
			long commitMemory = ((Long)heapMemoryUsage.get("committed")).longValue()/(1024*1024);//堆当前分配   
			long usedMemory = ((Long)heapMemoryUsage.get("used")).longValue()/(1024*1024); //当前使用的
			double heapUsage = (double)usedMemory*100/commitMemory;//堆使用率   
			    
			/*
			MemoryUsage nonheapMemoryUsage =  MemoryUsage.from((CompositeDataSupport)mbsc.getAttribute(heapObjName, "NonHeapMemoryUsage"));              
			long noncommitMemory = nonheapMemoryUsage.getCommitted();   
			long nonusedMemory = heapMemoryUsage.getUsed();   
			System.out.println("nonheap:"+(double)nonusedMemory*100/noncommitMemory+"%");   
			*/      
			ObjectName permObjName = new ObjectName("java.lang:type=MemoryPool,name=Perm Gen");   
			CompositeDataSupport permGenUsage =  (CompositeDataSupport)mbsc.getAttribute(permObjName, "Usage");              
			long committed = ((Long)heapMemoryUsage.get("committed")).longValue()/(1024*1024);//持久堆大小   
			long used = ((Long)permGenUsage.get("used")).longValue()/(1024*1024);
			double permUsage = (double)used*100/committed;//持久堆使用率   
			

			//当前内存堆使用比率
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-memory",
					"PM-00-04-003-01", String.valueOf((int)heapUsage));
			//允许支配的内存堆
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-memory",
					"CM-00-04-003-02", String.valueOf(maxMemory));
			
			//当前使用的内存堆
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-memory",
					"PM-00-04-004-01", String.valueOf(usedMemory));
			//持久内存堆大小
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-memory",
					"PM-00-04-004-02", String.valueOf(committed));
			//当前使用的持久内存堆大小
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-memory",
					"PM-00-04-004-03", String.valueOf(used));
			//内存持久堆使用率
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-memory",
					"PM-00-04-004-04", String.valueOf(permUsage));

		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
				connector.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return collResult.getKPISet();
	}	
	/**
	 * 采集会话指标
	 * @param params
	 * @return
	 */
	public Vector getSession(HashMap params) {
		logger.info("begin getSession");
		// 保存采集结果,并返回值
		CollBase collResult = new CollBase();
		try {
			init(params);
			String httPort = (String) params.get(HTTP_PORT);
			
			ObjectName threadpoolObjName = new ObjectName("resin:type=Port,name="+httPort); 
			//请求总数
//			String reqCountTotal = mbsc.getAttribute( threadpoolObjName, "RequestCountTotal").toString();  
			//最大连接数
			String idleThreads = mbsc.getAttribute( threadpoolObjName, "ConnectionMax").toString();   
			//请求时间总数
			String reqTimeTotal = mbsc.getAttribute( threadpoolObjName, "RequestTimeTotal").toString();
			//保持活动总数
			String minSpareThreads = mbsc.getAttribute( threadpoolObjName, "KeepaliveCountTotal").toString();
			//保持最大数
			String maxThreads = mbsc.getAttribute( threadpoolObjName, "KeepaliveMax").toString();  
		 
			//请求总数
//			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-session",
//					"PM-00-04-004-10", reqCountTotal);
			//最大连接数
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-11", idleThreads);
			//请求时间总数
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-12", reqTimeTotal);
			//保持活动总数
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-13", minSpareThreads);
			//保持最大数
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-14", maxThreads);

		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
				connector.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return collResult.getKPISet();
	}	
	/**
	 * 采集运行指标
	 * @param params
	 * @return
	 */
	public Vector getRuntime(HashMap params) {
		logger.info("begin getRuntime");
		// 保存采集结果,并返回值
		CollBase collResult = new CollBase();
		try {
			init(params);
			ObjectName runtimeObjName = new ObjectName("java.lang:type=Runtime");   
			
			//System.out.println("厂商:"+ (String)mbsc.getAttribute(runtimeObjName, "VmVendor"));   
			//System.out.println("程序:"+ (String)mbsc.getAttribute(runtimeObjName, "VmName"));   
			//System.out.println("版本:"+ (String)mbsc.getAttribute(runtimeObjName, "VmVersion"));

			Date runTime= new Date(((Long)mbsc.getAttribute(runtimeObjName, "StartTime")).longValue());   
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
			
			
			//启动时间
			String startTime = df.format(runTime);
			//连续工作时间
			Long timespan=(Long)mbsc.getAttribute(runtimeObjName, "Uptime");   
			String upTime =formatTimeSpan(timespan.longValue());  
			
			collResult.addKPI(this.PRE_UNITID_FM + ":" + hostName + "-runtime","FM-00-04-004-01", startTime);//启动时间
			collResult.addKPI(this.PRE_UNITID_FM + ":" + hostName + "-runtime","FM-00-04-004-02", upTime);//连续工作时间

		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
				connector.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return collResult.getKPISet();
	}	
	public Vector getThreadPool(HashMap params) {
		logger.info("begin getThreadPool");
		// 保存采集结果,并返回值
		CollBase collResult = new CollBase();
		try {
			init(params);
			ObjectName threadpoolObjName = new ObjectName("resin:type=ThreadPool"); 
			//活动线程数
			String activeThreads = mbsc.getAttribute( threadpoolObjName, "ThreadActiveCount").toString();  
			//空闲线程数
			String idleThreads =mbsc.getAttribute( threadpoolObjName, "ThreadIdleCount").toString();   
			//线程数
			String threads = mbsc.getAttribute( threadpoolObjName, "ThreadCount").toString();
			//最小空闲线程数
			String minSpareThreads = mbsc.getAttribute( threadpoolObjName, "SpareThreadMin").toString();
			//最大线程数
			String maxThreads = mbsc.getAttribute( threadpoolObjName, "ThreadMax").toString();  
		 
			//活动线程数
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-15", activeThreads);
			//空闲线程数
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-16", idleThreads);
			//线程数
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-17", threads);
			//最小空闲线程数
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-08", minSpareThreads);
			//最大线程数
			collResult.addKPI(this.PRE_UNITID_PM + ":" + hostName + "-thread",
					"PM-00-04-004-05", maxThreads);


		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
				connector.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return collResult.getKPISet();
	}	
	public static String formatTimeSpan(long ms){

		int ss = 1000;
		int mi = ss * 60;
		int hh = mi * 60;
		int dd = hh * 24;
		
		long day = ms / dd;
		long hour = (ms - day * dd) / hh;
		long minute = (ms - day * dd - hour * hh) / mi;
		long second = (ms - day * dd - hour * hh - minute * mi) / ss;
		long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
		
		String strDay = day < 10 ? "" + day : "" + day;
		String strHour = hour < 10 ? "0" + hour : "" + hour;
		String strMinute = minute < 10 ? "0" + minute : "" + minute;
		String strSecond = second < 10 ? "0" + second : "" + second;
		String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;
		strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;
		return strDay + "天" + strHour + ":" + strMinute + ":" + strSecond + " " + strMilliSecond;
	}
    /**  
     * @param args  
     */  
    public static void main(String[] args) {   
        try {   
        	
    		HashMap params = new HashMap();
    		//params.put(COLL_IP, "172.20.203.203");
    		//params.put(COLL_IP, "192.168.6.250");
    		params.put(COLL_IP, "192.168.6.250");
    		//params.put(COLL_IP, "192.168.3.254");
    		
    		params.put(JMX_PORT, "9999");
    		params.put(HTTP_PORT, "6666");
    		System.out.println("begin................");
    		CollResinWithJMX coll = new CollResinWithJMX();
    		Vector lst = coll.getMemory(params);
    		
    		
    		
    		
    		System.out.println("lst.size() is " + lst.size());
    		for (int i = 0; i < lst.size(); i++) {
    			TblATO_KPIDETAIL kpidetail = (TblATO_KPIDETAIL) lst.get(i);
    			System.out.println(kpidetail.UNIT_ID + "|" + kpidetail.KPI_ID + "|"
    					+ kpidetail.CLL_TIME + "|" + kpidetail.KPI_VALUE);
    		}     
    		 lst = coll.getSession(params);
    		 for (int i = 0; i < lst.size(); i++) {
     			TblATO_KPIDETAIL kpidetail = (TblATO_KPIDETAIL) lst.get(i);
     			System.out.println(kpidetail.UNIT_ID + "|" + kpidetail.KPI_ID + "|"
     					+ kpidetail.CLL_TIME + "|" + kpidetail.KPI_VALUE);
     		}     
    		 lst = coll.getThreadPool(params);
    		 for (int i = 0; i < lst.size(); i++) {
     			TblATO_KPIDETAIL kpidetail = (TblATO_KPIDETAIL) lst.get(i);
     			System.out.println(kpidetail.UNIT_ID + "|" + kpidetail.KPI_ID + "|"
     					+ kpidetail.CLL_TIME + "|" + kpidetail.KPI_VALUE);
     		}     
    		 lst = coll.getRuntime(params);
    		 for (int i = 0; i < lst.size(); i++) {
     			TblATO_KPIDETAIL kpidetail = (TblATO_KPIDETAIL) lst.get(i);
     			System.out.println(kpidetail.UNIT_ID + "|" + kpidetail.KPI_ID + "|"
     					+ kpidetail.CLL_TIME + "|" + kpidetail.KPI_VALUE);
     		}     
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
}