CollNetDeviceWithSNMP.java 28.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
package com.sitech.ismp.coll.net;

import java.text.DecimalFormat;
import java.util.*;

import com.sitech.ismp.coll.net.cisco.NetEventEntry;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.snmp4j.mp.SnmpConstants;

import bsh.Interpreter;

import com.sitech.database.dao.TbCfgSnmpPriKpiConvertDao;
import com.sitech.database.dao.TbCfgSnmpPriOidDao;
import com.sitech.database.dao.TbTmpInterfaceDao;
import com.sitech.database.domain.TbCfgSnmpPriKpiConvert;
import com.sitech.database.domain.TbCfgSnmpPriOid;
import com.sitech.database.domain.TbTmpInterface;
import com.sitech.ismp.coll.CollBase;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.ismp.snmp.IfEntry;
import com.sitech.ismp.snmp.IpAddrEntry;
import com.sitech.ismp.util.Ping;
import com.sitech.util.DES3;
import com.sitech.util.Formater;
import com.sitech.util.JSONUtil;
import com.sitech.util.LogUtil;
import com.sitech.util.SNMPClient;

/**
 * User: LJ
 * Date: 2010-1-18
 * Time: 16:56:16
 */
public class CollNetDeviceWithSNMP extends CollBase{

    private String kbpClass;
    private String ipAddr;
    private String deviceName;
    
    private int snmpVersion;
    private int snmpPort;
    private String snmpCommunity;
    

    private SNMPClient client;
    
    private String sysObjectID;
    
    private boolean isConn = false;
    private boolean isSupportSnmp = false;
    private String serurityName;
    private String authenticationPassphrase;
    private String privacyPassphrase;
    private String authProtocal;
    private String  privProtocal;
    private String securityLevel;


    public Vector<TblATO_KPIDETAIL> getTotal(HashMap<String, String> params) throws Exception {
        init(params);
        String unitId = kbpClass + "-10" + ":" + deviceName + "-total";
        try {
            connect();
            // CM-00-02-001-04 设备名称
            super.addKPI(unitId, "CM-00-02-001-04", params.get("HOST_NAME"));
            // CM-00-02-001-05 IP地址
            super.addKPI(unitId, "CM-00-02-001-05", ipAddr);
            // CM-00-02-001-06 端口数量
            super.addKPI(unitId, "CM-00-02-001-06", getPortNum());
            // CM-00-02-001-07 系统启动时间
            super.addKPI(unitId, "CM-00-02-001-07", getDevSysUpTime());
            // CM-00-02-001-03 设备软件版本
            super.addKPI(unitId, "CM-00-02-001-03", getSoftVersion());
            // CM-00-02-001-08 设备型号
            super.addKPI(unitId, "CM-00-02-001-08", client.get("1.3.6.1.2.1.1.2.0"));
        } catch (Exception e) {
            LogUtil.error("Exception while getTotal", e);
        } finally {
            destroy();
        }
        return super.KPISet;
    }


    public Vector<TblATO_KPIDETAIL> getStatus(HashMap<String, String> params) throws Exception {
        init(params);
        String unitId = kbpClass + "-10" + ":" + deviceName + "-total";
        String status = "UP";
        try {
            connect();
        } catch (Exception e) {
            status = e.getMessage();
            boolean isReacheable = false;
            try {
                isReacheable = com.sitech.util.Ping.ping1(ipAddr);
                logger.info("first ping " + ipAddr + " is " + isReacheable);
                if (!isReacheable) {
                    Thread.sleep(5000);
                    isReacheable = com.sitech.util.Ping.ping1(ipAddr);
                    logger.info("second ping " + ipAddr + " is " + isReacheable);
                    if (!isReacheable) {
                        Thread.sleep(5000);
                        isReacheable = com.sitech.util.Ping.ping1(ipAddr);
                        logger.info("third ping " + ipAddr + " is " + isReacheable);
                    }
                }
            } catch (Exception ex) {
                status = ex.getMessage();
                logger.error("Exception while ping " + ipAddr, ex);
            } finally {
                if (isReacheable) {
                    status = "SNMP unreachable, ping is " + isReacheable;
                } else {
                    status = "SNMP unreachable, ping is " + isReacheable;
                }
            }
        } finally {
            // FM-00-02-001-01 设备状态
            super.addKPI(unitId, "FM-00-02-001-01", status);
            destroy();
        }
        return super.KPISet;
    }
	
	public Vector<TblATO_KPIDETAIL> getCpuMem(HashMap<String, String> params) throws Exception{
		init(params);

		String cpuUnitId = kbpClass + "-12" + ":" + deviceName + "-cpu";
		String memUnitId = kbpClass + "-12" + ":" + deviceName + "-mem";

		CollBase result = new CollBase();
		try {
			connect();

			// CPU利用率 PM-00-02-001-06
			result.addKPI(cpuUnitId, "PM-00-02-001-06", getDeviceCPU());
			// 内存利用率 PM-00-02-001-07
			result.addKPI(memUnitId, "PM-00-02-001-07", getDeviceMEM());
		} catch (Exception e) {
			LogUtil.error("Exception while getCpuMem", e);
		} finally {
			destroy();
		}
		
		return result.KPISet;
	}

    public Vector<TblATO_KPIDETAIL> getFirewall(HashMap<String,String> params) throws Exception {
        init(params);
        CollBase result = new CollBase();
        try {
            connect();
            getNetEvents();
        } catch (Exception e) {
            LogUtil.error("Exception while getFirewall", e);
        } finally {
            destroy();
        }

        return super.getKPISet();
    }

    /**
     * 子网掩码
     * @param params
     * @return
     * @throws Exception
     */
    public Vector<TblATO_KPIDETAIL> getSubnetMask(HashMap<String,String> params) throws Exception {
        init(params);
        CollBase result = new CollBase();
        String unitId = kbpClass + "-13" + ":" + deviceName;
        try {
            connect();
            Map<String,String> resultMap = client.walk2Map("1.3.6.1.2.1.4.20.1.3");
            if(resultMap != null && (!resultMap.isEmpty())){
                for(Map.Entry temp :resultMap.entrySet()){
                    String subnetIP = (String)temp.getKey();
                    String subnetMask = (String)temp.getValue();
                    // CM-00-02-001-09 子网掩码
                    result.addKPI(unitId+"-"+subnetIP, "CM-00-02-001-09", subnetMask);
                    // CM-00-02-001-05 子网IP
                    result.addKPI(unitId+"-"+subnetIP, "CM-00-02-001-05", subnetIP);
                }
            }

        } catch (Exception e) {
            LogUtil.error("Exception while getSubnetMask", e);
        } finally {
            destroy();
        }

        return result.getKPISet();
    }

    private Vector<TblATO_KPIDETAIL> getNetEvents() {
        try {
            // oidSet不能为空,用于值传递
            Set<String> oidSet = new HashSet<String>();
            NetEventEntry neEntry = client.getNetEventsEntry(oidSet);
            while (null != neEntry) {
                newNetEventKpi(neEntry);
                neEntry = client.getNetEventsEntry(oidSet);
            }
        } catch (Exception e) {
            LogUtil.error("Exception while getInterface", e);
        }
        return super.getKPISet();
    }

    private void newNetEventKpi(NetEventEntry neEntry) {
        String neUnitId = kbpClass + "-12" + ":" + deviceName + "-" + neEntry.getNeInterface();
        logger.info(neUnitId);
        super.addKPI(neUnitId, "&&&&&&&&&&&&&&&1", neEntry.getNeInterface());
        // 1.3.6.1.4.9.9.147.1.1.2.2.
        super.addKPI(neUnitId, "&&&&&&&&&&&&&&&2", neEntry.getNeSrcIpAddress());
        // 1.3.6.1.4.9.9.147.1.1.2.2.
        super.addKPI(neUnitId, "&&&&&&&&&&&&&&&3", neEntry.getNeSrcIpPort());
        // 1.3.6.1.4.9.9.147.1.1.2.2.
        super.addKPI(neUnitId, "&&&&&&&&&&&&&&&4", neEntry.getNeDstIpAddress());
        // 1.3.6.1.4.9.9.147.1.1.2.2.
        super.addKPI(neUnitId, "&&&&&&&&&&&&&&&5", neEntry.getNeDstIpPort());
        // 1.3.6.1.4.9.9.147.1.1.2.2.
        super.addKPI(neUnitId, "&&&&&&&&&&&&&&&6", neEntry.getNeService());
        // 1.3.6.1.4.9.9.147.1.1.2.2.
        super.addKPI(neUnitId, "&&&&&&&&&&&&&&&7", neEntry.getNeIdentity());
        // 1.3.6.1.4.9.9.147.1.1.2.2.
        super.addKPI(neUnitId, "&&&&&&&&&&&&&&&8", neEntry.getNeDescription());
    }
	
	public Vector<TblATO_KPIDETAIL> getPort(HashMap<String, String> params)
			throws Exception {
		init(params);
		Map<String, String> filter = new HashMap<String, String>();
		try{
			if (null != params.get("IF_FILTER")) {
				@SuppressWarnings("unchecked")
				List<String> ifFilterList = (List<String>) JSONUtil.fromJSON(params.get("IF_FILTER"));
				if (null != ifFilterList && !ifFilterList.isEmpty()) {
					for (String ifUnitId : ifFilterList) {
						filter.put(ifUnitId, ifUnitId);
					}
				}
			}
		}catch(Exception e){
			logger.error("Exception while init interface filter :" + params.get("IF_FILTER"), e);
		}

		try {
			connect();
			return getPortKpi(filter);
		} catch (Exception e) {
			LogUtil.error("Exception while getPort", e);
		} finally {
			destroy();
		}

		return null;
	}
	
    /**
     * 采集端口指标
     * PM-00-02-001-01 LAN(半双工)端口利用率 ((△ifInOctes+△ifOUtOetets)*8)/(T*ifSpeed)*100% 
     * PM-00-02-001-02 WAN(全双工)端口流入利用率 △ifInOctes*8/(T*ifSpeed)*100%
     * PM-00-02-001-03 WAN(全双工)端口流出利用率 △ifOUtOetets*8/(T*ifSpeed)*100%
     * PM-00-02-001-04 端口误码率 (△ifInErrors+△ifOutErrors)/(△ifInUcastPkts+△ifInNUcastPkts+△ifOutUcastPkts+△ifOutNUcastPkts)*100%
     * PM-00-02-001-05 端口丢包率 (△ifInDiscards+△ifOutDiscards)/(△ifInUcastPkts+△ifInNUcastPkts+△ifInUcastPkts+△ifInNUcastPkts)*100%
     * PM-00-02-001-11 端口流入错包数	△ifInErrors
     * PM-00-02-001-12 端口流出错包数	△ifOutErrors
     * PM-00-02-001-13 端口流入丢包数	△ifInDiscards
     * PM-00-02-001-14 端口流出丢包数	△ifOutDiscards
     * PM-00-02-001-24 端口流入速率 △ifInOctes/T*8*100%
     * PM-00-02-001-25 端口流出速率 △ifOutOctes/T*8*100%
     * FM-00-02-001-02 设备端口状态
     * FM-00-02-001-03 一层端口状态
     * FM-00-02-001-04 二层端口状态
     * CM-00-02-002-01 端口标识
     * CM-00-02-002-02 端口类型
     * CM-00-02-002-03 端口设置速率
     * CM-00-02-002-04 端口物理地址
     * CM-00-02-002-05 端口IP地址
     * 采集时间间隔(15分钟)
     * @param filter 
     */
    private Vector<TblATO_KPIDETAIL> getPortKpi(Map<String, String> filter) {


        try {
            Map<String, IpAddrEntry> ipAddrTable = client.walkIpAddrTable();

            // oidSet不能为空,用于值传递
            Set<String> oidSet = new HashSet<String>();
            IfEntry ifEntry = client.getIfEntry(oidSet);
            while(null != ifEntry){
                newIfKpi(ipAddrTable, ifEntry, filter);
                ifEntry = client.getIfEntry(oidSet);
            }
        }catch (Exception e) {
        	LogUtil.error("Exception while getInterface", e);
		}
        return super.getKPISet();
    }

    private void newIfKpi(Map<String, IpAddrEntry> ipAddrTable, IfEntry ifEntry, Map<String, String> filter) {
        Date newCollTime = new Date();

        String temp = ifEntry.getIfDescr().toLowerCase();
        if (temp.indexOf("null") >= 0 || temp.indexOf("loopback") >= 0) {
            return;
        }

        String ifUnitId = kbpClass + "-11" + ":" + deviceName + "-" + ifEntry.getIfDescr().replace("'","_").replace(" ","_") + "-interface";

        if (!filter.isEmpty() && !filter.containsKey(ifUnitId)) {
            return;
        }
//        //去掉英文单引号和空格,单引号和空格都改为下划线
//        ifUnitId = ifUnitId.replace("'","_");
//        ifUnitId = ifUnitId.replace(" ","_");

        super.addKPI(ifUnitId, "CM-00-02-002-01", ifEntry.getIfDescr());
        super.addKPI(ifUnitId, "CM-00-02-002-02", ifTypeHelper.getTypeDesc(ifEntry.getIfType()));
        super.addKPI(ifUnitId, "CM-00-02-002-03", ifEntry.getIfSpeed());
        super.addKPI(ifUnitId, "CM-00-02-002-04", ifEntry.getIfPhysAddress());
        super.addKPI(ifUnitId, "CM-00-02-002-07", ifEntry.getIfIndex());

        String adminStatus = ifOperStatusHelper.getOperStatusDesc(ifEntry.getIfAdminStatus());
        super.addKPI(ifUnitId, "FM-00-02-001-07", adminStatus);

        String operSatatus = ifOperStatusHelper.getOperStatusDesc(ifEntry.getIfOperStatus());
        super.addKPI(ifUnitId, "FM-00-02-001-08", operSatatus);

        IpAddrEntry ipAddrEntry = ipAddrTable.get(ifEntry.getIfIndex());
        if(ipAddrEntry == null){
            super.addKPI(ifUnitId, "CM-00-02-002-05", "--");
        }else{
            super.addKPI(ifUnitId, "CM-00-02-002-05", ipAddrEntry.getIpAdEntAddr() + ":" + ipAddrEntry.getIpAdEntNetMask());
        }

        String ifSpeed = ifEntry.getIfSpeed();

        TbTmpInterface newIf = new TbTmpInterface(ifEntry, ipAddr, newCollTime);
        TbTmpInterface oldIf = queryTbTmpInterface(ipAddr, ifEntry.getIfIndex());
        if(oldIf == null){
            // 首次采集
            addTbTmpInterface(newIf);
            return;
        }else{
            updateTbTmpInterface(newIf);
        }

        Date oldCollTime = oldIf.getCOLL_TIME();

        String ifInOctets = ifEntry.getIfInOctets();
        String ifInUcastPkts = ifEntry.getIfInUcastPkts();
        String ifInNUcastPkts = ifEntry.getIfInNUcastPkts();
        String ifInDiscards = ifEntry.getIfInDiscards();
        String ifInError = ifEntry.getIfInErrors();
        String ifOutOctets = ifEntry.getIfOutOctets();
        String ifOutUcastPkts = ifEntry.getIfOutUcastPkts();
        String ifOutNUcastPkts = ifEntry.getIfOutNUcastPkts();
        String ifOutDiscards = ifEntry.getIfOutDiscards();
        String ifOutError = ifEntry.getIfOutErrors();

        String oldInOctets = oldIf.getIF_IN_OCTETS();
        String oldInUcastPkts = oldIf.getIF_IN_UCASTPKTS();
        String oldInNUcastPkts = oldIf.getIF_IN_NUCASTPKTS();
        String oldInDiscards = oldIf.getIF_IN_DISCARDS();
        String oldInError = oldIf.getIF_IN_ERRORS();
        String oldOutOctets = oldIf.getIF_OUT_OCTETS();
        String oldOutUcastPkts = oldIf.getIF_OUT_UCASTPKTS();
        String oldOutNUcastPkts = oldIf.getIF_OUT_NUCASTPKTS();
        String oldOutDiscards = oldIf.getIF_OUT_DISCARDS();
        String oldOutError = oldIf.getIF_OUT_ERRORS();

        // 计算差值
        DecimalFormat df = new DecimalFormat();
        String difInOctets = df.format(Math.abs(Float.parseFloat(Formater.counter32_sub(ifInOctets, oldInOctets))));
        String difOutOctets = df.format(Math.abs(Float.parseFloat(Formater.counter32_sub(ifOutOctets, oldOutOctets))));
        String difInError = Formater.counter32_sub(ifInError, oldInError);
        String difOutError = Formater.counter32_sub(ifOutError, oldOutError);
        String difInDiscards = Formater.counter32_sub(ifInDiscards, oldInDiscards);
        String difOutDiscards = Formater.counter32_sub(ifOutDiscards, oldOutDiscards);
        String difInUCastPkts = Formater.counter32_sub(ifInUcastPkts, oldInUcastPkts);
        String difOutUcastPkts = Formater.counter32_sub(ifOutUcastPkts, oldOutUcastPkts);
        String difInNUcastPkts = Formater.counter32_sub(ifInNUcastPkts, oldInNUcastPkts);
        String difOutNUCastPkts = Formater.counter32_sub(ifOutNUcastPkts, oldOutNUcastPkts);

        // T单位:秒
        String T = String.valueOf(Formater.parseExpression("("
                + String.valueOf(newCollTime.getTime()) + "-"
                + String.valueOf(oldCollTime.getTime()) + ")/1000"));

        // PM-00-02-001-01 LAN(半双工)端口利用率
        // (△ifInOctes+△ifOUtOetets)/(T*ifSpeed*8)*100%
        String ifUseRate = Formater.double2String(Formater.parseExpression("("+ difInOctets + "+" + difOutOctets +")" + "/(" + T + "*" + ifSpeed + ")*8*100"));
        super.addKPI(ifUnitId, "PM-00-02-001-01", ifUseRate);

        // PM-00-02-001-02 WAN(全双工)端口流入利用率 △ifInOctes/(T*ifSpeed)*8*100%   //modified by lj
        String ifInUseRate = Formater.double2String(Formater
                .parseExpression(difInOctets + "/(" + T + "*" + ifSpeed
                        + ")*8*100"));
        super.addKPI(ifUnitId, "PM-00-02-001-02", ifInUseRate);
        // PM-00-02-001-03 WAN(全双工)端口流出利用率
        // △ifOUtOetets/(T*ifSpeed*8)*100%
        String ifOutUseRate = Formater.double2String(Formater
                .parseExpression(difOutOctets + "/(" + T + "*"
                        + ifSpeed + ")*8*100"));  //modified by lj
        super.addKPI(ifUnitId, "PM-00-02-001-03", ifOutUseRate);

        //PM-00-02-001-24 端口流入速率 △ifInOctes/T*8*100%
        String ifInOctetsRate = Formater.double2String(Formater
                .parseExpression(difInOctets + "/" + T + "*8"));
        super.addKPI(ifUnitId, "PM-00-02-001-24", ifInOctetsRate);

        //PM-00-02-001-25 端口流出速率 △ifOutOctes/T*8*100%
        String ifOutOctetsRate = Formater.double2String(Formater
                .parseExpression(difOutOctets + "/" + T + "*8"));
        super.addKPI(ifUnitId, "PM-00-02-001-25", ifOutOctetsRate);

        // PM-00-02-001-04 端口误码率
        // (△ifInErrors+△ifOutErrors)/(△ifInUcastPkts+△ifInNUcastPkts+△ifOutUcastPkts+△ifOutNUcastPkts)*100%
        String ifErrorRate = Formater.double2String(Formater
                .parseExpression("(" + difInError + "+" + difOutError
                        + ")/(" + difInUCastPkts + "+"
                        + difInNUcastPkts + "+" + difOutUcastPkts + "+"
                        + difOutNUCastPkts + ")*100")); //modified by lj
        super.addKPI(ifUnitId, "PM-00-02-001-04", ifErrorRate);
        // PM-00-02-001-05 端口丢包率
        // (△ifInDiscards+△ifOutDiscards)/(△ifInUcastPkts+△ifInNUcastPkts+△ifInUcastPkts+△ifInNUcastPkts)*100%
        String ifDiscardsRate = Formater.double2String(Formater
                .parseExpression("(" + difInDiscards + "+"
                        + difOutDiscards + ")/(" + difInUCastPkts + "+"
                        + difInNUcastPkts + "+" + difOutUcastPkts + "+"
                        + difOutNUCastPkts + ")*100"));  //modified by lj
        super.addKPI(ifUnitId, "PM-00-02-001-05", ifDiscardsRate);
        //分端口入错误率
        String ifInErrorRate = Formater.double2String(Formater
                .parseExpression("(" + difInError + ")/(" + difInUCastPkts + "+"
                        + difInNUcastPkts + ")*100"));
        super.addKPI(ifUnitId, "PM-00-02-001-15", ifInErrorRate);
        //分端口出错误率
        String ifOutErrorRate = Formater.double2String(Formater
                .parseExpression("(" +difOutError + ")/(" + difOutUcastPkts + "+"
                        + difOutNUCastPkts + ")*100"));
        super.addKPI(ifUnitId, "PM-00-02-001-16", ifOutErrorRate);
        //分端口入 丢包率
        String ifInDiscardsRate = Formater.double2String(Formater
                .parseExpression("(" + difInDiscards + ")/(" + difInUCastPkts + "+"
                        + difInNUcastPkts + ")*100"));
        super.addKPI(ifUnitId, "PM-00-02-001-17", ifInDiscardsRate);

        //分端口出丢包率
        String ifOutDiscardsRate = Formater.double2String(Formater
                .parseExpression("(" + difOutDiscards + ")/(" + difOutUcastPkts + "+"
                        + difOutNUCastPkts + ")*100"));
        super.addKPI(ifUnitId, "PM-00-02-001-18", ifOutDiscardsRate);

        // PM-00-02-001-11 端口流入错包数	△ifInErrors
        super.addKPI(ifUnitId, "PM-00-02-001-11", difInError);
        // PM-00-02-001-12 端口流出错包数	△ifOutErrors
        super.addKPI(ifUnitId, "PM-00-02-001-12", difOutError);
        // PM-00-02-001-13 端口流入丢包数	△ifInDiscards
        super.addKPI(ifUnitId, "PM-00-02-001-13", difInDiscards);
        // PM-00-02-001-14 端口流出丢包数	△ifOutDiscards
        super.addKPI(ifUnitId, "PM-00-02-001-14", difOutDiscards);

        // ifInOctets 端口流入字节数
        super.addKPI(ifUnitId, "PM-00-02-001-26", ifInOctets);
        // ifOutOctets 端口流出字节数
        super.addKPI(ifUnitId, "PM-00-02-001-27", ifOutOctets);

        String portStatus = adminStatus;
        // 如果用户配置的是up,但实际情况为down,则表示该端口处于down的状态
        if ("UP".equals(adminStatus) && !"UP".equals(operSatatus)) {
            portStatus = operSatatus;
            if (Float.valueOf(difInOctets) > 512 || Float.valueOf(difOutOctets) > 512 ) {
                portStatus = "UP";
            }
        }
        super.addKPI(ifUnitId, "FM-00-02-001-02", portStatus);
    }

	/**
	 * 得到设备CPU利用率 PM-00-02-001-06
	 */
	private String getDeviceCPU() {
		try {
			TbCfgSnmpPriKpiConvert convert = getTbCfgSnmpPriKpiConvert("PM-00-02-001-06");

			String expression = convert.getEXPRESSION();
			List<TbCfgSnmpPriOid> oidList = getTbCfgSnmpPriOid();
			Interpreter interpreter = new Interpreter();

			for (TbCfgSnmpPriOid oid : oidList) {
				String name = oid.getNAME();
				if (!name.startsWith("CPU_")) {
					continue;
				}

				String value = "";
				Double valueD = 0.0;
				if (oid.getOID().startsWith("WALK:")) {
					String oidStr = oid.getOID().replace(
							"WALK:", "");
					boolean ignore0 = false;
					if(oidStr.endsWith(":IGNORE0")){
						oidStr = oidStr.replace(":IGNORE0","");
						ignore0 = true;
					}
					List<String> list = client.walk(oidStr);

					// 记录实际在使用的CPU个数,常数为0的表示该板卡不使用,可以将其忽略掉
					int cpuSum = 0;

					if (list != null && list.size() > 0) {
						// 如果有多个板卡,则求平均值
						for (String tmpStr : list) {
							Double tmp = 0.0;
							if (tmpStr != null && !tmpStr.isEmpty()) {
								tmp = Double.parseDouble(tmpStr.trim());
							}

							valueD += tmp;
							if(tmp == 0 && ignore0){
								cpuSum ++;
							}else{
								cpuSum = list.size();
							}

						}

						valueD = cpuSum!=0?(valueD / cpuSum):0;
					}
					value = Formater.formatDecimalKpivalue(String
							.valueOf(valueD));
				} else {
					// 单块板卡
					value = client.get(oid.getOID());
				}

				logger.info(" --" + name + "\t" + oid.getOID() + "\t" + value);
				interpreter.set(oid.getNAME(), value);
			}
			interpreter.eval("result=" + expression);

			Double cpuUseRate = (Double) interpreter.get("result");

			return Formater.double2String(cpuUseRate);
		} catch (Exception e) {
			LogUtil.error("Exception while getDeviceCPU", e);
			return "0";
		}
	}

	/**
	 * 得到设备内存利用率 PM-00-02-001-07
	 */
	private String getDeviceMEM() {
		try {
			TbCfgSnmpPriKpiConvert convert = getTbCfgSnmpPriKpiConvert("PM-00-02-001-07");

			String expression = convert.getEXPRESSION();

			List<TbCfgSnmpPriOid> oidList = getTbCfgSnmpPriOid();
			Interpreter interpreter = new Interpreter();

			for (TbCfgSnmpPriOid oid : oidList) {
				// 增加华三采集方式
				if (oid.getOID().startsWith("WALK:")) {
					String oidStr = oid.getOID().replace(
							"WALK:", "");

					boolean ignore0 = false;
					if(oidStr.contains(":IGNORE0")){
						ignore0 = true;
						oidStr = oidStr.replace(":IGNORE0","");
					}
					if(oidStr.contains("MUTI_MEM:")){
						oidStr = oidStr.replace("MUTI_MEM:","");// 多内存卡的情况,只需获取使用率相除即可
						List<String> list = client.walk(oidStr);

						int memSum = 0;
						double valueD = 0;
						if(list!= null && list.size() > 0){
							for (String elem : list) {
								double tmp = Double.parseDouble(elem);
								if(tmp == 0 && ignore0){ continue;}
								valueD += tmp;
								memSum ++;
							}
						}
						logger.info(" --" + oid.getNAME() + "\t" + oid.getOID()
								+ "\t" + valueD);
						logger.info(" --" + "SIZE" + "\t" + oid.getOID()
								+ "\t" + String.valueOf(memSum));
						interpreter.set(oid.getNAME(), String.valueOf(valueD));
						interpreter.set("SIZE", String.valueOf(memSum));//实际使用的内存槽数量

					}else {
						List<String> list = client.walk(oidStr);
						double valueD = 0;
						for (String elem : list) {
							valueD += Double.parseDouble(elem);
						}
						logger.info(" --" + oid.getNAME() + "\t" + oid.getOID()
								+ "\t" + valueD);
						interpreter.set(oid.getNAME(), String.valueOf(valueD));
					}
				} else {
					String value = client.get(oid.getOID());
					interpreter.set(oid.getNAME(), value);
					logger.info(" --" + oid.getNAME() + "\t" + oid.getOID()
							+ "\t" + value);
				}
			}
			interpreter.eval("result=" + expression);

			Double memUseRate = (Double) interpreter.get("result");

			return Formater.double2String(memUseRate);
		} catch (Exception e) {
			LogUtil.error("Exception while getDeviceMEM", e);
			return "0";
		}
	}

	private void init(HashMap<String, String> params) throws Exception {
		kbpClass = params.get("KBP_CLASS");
		ipAddr = params.get("IP");
		
		deviceName = Formater.neatenunitid(params.get("HOST_NAME"));
		
		try {
			snmpCommunity = DES3.decrypt(params.get("COMMUNITY"));
		}catch (Exception e) {
			throw new Exception("Wrong SNMP COMMUNITY");
		}
		
		try {
			snmpPort = Integer.parseInt(params.get("PORT"));
		} catch (Exception e) {
			throw new Exception("Wrong SNMP PORT:" + params.get("PORT"));
		}

		String versionStr = params.get("VERSION");

		if (versionStr != null && versionStr.toLowerCase().trim().equals("v1")) {
			snmpVersion = SnmpConstants.version1;
		} else if (versionStr != null
				&& versionStr.toLowerCase().trim().equals("v2c")) {
			snmpVersion = SnmpConstants.version2c;
		} else if (versionStr != null
				&& versionStr.toLowerCase().trim().equals("v3")) {
            snmpVersion = SnmpConstants.version3;
		} else {
			// 默认按照v2c版本采集
			snmpVersion = SnmpConstants.version2c;
		}
        if(SnmpConstants.version3==snmpVersion){
             serurityName=params.get("securityName");
            if(params.get("authenticationPassphrase")!=null){
                authenticationPassphrase=DES3.decrypt(params.get("authenticationPassphrase"));
            }
             authProtocal=params.get("authenticationProtocol");
             privProtocal=params.get("privacyProtocol");
            if(params.get("privacyPassphrase")!=null){
                privacyPassphrase=DES3.decrypt(params.get("privacyPassphrase"));
            }
             securityLevel=params.get("auth_priv_mode");
        }
	}

	private void connect() throws Exception {
		client = new SNMPClient(ipAddr, snmpPort, snmpCommunity, snmpVersion,securityLevel,serurityName,authProtocal,authenticationPassphrase,
                privProtocal,privacyPassphrase);
		isSupportSnmp = client.isOpenSNMP();
		isConn = client.connect();
		if (!isConn || !isSupportSnmp) {
			throw new Exception(
					"Device not support SNMP or Collect params is wrong or Network is error: "
							+ ipAddr + ":" + snmpPort);
		}
		sysObjectID = client.get("1.3.6.1.2.1.1.2.0");
        System.out.println(sysObjectID);
    }

    /**
     * 采集端口数量 CM-00-02-001-06
     */
	private String getPortNum() {
		String oid = "1.3.6.1.2.1.2.1.0";

		String portNum = null;
		try {
			portNum = client.get(oid);
		} catch (Exception e) {
			LogUtil.error("Exception while getPortNum", e);
		}
		return portNum;
	}

    /**
     * 采集系统启动时间
     */
	private String getDevSysUpTime() {
		String oid = "1.3.6.1.2.1.1.3.0";
		String sysUpTime = null;
		try {
			sysUpTime = client.get(oid);
		} catch (Exception e) {
			LogUtil.error("Exception while getDevSysUpTime", e);
		}
		return sysUpTime;
	}

    /**
     * 设备软件版本
     */
	private String getSoftVersion() {
		String oid = "1.3.6.1.2.1.1.1.0";
		String version = null;
		try {
			version = client.get(oid).replace("\n", " ").replace("\r", "");
		} catch (Exception e) {
			LogUtil.error("Exception while getSoftVersion", e);
		}
		return version;
	}


    private void updateTbTmpInterface(TbTmpInterface newIf) {
    	TbTmpInterfaceDao dao = new TbTmpInterfaceDao();
    	dao.deleteTbTmpInterface(newIf);
    	dao.addTbTmpInterface(newIf);		
	}

	private void addTbTmpInterface(TbTmpInterface newIf) {
		TbTmpInterfaceDao dao = new TbTmpInterfaceDao();
		dao.addTbTmpInterface(newIf);		
	}

	private TbTmpInterface queryTbTmpInterface(String ipAddr, String ifIndex) {
		TbTmpInterfaceDao dao = new TbTmpInterfaceDao();
		return dao.queryTbTmpInterface(ipAddr, ifIndex);
	}
	
	   
	private TbCfgSnmpPriKpiConvert getTbCfgSnmpPriKpiConvert(String kpiId) {
		TbCfgSnmpPriKpiConvertDao dao = new TbCfgSnmpPriKpiConvertDao();
		return dao.queryTbCfgSnmpPriKpiConvert(sysObjectID, kpiId);
	}
	

	private List<TbCfgSnmpPriOid> getTbCfgSnmpPriOid() {
		TbCfgSnmpPriOidDao dao = new TbCfgSnmpPriOidDao();
		return dao.queryTbCfgSnmpPriOid(sysObjectID);
	}

	private TblATO_KPIDETAIL createKPI(String unitId, String kpiId,
			String kpiValue) {
		TblATO_KPIDETAIL tblato_kpidetail = new TblATO_KPIDETAIL();
		tblato_kpidetail.UNIT_ID = unitId;
		tblato_kpidetail.KPI_ID = kpiId;
		tblato_kpidetail.KPI_VALUE = kpiValue;
		tblato_kpidetail.CLL_TIME = new Date();
		return tblato_kpidetail;
	}
    
	public void destroy() {
		if(client != null){
			client.close();
		}
	}


}