ACommonThread.java 2.58 KB
package com.sitech.base;

import java.io.File;
import java.util.Date;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

import org.apache.log4j.Logger;

import com.sitech.ismp.messageObject.HeartbeatObject;
import com.sitech.util.Formater;
import com.sitech.util.mq.MQConstants;
import com.sitech.util.mq.TunnelFactory;


public abstract class ACommonThread extends Thread {
	private Logger heartbeat = Logger.getLogger("HEARTBEAT");
	
	static final int UP = 1;
	static final int DOWN = 2;
	static final int UNKNOWN = 3;
	
	private String moduleId;

	private String processName;

	public ACommonThread(String moduleId, String processName) {
		this.moduleId = moduleId;
		this.processName = processName;
	}

	protected boolean isRun = true;
	
	private Date startTime;

	@Override
	public void run() {
		startTime = new Date();
		process();
	}

	protected void doHeartBeat() {
		heartbeat.info("Do heartbeat.");

		HeartbeatObject heartbeat = new HeartbeatObject();
		heartbeat.setModuleId(this.moduleId);
		heartbeat.setProcessName(this.processName);
		heartbeat.setProcessStartTime(startTime);
		heartbeat.setReportTime(new Date());
		heartbeat.setProcessStatus(UP);
		heartbeat.setProcessCpu(getCpuUsage());
		heartbeat.setProcessMem(getTotalMemory());
		heartbeat.setProcessErrInfo("-");
		heartbeat.setVersion(getVersion());

		TunnelFactory.getTunnel(MQConstants.Q_ROPORT_FROM_AGENT).writeData(heartbeat);
	}

	/**
	 * 1分钟内平均CPU利用率
	 * @return
	 */
	private String getCpuUsage() {
		return "-";
	}

	/**
	 * @return JVM内存大小,单位k
	 */
	private String getTotalMemory() {
		long totalMemory = Runtime.getRuntime().totalMemory();
		
		return Formater.formatDecimalKpivalue(String.valueOf(totalMemory / 1024L));
	}


	protected abstract void process();
	
	protected String getVersion() {
		String version = "-";
		try{
			File file = new File(AgentProperties.AGENT_HOME + "/libs/agent.jar");
			JarFile jarFile = new JarFile(file);

			Manifest manifest = jarFile.getManifest();			
			Attributes att = manifest.getMainAttributes();
			
			String specVersion = att.getValue("Specification-Version");
			String buildVersion = att.getValue("Implementation-Version");
			
			version = "V" + specVersion + "_B" + buildVersion;

		} catch (Exception e) {
			heartbeat.error("Exception while getAgentVersion", e);
		}
		return version;
	}

	public boolean isRun() {
		return isRun;
	}

	public void setRun(boolean isRun) {
		this.isRun = isRun;
	}

	public String getModuleId() {
		return moduleId;
	}

	public void setModuleId(String moduleId) {
		this.moduleId = moduleId;
	}
}