ProcessCollThread.java 4.76 KB
package com.sitech.ismp.coll.busi;

import java.io.File;
import java.util.HashMap;

import com.sitech.base.AgentProperties;
import com.sitech.util.FileUtils;
import com.sitech.util.RandomGUID;
import org.apache.log4j.Logger;

import com.sitech.ismp.coll.busi.util.FilesOperation;
import com.sitech.ismp.coll.busi.util.SystemUtil;
import com.sitech.util.Formater;

/**
 * ClassName:ProcessCollThread
 * Description: 进程采集(封装为SHELL采集)
 *
 * @author   Linxc
 * @version  
 * @since    Ver 1.1
 * @Date	 2012	Feb 20, 2012		6:01:35 PM
 */
public class ProcessCollThread implements Runnable {
	private static Logger logger = Logger.getLogger("BUSI_COLL");
	
	// 采集周期
	private String interval;
	// 业务类型
	private String kbpClass;
	
	// 根据用户名过滤
	private String userName;
	private String processKey;
	private String[] filterKey;
	
	public ProcessCollThread(HashMap<String, String> params) {
		interval = params.get("COLL_INTERVAL");
		kbpClass = params.get("KBP_CLASS");
		userName = params.get("USER_NAME");
		// 进程关键字
		processKey = params.get("PROCESS_KEY");
		// 过滤关键字(多个用逗号隔开)
		if(params.get("REMOVE_KEY") != null){
			filterKey = params.get("REMOVE_KEY").split(",");
		}
	}

	public void run() {
		if (processKey == null || processKey.length() == 0) {
			return;
		}
		String shellName = userName + "_" + Formater.neatenunitid(processKey) + "_p.sh";

		if (shellName.length() >= 127) {
			// 防止文件名长度过长
			shellName = shellName.substring(shellName.length() - 128, shellName.length());
		}
		
		// SHELL内容
		String shellContent = getShellContent();
		
		logger.info("\n" + shellName);
		logger.info("\n" + shellContent);
		
		// 2. SHELL脚本文件不存在,则创建脚本
		File file = new File(SystemUtil.SHELL_SCRIPT_PATH + shellName);
		if (!file.exists()) {
			logger.info("File[" + shellName + "] not exists, create..");
			createScriptFile(SystemUtil.SHELL_SCRIPT_PATH + shellName, shellContent);
		}
		
		// 3. 通知执行脚本	
		exec(shellName);	
	}
	
	/**
	 * 变量替换得到最终执行的shell
	 * @throws 
	 * @since Ver 1.1
	 */
	private String getShellContent() {
		String unitId = kbpClass + ":" + Formater.neatenunitid(processKey)  ;		
		String psCommand = "ps -ef ";
		
		if (userName != null && !userName.equals("")) {
			unitId = kbpClass + ":" + userName + "-" + Formater.neatenunitid(processKey);
			psCommand += "| grep '" + userName + "' ";
		}else{
			unitId = kbpClass + ":" + Formater.neatenunitid(processKey);
		}
		
		psCommand += "| grep '"+processKey+"' ";
		
		if (filterKey != null && filterKey.length > 0) {
			for(int i=0; i<filterKey.length; i++){
				psCommand += "| grep -v '" + filterKey[i] +"' ";
			}
		}
		
		psCommand += "| grep -v 'PPID' | grep -v '_p.sh' | grep -v grep | wc -l";
		
		String shellContent = "processCount=`" + psCommand + "`\n";
		// 进程名称 
		shellContent += SystemUtil.WRITE_SWAP + " " + unitId + " CM-01-14-008-01 " + processKey + " " + interval + "\n" ;
		// 进程个数
		shellContent += SystemUtil.WRITE_SWAP + " " + unitId + " PM-01-14-008-02 ${processCount} " + interval + "\n" ;
		
		return shellContent;
	}
	
	/**
	 * 创建脚本文件
	 * @throws 
	 * @since Ver 1.1
	 */
	private void createScriptFile(String shellName, String shellContent) {
		try {
			// 创建脚本文件
			File file = FilesOperation.createFiles(shellName, shellContent);
			// JVM退出时删除文件
			file.deleteOnExit();
		} catch (Exception e) {
			logger.error("Exception while createShellScript()", e);
		}		
	}

	/**
	 * 通知执行脚本
	 * 通知方式:写一个文件(文件名为采集脚本名称,如:getCpu.sh、getMem.sh)到notice目录,
	 * contab会定时执行脚本扫描该目录,得到文件名,并执行脚本
	 * 
	 * @throws
	 * @since Ver 1.1
	 */
	private void exec(String shellName){	
//		String noticeFileName = "../notice/busi/" + shellName;
//		try {
//			FilesOperation.createFiles(noticeFileName, noticeFileName);
//		} catch (Exception e) {
//			logger.error("Exception while exec("+noticeFileName+")", e);
//		}
        try {
            String noticeContent = getShellContent();

            String fileName = "notice_" + RandomGUID.getRandomGUID() + ".sh";

            logger.info("[" + shellName  + "]  Create TmpNoticeFile[" + fileName + "]");
            FileUtils.writeFile(AgentProperties.AGENT_HOME + "/script/busi/busi_tmp/", fileName, noticeContent, false);

            logger.info("[" + shellName  + "]  Create NoticeFile[" + AgentProperties.AGENT_HOME + "/notice/" + userName + "/" + fileName + "][" + shellName);
            FileUtils.createNewFile(AgentProperties.AGENT_HOME + "/notice/bnms/", fileName);
        } catch (Exception e) {
            logger.info("[" + shellName  + "]  Exception While Create NoticeFile", e);
        }
	}
}