CollFileWithCMD.java 14.4 KB
package com.sitech.ismp.coll.centercoll;

import com.sitech.ismp.coll.CollBase;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.util.DES3;
import com.sitech.util.Formater;
import com.sitech.util.upload.SSHThread;
import com.sitech.util.upload.TelnetThread;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author liush_bj 日期:2014-10-08
 * 		      主机文件采集
 */
public class CollFileWithCMD extends CollBase {

    String ipAddr;

    String deviceName;

    String deviceId;

    public Vector<TblATO_KPIDETAIL> getFileChange(HashMap<String, String> params) {
        logger.info("Begin getFileChange...");
        logger.info(params.toString());
        CollBase collResult = new CollBase();
        String UNIT_ID = params.get("KBP_CLASS");
        init(params);
        //kctune 系统参数变动监控
        try{
            logger.info("-------coll------kctune--------");
            // 获得结果
            Vector<String> netlogV = tt.getResultAsVector("kctune");
            String host_name = deviceId;
            // 得到unit_id中使用的主机名称
            String neat_host_name = Formater.neatenunitid(host_name);
            //文件名称
            collResult.addKPI(UNIT_ID + "-20:" + neat_host_name+"-kctune", "CM-10-10-020-01", "kctune");
            Boolean isChange = checkFileChange(netlogV,"kctune",deviceId);
            //变动部分有结果,则生成告警指标
            collResult.addKPI(UNIT_ID + "-20:" + neat_host_name+"-kctune", "FM-10-10-020-01",isChange.toString());

            logger.info("-------coll------filepaths--------");
            //得到filechange UnitId
            String filechangeUnitId = UNIT_ID + "-20:" +  deviceId + "-";
            String filePaths = params.get("FILE_PATHS");
            String[] filePathList = filePaths.split(",");
            // 获得结果
            for(String tempPath:filePathList) {

                Vector<String> fileResult = tt.getResultAsVector("ls -l " +tempPath);
                /**
                 * 分析传入的文件绝对路径参数
                 * 如果传入的参数中是路径则采集该路径下所有的文件
                 * 如果传入的参数中包含文件名则采集该文件
                 */
                if (fileResult.size() > 1) {//说明该tempPath为目录,记录当前目录下文件数(除去文件夹及文件夹下内容)。
                    Vector<String> dirResult = tt.getResultAsVector("ls -l " +tempPath+" |grep \"^-\"");
                    //文件数量
                    collResult.addKPI(filechangeUnitId + tempPath, "PM-01-09-021-01", dirResult.size()+"");
                }else {
                    collResult.addKPI(filechangeUnitId + tempPath, "PM-01-09-021-01", "0");
                }
                isChange = checkFileChange(fileResult, tempPath, deviceId);
                //文件名称
                collResult.addKPI(filechangeUnitId + tempPath, "CM-10-10-020-01", tempPath);
                //变动部分有结果,则生成告警指标
                collResult.addKPI(filechangeUnitId + tempPath, "FM-10-10-020-01", isChange.toString());

            }
        }catch (Exception e) {
            logger.error("Exception while get fileChange!",e);
        }finally {
            release();
        }
        logger.info("END COLL fileChange ");
        return collResult.getKPISet();
    }

    private Boolean checkFileChange(List result,String fileName,String deviceId){
        Boolean isChange = false;
        try{
            String now = this.getVetorString(result);
            String data_path = "../filechange";
            fileName = StringUtils.replace(fileName,"/","-");
            String now_filename = "now_" + deviceId + "-"+fileName+".dat";
            String tmp_filename = "tmp_" + deviceId + "-"+fileName+".dat";
            String diff_filename = "diff_" + deviceId + "-"+fileName+".dat";

            //目录不存在则创建
            File f = new File(data_path);
            if(!f.exists()){
                f.mkdir();
            }

            File now_file = new File(data_path+"/" + now_filename);// 最新日志信息
            File tmp_file = new File(data_path+"/" + tmp_filename);// 上次日志信息
            File diff_file = new File(data_path+"/" + diff_filename);// 增量日志
            PrintWriter write_now = new PrintWriter(new OutputStreamWriter(
                    new FileOutputStream(now_file), "GB2312"));
            PrintWriter write_tmp = new PrintWriter(new OutputStreamWriter(
                    new FileOutputStream(tmp_file, true), "GB2312"));
            PrintWriter write_diff = new PrintWriter(new OutputStreamWriter(
                    new FileOutputStream(diff_file), "GB2312"));
            String path = now_file.getAbsolutePath();
            logger.info("Current path is " + path);
            // 日志解析
            if (tmp_file.exists() && tmp_file.length() > 0) {// 非第一次采集
                write_now.write(now);
                write_now.flush();
                write_now.close();
                // 读取上次日志文件(tmp)
                FileReader tmp_reader = new FileReader(tmp_file);
                BufferedReader tmp = new BufferedReader(tmp_reader);
                String line;
                String tmp_file_string = "";
                while ((line = tmp.readLine()) != null) {
                    tmp_file_string += line + "\n";
                }
                tmp.close();
                tmp_reader.close();
                // 读取本次日志文件(now),生成差异文件(diff)
                FileReader now_reader = new FileReader(now_file);
                BufferedReader br = new BufferedReader(now_reader);
                while ((line = br.readLine()) != null) {
                    if (tmp_file_string.indexOf(line) == -1)
                        write_diff.write(line);
                    else
                        continue;
                }
                br.close();
                now_reader.close();
                write_diff.flush();
                write_diff.close();
                write_tmp = new PrintWriter(new OutputStreamWriter(
                        new FileOutputStream(tmp_file), "GB2312"));
                write_tmp.write(now);
                write_tmp.flush();
                write_tmp.close();

                // 生成指标
                FileReader diff_reader = new FileReader(diff_file);
                BufferedReader diff = new BufferedReader(diff_reader);
                //变动部分有结果,则生成告警指标
                if (diff.readLine() != null) {
                    isChange =true;
                }
                diff.close();
                diff_reader.close();
            } else {// 第一次采集
                write_tmp.write(now);
                write_tmp.flush();
                write_tmp.close();
                write_diff.write(now);
                write_diff.flush();
                write_diff.close();
            }
        }catch (Exception e) {
            logger.error("Exception while get fileChange!",e);
        }finally {

            return isChange;
        }
    }

    public Vector<TblATO_KPIDETAIL> getCatalog(HashMap<String, String> params) {
        logger.info("Begin getCatalog...");
        logger.info(params.toString());
        CollBase collResult = new CollBase();
        String UNIT_ID = params.get("KBP_CLASS");
        //建立连接
        init(params);
        try{
            int count=0;
            String[] catalogList =  params.get("CATALOG").split(",");
            //单目录采集 开始
            String catalog = catalogList[0];
            String size = new BigDecimal(catalogList[1]).toPlainString().toString();
            // ls -ltrd catalog | grep '^d' | grep -v '201[456789]' |sort -nrk5 | awk '$5>size {print $0}' |head -50
            StringBuffer cmdsb = new StringBuffer();
            //拼接采集语句
            cmdsb.append("ls -ltrd ").append(catalog).append(" | grep '^d' | grep -v '201[456789]' |sort -nrk5 | awk '$5>").append(size).append(" {print $0}' |head -50");
            logger.info("-------coll------Catalog--------");
            // 获得结果
            Vector<String> netlogV = tt.getResultAsVector(cmdsb.toString());
            String host_name = deviceId;
            // 得到unit_id中使用的主机名称
            String neat_host_name = Formater.neatenunitid(host_name);
            List<List<String>> resultList = analyticalResult(netlogV);
            for(List list:resultList){
                if(list.size() ==2){
                    //添加采集路径
                    //  CM-20-21-027-21关键路径
                    collResult.addKPI(UNIT_ID + "-74:"+host_name+"-" + list.get(0).toString(), "CM-20-21-027-01" , list.get(0).toString());
                    //添加采集路径大小  保留小数点后四位           b
                    // PM-20-21-027-21关键路径大小

                    collResult.addKPI(UNIT_ID + "-74:"+host_name+"-" + list.get(0).toString(), "PM-20-21-027-01" , Formater.formatDecimalByScale((Double.parseDouble(list.get(1).toString())/1024/1024)+"",4));
                }
            }
            //循环执行 用于多目录采集
//            for(count = 0;count<catalogList.length;count=count+2){
//                 String catalog = catalogList[count];
//                 String size = catalogList[count+1];
//                 // ls -ltrd catalog | grep '^d' | grep -v '201[456789]' |sort -nrk5 | awk '$5>size {print $0}' |head -50
//                 StringBuffer cmdsb = new StringBuffer();
//                //拼接采集语句
//                 cmdsb.append("ls -ltrd ").append(catalog).append(" | grep '^d' | grep -v '201[456789]' |sort -nrk5 | awk '$5>").append(size).append(" {print $0}' |head -50");
//                 logger.info("-------coll------Catalog--------");
//                 // 获得结果
//                 Vector<String> netlogV = tt.getResultAsVector(cmdsb.toString());
//                 String host_name = deviceId;
//                 // 得到unit_id中使用的主机名称
//                 String neat_host_name = Formater.neatenunitid(host_name);
//                 List<List<String>> resultList = analyticalResult(netlogV);
//                    for(List list:resultList){
//                        if(list.size() ==2){
//                        //添加采集路径
//                        //  CM-20-21-027-21关键路径
//                        collResult.addKPI(UNIT_ID + "-74:"+host_name+"-" + list.get(0).toString(), "CM-20-21-027-01" , list.get(0).toString());
//                        //添加采集路径大小      保留小数点后4位
//                        // PM-20-21-027-21关键路径大小
//                        collResult.addKPI(UNIT_ID + "-74:"+host_name+"-" + list.get(0).toString(), "PM-20-21-027-01" , Formater.formatDecimalByScale((Double.parseDouble(list.get(1).toString())/1024/1024)+"",4));
//                        }
//                    }
//            }
        }catch (Exception e) {
            logger.error("Exception while get Catalog!",e);
        }finally {
            release();
        }
        logger.info("END COLL Catalog ");
        return collResult.getKPISet();
    }

    /**
          *解析目录采集结果返回指定集合
          *List<List<String>>
          * */
    private List<List<String>> analyticalResult(List list){
        List<List<String>> resultList = new ArrayList<List<String>>();
        int i = 0;
        for(i=0;i< list.size();i++){
            //目标目录
            String path = split(list.get(i).toString(), 8);
            //目录大小
            String size = split(list.get(i).toString(),4);
            List<String>  strList = new ArrayList<String>();
            strList.add(path);
            strList.add(size);
            if((path != null & path !="")  && (size != null & size != "") ){
                resultList.add(strList);
            }
        }
        return  resultList;
    }
    public String getVetorString(List v) {
        StringBuffer sb = new StringBuffer();
        if (v != null && v.size() > 0) {
            for (int i = 0; i < v.size(); i++) {
                String s = (String) v.get(i);
                if (s != null && i < v.size()) {
                    sb.append(s + "\n");
                }
            }
        }
        return sb.toString();
    }

    public void init(HashMap<String,String> params) {
        deviceName = params.get("HOSTNAME");
        deviceId = Formater.neatenunitid(deviceName);

        ipAddr = params.get("IP_ADDR");
        String user = params.get("USERNAME");
        String passwd = params.get("PASSWORD");
        passwd = DES3.decrypt(passwd);
        String protocol = params.get("PROTOCOL");

        if (protocol != null && protocol.equals("telnet")) {
            tt = new TelnetThread(ipAddr, 23, user, passwd);
        } else {
            tt = new SSHThread(ipAddr, 22, user, passwd);
        }

        try {
            tt.initial();
        } catch (Exception e) {
            logger.error("Exception while initial RomoteController!", e);
        }
    }


    public static void  main(String[] args){

        CollFileMBean cmd = new CollFile();
		String deviceId = "11:22";
		String s1= "/ssdbomc";
		System.out.println(deviceId.substring(deviceId.indexOf(":")+1,deviceId.length()));
		System.out.println(s1.split("/")[s1.split("/").length-1]);
        HashMap<String, String> params = new HashMap<String, String>();

		params.put("IP_ADDR", "172.21.0.201");
		params.put("PASSWORD", "a1a50f36f1303ba3ed36f2b019e508f97628ee3c065f0984");
		params.put("PROTOCOL", "ssh");
		params.put("USERNAME", "ssdbomc");
		params.put("FILEPATH", "/ssdbomc/csdppd_mysql/cs/web_env/apache-tomcat-6.0/logs/catalina.out");
		params.put("UNIT_ID", "10-10-24:172_21_0_203");
		params.put("DEVICENAME", "172_21_0_203");
        params.put("CATALOG","/ssdbomc/csdppd_mysql/*/*/*/*,200000000000000");
        params.put("HOSTNAME","172.21.0.201");
        params.put("KBP_CLASS","10-10-21");
//		cmd.getFileChange(params);
        cmd.getCatalog(params);

        Vector<TblATO_KPIDETAIL> result = cmd.getFileChange(params);
        for (int i = 0; i < result.size(); i++) {
            TblATO_KPIDETAIL record = (TblATO_KPIDETAIL) result.get(i);
            System.out.println(record.UNIT_ID + "\t" + record.KPI_ID + "\t" + record.KPI_VALUE);
        }
//        System.out.println(Formater.formatDecimalByScale((Double.parseDouble(list.get(1).toString())/1024/1024)+"",4).getClass());
    }
}