PDUProcessor.java 11.1 KB
package com.sitech.ismp.snmp;

import com.sitech.database.dao.TbAssestHostDao;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.util.Formater;
import org.apache.log4j.Logger;
import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.ResourceBundle;
import java.util.Vector;
import java.util.List;
import com.sitech.database.dao.TbCfgSnmpTrapOidDao;

public class PDUProcessor implements CommandResponder {
    private static Logger logger = Logger.getLogger("SNMP_TRAP");
	String swap_path;
	String trap_config_path;
    String error_path;
	Hashtable trapMap = new Hashtable();
	ResourceBundle snmpConfig =null;
    static SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public PDUProcessor() {
		try {
			snmpConfig = ResourceBundle.getBundle("snmp");
			// 在snmp.properties获得snmp配置参数
			this.swap_path = snmpConfig.getString("swap_path");
            this.trap_config_path = snmpConfig.getString("trap_config_path");
            this.error_path=snmpConfig.getString("error_file_path");
		//	initTrapConfig();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("initial swap_path config error......exit ");
		}
	}

	private void initTrapConfig() {
		if (this.trap_config_path != null) {
			//读Trap配置信息,并把配置信息放到一个hashtable中。
			File file = new File(System.getProperty("user.dir")+"/config/"+this.trap_config_path);
			if (file.isFile()) {
				FileReader fr = null;
				BufferedReader bfr = null;
				try {
					fr = new FileReader(file);
					bfr = new BufferedReader(fr);
					String line = null;
					while ((line = bfr.readLine()) != null) {
						String[] trap_config = line.split(",");
						if (trap_config != null && trap_config.length == 3) {
							String oid = trap_config[0];
							String kbp_class = trap_config[1];
							String kpi_id = trap_config[2];
							TrapDescription trapDes = new TrapDescription();
							trapDes.setKbp_class(kbp_class);
							trapDes.setKpi_id(kpi_id);
							trapDes.setOid(oid);
							this.trapMap.put(oid, trapDes);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (fr != null) {
						try {
							fr.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					if (bfr != null) {
						try {
							bfr.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}

			}
		}
	}

    private void initTrapConfigByHsqldb(){
        TbCfgSnmpTrapOidDao dao =new TbCfgSnmpTrapOidDao();
        List list=dao.queryTbCfgSnmpTrapOid();
        for(int i=0;i<list.size();i++){
            TrapDescription trapDes=(TrapDescription)list.get(i);
            String oid=trapDes.getOid();
            this.trapMap.put(oid, trapDes);
        }


    }

	public void processPdu(CommandResponderEvent respEvnt) {
//        initTrapConfigByHsqldb();
		// 解析Response
		Address ad = respEvnt.getPeerAddress();
		System.out.println("trap_from=" + ad.toString());
		String trap_ip = ad.toString();
		String ip = null;
		//解析出IP地址
		int index_split =0;
		if(trap_ip!=null&&!trap_ip.trim().equals("")){
			index_split = trap_ip.indexOf("/");
			if(index_split>0){
				ip=trap_ip.substring(0,index_split);
			}
		}
		if(ip!=null){

            recodeSnmpTrapRequest(respEvnt);
            //根据IP地址在tb_assest_host中查询对应的unit_id,如果没有找到,则将该信息记录在缺失文件中
            String unit_id="";
            TbAssestHostDao dao=new TbAssestHostDao();
            unit_id=dao.queryUnitIdByIPaddress(ip);
            if(!"".equals(unit_id)) {
                if (respEvnt != null && respEvnt.getPDU() != null) {
                    PDU pdu=respEvnt.getPDU();
                    doPDUVariableBinding(pdu,unit_id);
                }

                }

            }else{
                //缺少监控实体,进行记录
                try {
                    String time= PDUProcessor.format1.format(new Date());
                    File errorFile=new File(error_path);
                    FileWriter fw= null;
                    fw = new FileWriter(errorFile,true);
                    PrintWriter pw=new PrintWriter(fw);
                    pw.println(time+"------IP:"+ip+"对应实体缺失");
                    fw.flush();
                    pw.close();
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    private void doPDUVariableBinding(PDU pdu,String unit_id){
        PDU trappdu=pdu;
        PDUv1 pdu1=null;
        // 记录SNMP数据发送过来的时间
        Vector snmp_kpi_set = new Vector();
        Vector recVBs=null;
        if(trappdu instanceof PDUv1){
            pdu1 = (PDUv1) trappdu;
            //判断是否是通用告警
            int common_alarm=pdu1.getGenericTrap();
            String kpi_value="";
            switch (common_alarm){
                case SNMPConstant.COLDSTARTv1:
                    kpi_value= SNMPConstant.COLDSTARTDes;
                    break;
                case SNMPConstant.WARMSTARTv1:
                    kpi_value= SNMPConstant.WARMSTARTDes;
                    break;
                case SNMPConstant.LINKDAOWNv1:
                    kpi_value= SNMPConstant.LINKDAOWNDes;
                    break;
                case SNMPConstant.LINKUPv1:
                    kpi_value= SNMPConstant.LINKUPDes;
                    break;
                case SNMPConstant.AUTHENTICATIONFAILUREv1:
                    kpi_value= SNMPConstant.AUTHENTICATIONFAILUREDes;
                    break;
                case SNMPConstant.EGPNEIGHBORLOSSv1:
                    kpi_value= SNMPConstant.EGPNEIGHBORLOSSDes;
                    break;
            }
            if(!"".equals(kpi_value)){
                TrapDescription trapDes = (TrapDescription) this.trapMap
                        .get(SNMPConstant.TRAPOID);
                String kbp_class = trapDes.getKbp_class();
                String kpi_id = trapDes.getKpi_id();

                TblATO_KPIDETAIL ato_kpi_detail = new TblATO_KPIDETAIL();
                try {
                    ato_kpi_detail.setKPI_ID(kpi_id);
                    ato_kpi_detail.setUNIT_ID(unit_id);
                    ato_kpi_detail.setKPI_VALUE(kpi_value);
                    ato_kpi_detail.setCLL_TIME(new Date());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                snmp_kpi_set.add(ato_kpi_detail);

            }
            recVBs=pdu1.getVariableBindings();
        }else{
            recVBs=pdu.getVariableBindings();
        }

        for (int i = 0; i < recVBs.size(); i++) {
            VariableBinding recVB = (VariableBinding) recVBs.elementAt(i);
            String oid = recVB.getOid().toString();
            String value = "";

            try {
                OctetString octs = new OctetString();
                octs = (OctetString) recVB.getVariable();
                if (octs.getValue() != null){
                    value = new String(octs.getValue(), "GBK");
                }
            } catch (Exception e) {
                value = recVB.getVariable().toString();
            }
            if(SNMPConstant.TRAPOID.equals(oid)){
                //V2.0版本的通用告警
                if(value.equals(SNMPConstant.COLDSTART)) value= SNMPConstant.COLDSTARTDes;
                if(value.equals(SNMPConstant.WARMSTART)) value= SNMPConstant.WARMSTARTDes;
                if(value.equals(SNMPConstant.LINKDAOWN)) value= SNMPConstant.LINKDAOWNDes;
                if(value.equals(SNMPConstant.LINKUP)) value= SNMPConstant.LINKUPDes;
                if(value.equals(SNMPConstant.AUTHENTICATIONFAILURE)) value= SNMPConstant.AUTHENTICATIONFAILUREDes;
            }
            TrapDescription trapDes = (TrapDescription) this.trapMap
                    .get(oid);
            if (trapDes == null) {
                //接受到的Trap信息未在trap_config中配置
                System.out.println("can't match Trap config oid=" + oid + "~" + value);
            } else {
                //找到匹配的Trap配置,生成告警
                try {
                    String kbp_class = trapDes.getKbp_class();
                    String kpi_id = trapDes.getKpi_id();

                    TblATO_KPIDETAIL ato_kpi_detail = new TblATO_KPIDETAIL();
                    ato_kpi_detail.setUNIT_ID(unit_id);
                    ato_kpi_detail.setKPI_ID(kpi_id);
                    ato_kpi_detail.setKPI_VALUE(value);
                    ato_kpi_detail.setCLL_TIME(new Date());
                    snmp_kpi_set.add(ato_kpi_detail);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        // 把生成的KPI写到文件中
        writeKPI2file(snmp_kpi_set);
    }
	/**
	 * 把kpi写到swap文件中
	 * 
	 *
	 */
	public void writeKPI2file(Vector KPISet) {
		PrintWriter kpiFileStream = null;
		for (int i = 0; i < KPISet.size(); i++) {
			TblATO_KPIDETAIL tblato_kpidetail = (TblATO_KPIDETAIL) KPISet
					.elementAt(i);
			if (tblato_kpidetail == null)
				continue;

			if (kpiFileStream == null) {
				String kpiFileName = null;
				try {
					String swapPath = this.swap_path;
					if (swapPath != null && !swapPath.endsWith("/")) {
						swapPath = swapPath + "/";
					}
					String cTime = "";
					try {
						cTime = Formater
								.getDateAsFile(tblato_kpidetail.CLL_TIME);
					} catch (ParseException e) {
						 logger.error("", e);
					}
					kpiFileName = swapPath + cTime
							+ tblato_kpidetail.KPI_ID;
                    System.out.println("kpiFileName:"+kpiFileName);
					kpiFileStream = new PrintWriter(new FileWriter(Formater
							.replaceSpace(kpiFileName), true), true);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			String cDateTime = "";
				cDateTime = Formater
						.datetimeToString(tblato_kpidetail.CLL_TIME);
			kpiFileStream.println(tblato_kpidetail.UNIT_ID + "	"
					+ tblato_kpidetail.KPI_ID + "	" + cDateTime + "	"
					+ tblato_kpidetail.KPI_VALUE);

		}
		kpiFileStream.flush();
		kpiFileStream.close();
	}

    private void recodeSnmpTrapRequest(CommandResponderEvent respEvnt){
        PDU pdu=respEvnt.getPDU();
        Vector recVBs=pdu.getVariableBindings();
        for (int i = 0; i < recVBs.size(); i++) {
            VariableBinding recVB = (VariableBinding) recVBs.elementAt(i);
            String oid = recVB.getOid().toString();
            String value = "";

            try {
                OctetString octs = new OctetString();
                octs = (OctetString) recVB.getVariable();
                if (octs.getValue() != null){
                    value = new String(octs.getValue(), "GBK");
                }
            } catch (Exception e) {
                value = recVB.getVariable().toString();
            }

            logger.info("oid="+oid+"------------value="+value);
        }
    }
}