CollLinuxWithCMDByCron.java 59.6 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 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
package com.sitech.ismp.coll.host;

import com.sitech.ismp.app.coll.RPCTarget;
import com.sitech.ismp.coll.CollBase;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.ismp.coll.virtual.VirtualScheduleManager;
import com.sitech.util.Formater;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.libvirt.Connect;
import org.libvirt.Domain;
import org.libvirt.DomainInfo;
import org.libvirt.LibvirtException;

import java.io.*;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Chandler
 * Date: 14-2-20
 * Time: 下午2:45
 * To change this template use File | Settings | File Templates.
 */
public class CollLinuxWithCMDByCron extends CollBase {

    static final String RESULT_PATH = "../result/";

    String kbpClass = "10-10-24";//linux 主机标识

    RPCTarget rpctarget = new RPCTarget();

    String deviceId;

    static final String SH_COLL_DISK = "getLinuxDisk.sh";
    static final String RESULT_DISK = "linuxDiskResult";

    static final String SH_COLL_PROCESS = "getLinuxProcessTop10.sh";
    static final String RESULT_PROCESS = "linuxProcessTop10Result";

    static final String SH_COLL_KEY_PROCESS = "getLinuxProcess.sh";
    static final String RESULT_KEY_PROCESS = "linuxProcessResult";

    static final String SH_COLL_CONFIG = "getLinuxConfig.sh";
    static final String RESULT_CONFIG = "linuxConfigResult";

    static final String SH_COLL_NET = "getLinuxNet.sh";
    static final String RESULT_NET = "linuxNetResult";

    static final String SH_COLL_FILE = "getFile.sh";
    static final String RESULT_FILE = "fileResult";

    public CollLinuxWithCMDByCron(){

    }
    /**
     * 通知执行脚本
     * 通知方式:写一个文件(文件名为采集脚本名称,如:getCpu.sh、getMem.sh)到notice目录,
     * contab会定时执行脚本扫描该目录,得到文件名,并执行脚本
     *
     * @throws
     * @since Ver 1.1
     */
    private void exec(String shellName) {
        String noticePath = "../notice/ibm/";
        String noticeFileName = noticePath + shellName;
        PrintWriter kpiFileStream = null;
        try {
            kpiFileStream = new PrintWriter(new FileWriter(Formater.replaceSpace(noticeFileName), false), true);
            kpiFileStream.println(shellName);
        } catch (IOException e) {
            logger.error("[Linux COLL] Exception while exec(" + shellName + ")", e);
        } finally {
            if (kpiFileStream != null) {
                kpiFileStream.flush();
                kpiFileStream.close();
            }
        }
    }

    /**
     * 获得脚本执行结果
     *
     * @throws
     * @since Ver 1.1
     */
    private List<String> getResult(String resultFileName) {
        try {
            Thread.sleep(20 * 1000L);
        } catch (InterruptedException e) {
            logger.warn("[Linux COLL] InterruptedException.");
        }

        StringBuffer sb = new StringBuffer();
        // 超时时间:2分钟
        long timeout = 3 * 60 * 1000L;
        List<String> result = new ArrayList<String>();
        long beginTime = new Date().getTime();

        File file = new File(RESULT_PATH);
        while (true) {
            if (new Date().getTime() - beginTime > timeout) {
                // 超时退出
                logger.warn("[Linux COLL] Timeout, exit.");
                break;
            }

            File[] filelist = file.listFiles();
            if (filelist == null || filelist.length == 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    logger.error("[Linux COLL] InterruptedException", e);
                }
                continue;
            }

            File resultFile = null;
            // 根据文件名找到采集文件
            for (int i = 0; i < filelist.length; i++) {
                if (filelist[i].getName().startsWith(resultFileName)) {
                    resultFile = filelist[i];
                    break;
                }
            }

            if (resultFile != null) {
                BufferedReader br = null;
                try {
                    br = new BufferedReader(new FileReader(resultFile));
                    String line = "";
                    while ((line = br.readLine()) != null) {
                        result.add(line);
                        sb.append(line + "\n");
                    }
                    break;
                } catch (Exception e) {
                    logger.error("[Linux COLL] Exception while readFile:" + resultFileName, e);
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            logger.error("[Linux COLL] IOException:", e);
                        }
                    }
                    logger.info("[HP COLL] Delete coll result file : " + resultFile.getName());
                    logger.info(RESULT_PATH + ":\n" + sb.toString());
                    resultFile.delete();
                }
            }
        }// end while

        return result;
    }

    /**
     * 解析每个命令的执行结果
     *
     * @throws
     * @since Ver 1.1
     */
    private List<List<String>> parseResult(List<String> result, int num) {
        List<List<String>> list = new ArrayList<List<String>>();
        for (int i = 0; i < num; i++) {
            list.add(new ArrayList<String>());
        }

        int i = 0;
        for (String line : result) {
            if (line.trim().equals(SPLIT_LINE)) {
                i++;
                continue;
            }else if(line.trim().endsWith(SPLIT_LINE)){
                line = line.replace(SPLIT_LINE,"");
                list.get(i).add(line);
                i++;
            }else{
                list.get(i).add(line);
            }
        }
        return list;
    }

    private void init(HashMap<String, String> params){
        deviceId = params.get("DEVICE_ID");
        if (null == deviceId || "".equals(deviceId) || "null".equals(deviceId)) {
            deviceId = getHostName(params);
        }
        deviceId = Formater.neatenunitid(deviceId);
    }



    /**
     * CM-00-01-001-01	主机名
     * CM-00-01-001-03	主机厂商
     */
    public Vector<TblATO_KPIDETAIL> collBaseInfo(HashMap<String, String> params){
        init(params);
        CollBase collResult = new CollBase();
        String unitId = kbpClass + "-10:" + deviceId + "-total";
        collResult.addKPI(unitId, "CM-00-01-001-01", getHostName(params));
        collResult.addKPI(unitId, "CM-00-01-001-03", "Linux");
        return collResult.KPISet;
    }

    /**
     * CM-00-01-001-04 主机CPU个数
     * CM-00-01-001-05 主机CPU型号
     * CM-00-01-001-06 主机CPU主频
     */
    public Vector<TblATO_KPIDETAIL> collCpuInfo(HashMap<String, String> params){
        init(params);
        CollBase collResult = new CollBase();
        String unitId = kbpClass + "-10:" + deviceId + "-total";

        String cpuCount = rpctarget.getKPIValue("sh linux/cpucount.sh");
        if(null == cpuCount || "".equals(cpuCount)){
            cpuCount = "-";
        }
        collResult.addKPI(unitId, "CM-00-01-001-04", cpuCount.trim());

        String cpuType = rpctarget.getKPIValue("sh linux/cputype.sh");
        if(null == cpuType || "".equals(cpuType)){
            cpuType = "-";
        }
        collResult.addKPI(unitId, "CM-00-01-001-05", cpuType.trim());

        String cpuClock = rpctarget.getKPIValue("sh linux/cpuclock.sh");
        if(null == cpuClock || "".equals(cpuClock)){
            cpuClock = "-";
        }
        collResult.addKPI(unitId, "CM-00-01-001-06", cpuClock.trim());

        return collResult.KPISet;
    }

    /**
     * CM-00-01-001-07	主机内存大小
     */
    public Vector<TblATO_KPIDETAIL> collMemSize(HashMap<String, String> params){
        init(params);
        CollBase collResult = new CollBase();
        String unitId = kbpClass + "-10:" + deviceId + "-total";

        Vector<String> vMemSize = rpctarget.getKPISet("sh linux/mem.sh");
        collResult.addKPI(unitId, "CM-00-01-001-07", vMemSize.elementAt(0));

        return collResult.KPISet;
    }

    /**
     * CM-00-01-001-08	主机操作系统版本
     */
    public Vector<TblATO_KPIDETAIL> collOsVersion(HashMap<String, String> params) {
        init(params);
        CollBase collResult = new CollBase();
        String unitId = kbpClass + "-10:" + deviceId + "-total";

        Vector<String> vOsVersion = rpctarget.getKPISet("uname -a");
        String version = split(vOsVersion.get(0), 2);
        collResult.addKPI(unitId, "CM-00-01-001-08", version);

        return collResult.KPISet;
    }



    /**
     * @author lianlian
     *
     * CM-00-01-001-11 系统网络接口IP地址
     * CM-00-01-001-12 系统网络接口物理地址
     * FM-00-01-001-03 主机网卡状态
     * CM-00-01-001-02 主机地址(服务IP)
     * CM-00-01-001-10 系统网络接口数
     * PM-00-01-900-04 系统网络接口使用带宽
     * PM-00-01-900-05 系统网络接口带宽使用率(暂无法采集)
     * PM-00-01-900-06 系统网络接口丢包率
     * PM-00-01-900-07 系统网络接口错包率
     * CM-00-01-001-21 系统网络接口速率(暂时无法采集)
     */
    public Vector<TblATO_KPIDETAIL> collInterface(HashMap<String, String> params) {
        init(params);
        CollBase collResult = new CollBase();
        String preUnitId = kbpClass + "-16:" + deviceId;
        String totalUnitId = kbpClass + "-10:" + deviceId + "-total";

        int sleepSeconds = 2;
        String networkName = "";
        String serviceIp = "";

        Map<String, Map<String, String>> networkMap = new HashMap<String, Map<String, String>>();

        // first coll
        Vector<String> vLan = rpctarget.getKPISet("/sbin/ifconfig -a");
        if (vLan == null || vLan.size() == 0) {
            return collResult.KPISet;
        }

        for (String network : vLan) {
            Map<String, String> map = null;

            if (network.indexOf("Link encap:") >= 0) {
                map = new HashMap<String, String>();
                networkName = network.substring(0, network.indexOf("Link encap:")).trim();
                String networkType = "unknown";
                if(network.indexOf("HWaddr")!=-1){
                    networkType = network.substring(network.indexOf("Link encap:") + "Link encap:".length(), network.indexOf("HWaddr")).trim();
                }else{
                    networkType = network.substring(network.indexOf("Link encap:") + "Link encap:".length()).trim();
                }
                map.put("Link encap:", networkType);
                networkMap.put(networkName, map);
            } else {
                map = networkMap.get(networkName);
            }

            if (network.indexOf("HWaddr") >= 0) {
                String macaddr = network.substring(network.indexOf("HWaddr") + "HWaddr".length()).trim();
                map.put("HWaddr", macaddr);
            }

            if (network.indexOf("inet addr") >= 0) {
                int index1 = network.indexOf("Bcast");
                int index2 = network.indexOf("Mask");
                int tmp = (index1 == -1) ? index2 : index1;
                String ipaddr = network.substring(network.indexOf(":") + 1, tmp).trim();
                map.put("inet addr", ipaddr);
            }

            if (network.indexOf("RX packets") >= 0){
                String packets = network.substring(network.indexOf("RX") + 2).trim();
                String[] temps = packets.split(" ");
                for(String temp:temps){
                    map.put("rx_" + temp.split(":")[0].trim(), temp.split(":")[1].trim());
                }
            }

            if (network.indexOf("TX packets") >= 0){
                String packets = network.substring(network.indexOf("TX") + 2).trim();
                String[] temps = packets.split(" ");
                for(String temp:temps){
                    map.put("tx_" + temp.split(":")[0].trim(), temp.split(":")[1].trim());
                }
            }

            if (network.indexOf("RX bytes") >= 0) {
                String rx_bytes = network.substring(network.indexOf("RX bytes:") + "RX bytes:".length(), network.indexOf("(")).trim();
                String tx_bytes = network.substring(network.indexOf("TX bytes:") + "TX bytes:".length(), network.lastIndexOf("(")).trim();
                map.put("rx_bytes", rx_bytes);
                map.put("tx_bytes", tx_bytes);
            }
        }


        for(String key : networkMap.keySet()) {
            Map<String, String> map = networkMap.get(key);
            if(!map.containsKey("inet addr")) {
                map.put("inet addr", "N/A");
            }
            if(!map.containsKey("HWaddr")) {
                map.put("HWaddr", "N/A");
            }

            // RX packets:0 errors:0 dropped:0 overruns:0 frame:0
            // TX packets:0 errors:0 dropped:478644 overruns:0 carrier:0

            long int_rxpackets = Long.parseLong(map.get("rx_packets"));
            long int_rxerrors = Long.parseLong(map.get("rx_errors"));
            long int_rxdropped = Long.parseLong(map.get("rx_dropped"));
            long int_rxoverruns = Long.parseLong(map.get("rx_overruns"));
            long int_rxframe = Long.parseLong(map.get("rx_frame"));

            long int_txpackets = Long.parseLong(map.get("tx_packets"));
            long int_txerrors = Long.parseLong(map.get("tx_errors"));
            long int_txdropped = Long.parseLong(map.get("tx_dropped"));
            long int_txoverruns = Long.parseLong(map.get("tx_overruns"));
            long int_txcarrier = Long.parseLong(map.get("tx_carrier"));

            if(int_rxpackets > 0 || int_rxerrors > 0 || int_rxdropped > 0 || int_rxoverruns > 0 || int_rxframe > 0 ||
                    int_txpackets > 0 || int_txerrors > 0 || int_txdropped > 0 || int_txoverruns > 0 || int_txcarrier > 0) {
                map.put("networkState", "UP");
            } else {
                map.put("networkState", "DOWN");
            }
        }

        // sleep 2 seconds
        try {
            Thread.sleep(sleepSeconds * 1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // second coll
        vLan = rpctarget.getKPISet("/sbin/ifconfig -a");
        if (vLan == null || vLan.size() == 0) {
            return collResult.KPISet;
        }

        for (String network : vLan) {
            Map<String, String> map = null;
            String key = "";
            String firstCollStr = "";
            String secondCollStr = "";

            if (network.indexOf("Link encap:") >= 0) {
                networkName = network.substring(0, network.indexOf("Link encap:")).trim();
                map = networkMap.get(networkName);
            } else {
                map = networkMap.get(networkName);
            }

            if (network.indexOf("RX packets") >= 0){
                String packets = network.substring(network.indexOf("RX") + 2).trim();
                String[] temps = packets.split(" ");
                for(String temp:temps){
                    key = "rx_" + temp.split(":")[0].trim();
                    if(map.containsKey(key)){
                        firstCollStr = map.get(key);
                        secondCollStr = temp.split(":")[1].trim();
                        map.put(key, String.valueOf(Long.parseLong(secondCollStr)-Long.parseLong(firstCollStr)));
                    }
                }
            }

            if (network.indexOf("TX packets") >= 0){
                String packets = network.substring(network.indexOf("TX") + 2).trim();
                String[] temps = packets.split(" ");
                for(String temp:temps){
                    key = "tx_" + temp.split(":")[0].trim();
                    if(map.containsKey(key)){
                        firstCollStr = map.get(key);
                        secondCollStr = temp.split(":")[1].trim();
                        map.put(key, String.valueOf(Long.parseLong(secondCollStr)-Long.parseLong(firstCollStr)));
                    }
                }
            }

            if (network.indexOf("RX bytes") >= 0) {
                String rx_bytes = network.substring(network.indexOf("RX bytes:") + "RX bytes:".length(), network.indexOf("(")).trim();
                String tx_bytes = network.substring(network.indexOf("TX bytes:") + "TX bytes:".length(), network.lastIndexOf("(")).trim();
                if(map.containsKey("rx_bytes")){
                    firstCollStr = map.get("rx_bytes");;
                    map.put("rx_bytes", String.valueOf(Long.parseLong(rx_bytes)-Long.parseLong(firstCollStr)));
                }

                if(map.containsKey("tx_bytes")){
                    firstCollStr = map.get("tx_bytes");;
                    map.put("tx_bytes", String.valueOf(Long.parseLong(tx_bytes)-Long.parseLong(firstCollStr)));
                }
            }
        }

        // create coll kpi
        for(String key : networkMap.keySet()){
            Map<String,String> map = networkMap.get(key);
            String unitId = preUnitId + "-" + Formater.neatenunitid(key);
            // ifname
            collResult.addKPI(unitId, "CM-00-01-001-19", key);
            // macaddr
            collResult.addKPI(unitId, "CM-00-01-001-12", map.get("HWaddr"));
            // ipaddr
            String inetAddr = map.get("inet addr");
            collResult.addKPI(unitId, "CM-00-01-001-11", inetAddr);
            if(!inetAddr.equals("N/A")) {
                serviceIp += inetAddr + ",";
            }
            // network status
            collResult.addKPI(unitId, "FM-00-01-001-03", map.get("networkState"));
            // network use kbps
            collResult.addKPI(unitId, "PM-00-01-900-04", Formater.formatDecimalByScale(String.valueOf((Long.parseLong(map.get("rx_bytes")) + Long.parseLong(map.get("tx_bytes")))/1024/sleepSeconds), 2));

            long long_packets = Long.parseLong(map.get("rx_packets")) + Long.parseLong(map.get("tx_packets"));
            long long_dropped = Long.parseLong(map.get("rx_dropped")) + Long.parseLong(map.get("tx_dropped"));
            long long_errors = Long.parseLong(map.get("rx_errors")) + Long.parseLong(map.get("tx_errors"));

            String dropped = "";
            String errors = "";

            if (long_packets == 0) {
                if (long_dropped > 0) {
                    dropped = "1.00";
                } else {
                    dropped = "0.00";
                }

                if (long_errors > 0) {
                    errors = "1.00";
                } else {
                    errors = "0.00";
                }
            } else {
                dropped = Formater.formatDecimalByScale(String.valueOf(long_dropped / long_packets), 2);
                errors = Formater.formatDecimalByScale(String.valueOf(long_errors / long_packets), 2);
            }

            collResult.addKPI(unitId, "PM-00-01-900-06", dropped);
            collResult.addKPI(unitId, "PM-00-01-900-07", errors);

        }

        serviceIp = serviceIp.substring(0, serviceIp.length() - 1);
        collResult.addKPI(totalUnitId, "CM-00-01-001-02", serviceIp);
        collResult.addKPI(totalUnitId, "CM-00-01-001-10", networkMap.size() + "");

        return collResult.KPISet;
    }



    /**
     * CM-00-01-001-13	系统交换区大小	总的SWAP区大小(MB)
     * PM-00-01-004-02	交换区使用百分比
     * PM-00-01-002-08	文件系统数据缓冲命中率
     */
    public Vector<TblATO_KPIDETAIL> collSwap(HashMap<String, String> params) {
        init(params);
        CollBase collResult = new CollBase();
        String unitId = kbpClass + "-10:" + deviceId + "-total";
        String memUnitId = kbpClass + "-12:" + deviceId + "-memory";

        Vector<String> vSwap = rpctarget.getKPISet("free -m");
        if(vSwap == null || vSwap.size() == 0){
            return collResult.KPISet;
        }

        for(String swap : vSwap){
            if (swap.indexOf("Swap:") > -1) {
                long swapTotal = Long.parseLong(split(swap, 1).trim());
                long swapFree = Long.parseLong(split(swap, 3).trim());
                long rate = (swapTotal - swapFree) * 100 / swapTotal;
                long swapUsed = swapTotal - swapFree;
                String sRate = Formater.formatDecimalKpivalue(String.valueOf(rate));
                collResult.addKPI(unitId, "CM-00-01-001-13", Long.toString(swapTotal));
                collResult.addKPI(unitId, "PM-00-01-004-19", Long.toString(swapUsed));
                collResult.addKPI(unitId, "PM-00-01-004-22", Long.toString(swapFree));
                collResult.addKPI(unitId, "PM-00-01-004-02", sRate);
            } else if (swap.indexOf("buffers/cache:") > -1) {
                long buffers_used = Long.parseLong(split(swap, 2).trim());
                long buffers_free = Long.parseLong(split(swap, 3).trim());
                long rate = buffers_used * 100 / (buffers_used + buffers_free);
                String sRate = Formater.formatDecimalKpivalue(String.valueOf(rate));
                collResult.addKPI(memUnitId, "PM-00-01-002-08", sRate);
            }
        }
        return collResult.KPISet;
    }

    /**
     * PM-00-01-001-01	CPU时间:空闲百分比
     * PM-00-01-001-02	CPU时间:系统百分比
     * PM-00-01-001-03	CPU时间:用户百分比
     * PM-00-01-001-04	CPU时间:等待百分比
     * PM-00-01-001-05	CPU使用率
     * PM-00-01-001-06	CPU运行队列中进程个数
     */
    public Vector<TblATO_KPIDETAIL> collCpu(HashMap<String, String> params) {
        init(params);
        logger.info("begin getCpu");
        CollBase collResult = new CollBase();
        String unitId = kbpClass + "-11:" + deviceId + "-cpu";

        Vector<String> cpuout = rpctarget.getKPISet("vmstat 2 10");
        String cpurun = cpuout.elementAt(cpuout.size() - 1);

        collResult.addKPI(unitId, "PM-00-01-001-01", collResult.split(cpurun, 14));

        collResult.addKPI(unitId, "PM-00-01-001-02", collResult.split(cpurun, 13));

        collResult.addKPI(unitId, "PM-00-01-001-03", collResult.split(cpurun, 12));

        collResult.addKPI(unitId, "PM-00-01-001-06", collResult.split(cpurun, 0));
        // CPU阻塞队列中进程个数
        collResult.addKPI(unitId, "PM-00-01-001-11", collResult.split(cpurun, 1));

        String cpuRavalue = getCpuRate(3, 30);
        collResult.addKPI(unitId, "PM-00-01-001-05", cpuRavalue);

        try {
            Vector<String> sar_cpuout = rpctarget.getKPISet("sar -u 1 3");
            for (String sar_cpurun : sar_cpuout) {
                if (sar_cpurun.indexOf("Average:") > -1) {
                    collResult.addKPI(unitId, "PM-00-01-001-04", split(sar_cpurun, 5));
                    break;
                }
            }
        } catch (Exception e) {
            logger.info("Exception while getCpu.", e);
        }

        logger.info("end collCpu");
        return collResult.KPISet;
    }

    private String getCpuRate(int times, int interval) {
        CollBase collResult = new CollBase();
        float cpu_value = 0;
        for (int i = 0; i < times; i++) {
            Vector<String> cpuout = rpctarget.getKPISet("vmstat 1 3");
            String cpurun = (String) cpuout.elementAt(cpuout.size() - 1);
            cpu_value = (100 - Integer.parseInt(collResult.split(cpurun, 14))) + cpu_value;
            try {
                Thread.sleep(interval * 1000L);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        cpu_value = cpu_value / times;
        return Formater.formatDecimalKpivalue(Float.toString(cpu_value));
    }

    /**
     * 采集内存性能指标
     */
    public Vector<TblATO_KPIDETAIL> collMemory(HashMap<String, String> params) {
        init(params);
        CollBase collResult = new CollBase();
        String unitId = kbpClass + "-12:" + deviceId + "-memory";

        Vector<String> vmstatResult = rpctarget.getKPISet("vmstat 2 2");
        if (vmstatResult == null || vmstatResult.size() == 0) {
            return collResult.KPISet;
        }

        String sVmstat = vmstatResult.get(vmstatResult.size() - 1);

        String value = "";

        value = split(sVmstat, 8);
        collResult.addKPI(unitId, "PM-00-01-002-02", Formater
                .formatDecimalKpivalue(value));

        value = split(sVmstat, 6);
        collResult.addKPI(unitId, "PM-00-01-002-03", Formater
                .formatDecimalKpivalue(value));

        value = split(sVmstat, 7);
        collResult.addKPI(unitId, "PM-00-01-002-04", Formater
                .formatDecimalKpivalue(value));



        float fMemRate = getMemoryUsage();

        logger.info("-- Memory usage=" + fMemRate);

        collResult.addKPI(unitId, "PM-00-01-002-01", Formater.formatDecimalKpivalue(fMemRate+""));

        return collResult.KPISet;
    }

    private float getMemoryUsage() {
        String sMemoryUsage = rpctarget.getKPIValue("sh linux/getMemoryUsage.sh");
        return Float.parseFloat(sMemoryUsage) * 100;
    }

    public Vector<TblATO_KPIDETAIL> collFileSystem(HashMap<String, String> params) {
        init(params);
        CollBase collResult = new CollBase();
        String preUnitId = kbpClass + "-14:" + deviceId;

        Vector<String> vFileSystem = rpctarget.getKPISet("sh linux/filesys.sh");
        if(vFileSystem == null || vFileSystem.size() == 0){
            return collResult.KPISet;
        }

        double totalSize = 0;
        for(String fileSystem : vFileSystem){
            String fileSystemName = split(fileSystem, 0);
            String rate = split(fileSystem, 4).trim();
            rate = rate.substring(0, rate.length()-1);

            String diskName = split(fileSystem, 5);
            String size = split(fileSystem, 1).trim();
            String available = split(fileSystem, 3);

            double avaliavle_tmp = Double.parseDouble(available.trim()) / 1024;

            totalSize = totalSize + Double.parseDouble(size);

            String unitId = preUnitId + "-" + Formater.neatenunitid(diskName);

            collResult.addKPI(unitId, "CM-00-01-001-16", diskName);

            collResult.addKPI(unitId, "PM-00-01-004-03", Formater.formatDecimalKpivalue(rate));

            collResult.addKPI(unitId, "PM-00-01-004-04", Formater.formatDecimalKpivalue(Double.toString(avaliavle_tmp)));

//            String lvUnitId = kbpClass + "-17:" + deviceId + "-" + fileSystemName + "_" + Formater.neatenunitid(diskName);
//
//            collResult.addKPI(lvUnitId, "CM-00-01-001-14", fileSystemName);
//
//            collResult.addKPI(lvUnitId, "CM-00-01-001-15", Formater.formatDecimalKpivalue(Double.toString(avaliavle_tmp)));
        }

        double value = Double.parseDouble(Double.toString(totalSize)) / 1000;
        collResult.addKPI(kbpClass + "-10" + ":" + deviceId + "-total",
                "CM-00-01-001-17", Formater.formatDecimalKpivalue(Double.toString(value)));

        return collResult.KPISet;
    }

    public Vector<TblATO_KPIDETAIL> collDisk(HashMap<String, String> params) {
        init(params);
        CollBase collResult = new CollBase();
        String preUnitId = kbpClass + "-13:" + deviceId;

//        Vector<String> sarResult = rpctarget.getKPISet("sar -d 5 5");

        exec(SH_COLL_DISK);
        //获取执行结果
        // 获得脚本执行结果
        List<String> result = getResult(RESULT_DISK);
        if (result == null || result.size() == 0) {
            return collResult.KPISet;
        }
        List<List<String>> list = parseResult(result, 2);

        // 获取主机名称
//            String host_name = this.getHostName();
        String deviceId = params.get("DEVICE_ID");
        if(null==deviceId || "".equals(deviceId.trim())){
            // 获取主机名称 : uname -a
            List<String> vHostName = list.get(0);
            deviceId = split(vHostName.get(0), 1);
        }
        // 得到unit_id中使用的主机名称
//        String neat_host_name = Formater.neatenunitid(deviceId);

        List<String> diskV = list.get(1);

        Set<String> diskSet = new HashSet<String>();

        for(String disk : diskV){
            if (disk.indexOf("Average") < 0)
                continue;

            if (disk.indexOf("DEV") != -1)
                continue;

            String diskName = split(disk, 1);
            diskSet.add(diskName);

            String neatDiskName = Formater.neatenunitid(diskName);

            String unitId = preUnitId + "-" + neatDiskName;

            collResult.addKPI(unitId, "CM-00-01-001-20", diskName);
            logger.info("***unitId="+unitId);
            logger.info("***diskName="+diskName);
            collResult.addKPI(unitId, "FM-00-01-001-02", "CLAIMED");
            collResult.addKPI(unitId, "PM-00-01-003-01", split(disk, 2));
            logger.info("***PM-00-01-003-01="+split(disk, 2));
            collResult.addKPI(unitId, "PM-00-01-003-04", split(disk, 3));
            logger.info("***PM-00-01-003-04="+split(disk, 3));
            collResult.addKPI(unitId, "PM-00-01-003-05", split(disk, 4));
            logger.info("***PM-00-01-003-05="+split(disk, 4));
            collResult.addKPI(unitId, "PM-00-01-003-03", split(disk, 9));
            logger.info("***PM-00-01-003-03="+split(disk, 9));
            collResult.addKPI(unitId, "PM-00-01-003-02", split(disk, 6));
            logger.info("***PM-00-01-003-02="+split(disk, 6));
            // 磁盘I/O速率
            double kbps = 0;
            try {
                // 每秒读扇区的数量
                String sRdSec = split(disk, 3);
                // 每秒写扇区的数量
                String sWrSec = split(disk, 4);

                kbps = (Double.parseDouble(sRdSec) + Double.parseDouble(sWrSec)) ;
            } catch (Exception e) {
                kbps = -1;
                logger.error("Error", e);
            }
            String sKbps = Formater.formatDecimalKpivalue(kbps + "");
            // 磁盘命令时延
            String await = split(disk, 7);

            // PM-00-01-003-16每秒磁盘I/O命令数量 数量
            //PM-00-01-003-07磁盘命令时延
            collResult.addKPI(unitId, "PM-00-01-003-16", sKbps);
            logger.info("***sKbps="+sKbps);
            collResult.addKPI(unitId, "PM-00-01-003-07", await);
            logger.info("***await="+await);

        }
        return collResult.KPISet;
    }

    public Vector getProcessTop10(HashMap<String, String> params) {
        logger.info("begin getProcessTop10");
        CollBase collResult = new CollBase();

        // 获得脚本执行结果
        exec(SH_COLL_PROCESS);
        List<String> result = getResult(RESULT_PROCESS);
        if (result == null || result.size() == 0) {
            return collResult.KPISet;
        }
        List<List<String>> list = parseResult(result, 3);

        // 获取主机名称
        deviceId = params.get("DEVICE_ID");
        if(null==deviceId || "".equals(deviceId.trim())){
            // 获取主机名称 : uname -a
            List<String> vHostName = list.get(0);
            deviceId = split(vHostName.get(0), 1);
        }
        try {
            logger.info("begin getProcessTop10Mem");
            String pro_PRE_UNITID = kbpClass + "-27:" + deviceId;
            List<String> processMems = list.get(1);
            if (processMems == null || processMems.equals("") || processMems.equals("null")) {
                //
            } else {
                int i = 1;
                for (String processInfo : processMems) {
                    String processUser = split(processInfo, 0);
                    String processPid = split(processInfo, 1);
                    String processCpu = split(processInfo, 2);
                    String processMem = split(processInfo, 3);
                    String processCmd = split(processInfo, 10);
                    System.out.println(processUser + "#@#" + processPid + "#@#" + processCpu + "#@#" + processMem);
                    String unitId = pro_PRE_UNITID + "-" + i++;
                    // 进程用户 CM-00-01-005-06
                    collResult.addKPI(unitId, "CM-00-01-005-06", processUser);
                    // 进程ID CM-00-01-005-01
                    collResult.addKPI(unitId, "CM-00-01-005-01", processPid);
                    // 进程占用CPU百分比 PM-00-01-005-10
                    collResult.addKPI(unitId, "PM-00-01-005-10", processCpu);
                    // 进程占用MEM百分比 PM-00-01-005-11
                    collResult.addKPI(unitId, "PM-00-01-005-11", processMem);
                    // 进程指令行 CM-00-01-005-08
                    collResult.addKPI(unitId, "CM-00-01-005-08", processCmd);
                    // 更新时间 CM-00-03-002-10
                    collResult.addKPI(unitId, "CM-00-03-002-10", Formater.datetimeToString(new Date()));
                }
            }
        } catch (Exception e) {
            logger.error("getProcessTop10Mem has error", e);
        }
        try {
            logger.info("begin getProcessTop10CPU");
            String pro_PRE_UNITID = kbpClass + "-28:" + deviceId;
            List<String> processCPUs = list.get(2);
            if (processCPUs == null || processCPUs.equals("") || processCPUs.equals("null")) {
                //
            } else {
                int i = 1;
                for (String processInfo : processCPUs) {
                    String processUser = split(processInfo, 0);
                    String processPid = split(processInfo, 1);
                    String processCpu = split(processInfo, 2);
                    String processMem = split(processInfo, 3);
                    String processCmd = split(processInfo, 10);
                    System.out.println(processUser + "#@#" + processPid + "#@#" + processCpu + "#@#" + processMem);
                    String unitId = pro_PRE_UNITID + "-" + i++;
                    // 进程用户 CM-00-01-005-06
                    collResult.addKPI(unitId, "CM-00-01-005-06", processUser);
                    // 进程ID CM-00-01-005-01
                    collResult.addKPI(unitId, "CM-00-01-005-01", processPid);
                    // 进程占用CPU百分比 PM-00-01-005-10
                    collResult.addKPI(unitId, "PM-00-01-005-10", processCpu);
                    // 进程占用MEM百分比 PM-00-01-005-11
                    collResult.addKPI(unitId, "PM-00-01-005-11", processMem);
                    // 进程指令行 CM-00-01-005-08
                    collResult.addKPI(unitId, "CM-00-01-005-08", processCmd);
                    // 更新时间 CM-00-03-002-10
                    collResult.addKPI(unitId, "CM-00-03-002-10", Formater.datetimeToString(new Date()));
                }
            }
        } catch (Exception e) {
            logger.error("getProcessTop10CPU has error", e);
        }
        logger.info("end getProcessTop10");
        return collResult.getKPISet();
    }

    public Vector getProcessByKey(HashMap<String, String> params) {
        logger.info("begin getProcessByKey");
        CollBase collResult = new CollBase();
        deviceId = params.get("DEVICE_ID");
        String keywords = params.get("KEYWORDS");
        String[] keywordsList = keywords.split("#");
        // 获得脚本执行结果
        exec(SH_COLL_KEY_PROCESS);
        List<String> result = getResult(RESULT_KEY_PROCESS);
        if (result == null || result.size() == 0) {
            return collResult.KPISet;
        }
        List<List<String>> list = parseResult(result, 2);

        // 获取主机名称
        if(null==deviceId || "".equals(deviceId.trim())){
            // 获取主机名称 : uname -a
            List<String> vHostName = list.get(0);
            deviceId = split(vHostName.get(0), 1);
        }
        try {
            logger.info("begin getProcess");
            String pro_PRE_UNITID = kbpClass + "-25:" + deviceId;
            List<String> processInfos = list.get(1);
            if (processInfos == null || processInfos.equals("") || processInfos.equals("null")) {
                //
            } else {

                int i = 1;
                for (String processInfo : processInfos) {
                    for(String key : keywordsList){
                        if(StringUtils.contains(processInfo, key)){
                            String processUser = split(processInfo, 0);
                            String processPid = split(processInfo, 1);
                            String processCpu = split(processInfo, 2);
                            String processMem = split(processInfo, 3);
                            String processCmd = split(processInfo, 10);
                            processCmd = processCmd+StringUtils.substringAfter(processInfo, processCmd);
                            System.out.println(processUser + "#@#" + processPid + "#@#" + processCpu + "#@#" + processMem);
                            String unitId = pro_PRE_UNITID + "-" + i++;
                            // 进程用户
                            collResult.addKPI(unitId, "CM-00-01-005-06", processUser);
                            // 进程ID
                            collResult.addKPI(unitId, "CM-00-01-005-01", processPid);
                            // 进程占用CPU百分比
                            collResult.addKPI(unitId, "PM-00-01-005-10", processCpu);
                            // 进程占用MEM百分比
                            collResult.addKPI(unitId, "PM-00-01-005-11", processMem);
                            // 进程指令行
                            collResult.addKPI(unitId, "CM-00-01-005-08", processCmd);
                            // 更新时间
                            collResult.addKPI(unitId, "CM-00-03-002-10", Formater.datetimeToString(new Date()));
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("getProcessTop10Mem has error", e);
        }
        logger.info("end getProcessTop10");
        return collResult.getKPISet();
    }
    public Vector getConfig(HashMap<String, String> params) {
        logger.info("begin getConfig");
        CollBase collResult = new CollBase();
        deviceId = params.get("DEVICE_ID");
        // 获得脚本执行结果
        exec(SH_COLL_CONFIG);
        List<String> result = getResult(RESULT_CONFIG);
        if (result == null || result.size() == 0) {
            return collResult.KPISet;
        }
        List<List<String>> list = parseResult(result, 3);

        // 获取主机名称
        if(null==deviceId || "".equals(deviceId.trim())){
            // 获取主机名称 : uname -a
            List<String> vHostName = list.get(0);
            deviceId = split(vHostName.get(0), 1);
        }
        String unitId = kbpClass + "-10:" + deviceId+"-total";
        try {
            logger.info("begin NTP");
            List<String> NTPInfos = list.get(1);
            if (NTPInfos != null && NTPInfos.size()>0) {
                // 网络时钟状态
                collResult.addKPI(unitId, "FM-00-01-001-13", NTPInfos.get(0));
            }
        } catch (Exception e) {
            logger.error("getNTP has error", e);
        }
        try{
            logger.info("=========================version start=========================");
            List<String> version = list.get(2);
            if(version != null && version.size() > 0){
                //操作系统维护版本
                collResult.addKPI(unitId, "CM-00-01-001-62", version.get(0).trim());
            }
            logger.info("=========================version end=========================");
        } catch (Exception e) {
            logger.error("Exception while get version!", e);
        }
        logger.info("end getConfig");
        return collResult.getKPISet();
    }

    /**
     * 网络信息
     * @param params
     * @return
     */
    public Vector<TblATO_KPIDETAIL> getNet(HashMap<String, String> params) {
        logger.info("[Linux COLL]begin getNet");
        // 保存采集结果,并返回值
        CollBase collResult = new CollBase();
        List<String> result = null;
        List<List<String>> list = null;

        exec(SH_COLL_NET);
        // 获得脚本执行结果
        result = getResult(RESULT_NET);
        if(result == null || result.size() == 0){
            return collResult.KPISet;
        }
        // 分隔每个命令的执行结果
        list = parseResult(result, 3);


        // 获取主机名称
        deviceId = params.get("DEVICE_ID");
        if(null==deviceId || "".equals(deviceId.trim())){
            List<String> vHostName = list.get(0);
            deviceId = split(vHostName.get(0), 1);
        }
        // 得到unit_id中使用的主机名称
        String neat_host_name = Formater.neatenunitid(deviceId);
        String unitId = kbpClass + "-10:"+neat_host_name+"-total";
        try{
            List<String> netResult = list.get(1);
            int fin_wait_number =0;
            int wait_number =0;
            int established_number =0;
            for(String tempNet : netResult){
                if(tempNet.contains("FIN")){
                    fin_wait_number++;
                }else if(tempNet.contains("WAIT")){
                    wait_number++;
                }else if(tempNet.contains("ESTABLISHED")){
                    established_number++;
                }
            }
            // 失效网络数
            collResult.addKPI(unitId, "PM-00-01-006-11", Integer.toString(fin_wait_number));
            // 等待网络数
            collResult.addKPI(unitId, "PM-00-01-006-12",Integer.toString(wait_number));
            // 连接网络数
            collResult.addKPI(unitId, "PM-00-01-006-13",Integer.toString(established_number));

            //网络接收速率及发送速率
            List<String> netRate = list.get(2);//如果linux操作系统是英文的,则用以下命令sar -n DEV 1 10 | sed  -n '/Average/p'
            if(null==netRate || netRate.size()<1){
                throw new Exception("[COLL] sar -n DEV 1 10  |grep ':' : null");
            }

            boolean netflag = false;
            for(int i=0;i<netRate.size();i++){
                String vs=netRate.get(i).toString();
                if(vs.indexOf("Average")>-1){
                    netflag = true;//linux操作系统是英文的
                }
            }
            String rxValue = ""; // 临时变量
            String txValue = ""; // 临时变量
            if(netflag){//如果linux操作系统是英文的
                //网络接收速率
                rxValue = this.get_rxValue(netRate);
                collResult.addKPI(unitId,"PM-00-01-006-14",rxValue);
                //网络发送速率
                txValue = this.get_txValue(netRate);
                collResult.addKPI(unitId,"PM-00-01-006-15",txValue);
            }else {//linux中文操作系统适合用此命令 sar -n DEV 1 10  |grep ':'
                exec("getLinuxNetnet.sh");
                // 获得脚本执行结果
                result = getResult("linuxNetResultnet");
                // 分隔每个命令的执行结果
                list = parseResult(result, 3);
                netRate = list.get(2);
                //网络接收速率
                rxValue = this.get_rxValue(netRate);
                collResult.addKPI(unitId,"PM-00-01-006-14",rxValue);
                //网络发送速率
                txValue = this.get_txValue(netRate);
                collResult.addKPI(unitId,"PM-00-01-006-15",txValue);
            }


        } catch (Exception e){
            logger.error("[HP COLL] Exception while execute getNet",e);
        }

        return collResult.getKPISet();
    }
    private String  get_rxValue(List<String> netRate){
        double rxRate = 0;
        //计算eth0  eth1  eth2 等端口之和
        for (int i = netRate.size() - 1; i >= 2; i--) {//不要读取头两行title
            String rx = netRate.get(i);
            rxRate += Double.parseDouble(split(rx, 4));
        }
        rxRate=rxRate*8;//单位从kBps转换为kbps
        return Formater.formatDecimalKpivalue(Double.toString(rxRate));
    }
    private String  get_txValue(List<String> netRate){
        double txRate = 0;
        //计算eth0  eth1  eth2 等端口之和
        for (int i = netRate.size() - 1; i >= 2; i--) {//不要读取头两行title
            String tx = netRate.get(i);
            txRate += Double.parseDouble(split(tx, 5));
        }
        txRate=txRate*8;//单位从kBps转换为kbps
        return Formater.formatDecimalKpivalue(Double.toString(txRate));
    }

    private String getHostName(HashMap<String, String> params) {
        deviceId = params.get("DEVICE_ID");
        if (null == deviceId || "".equals(deviceId) || "null".equals(deviceId)) {
            String deviceId = rpctarget.getKPISet("uname -a").elementAt(0);
            deviceId = split(deviceId, 1);
        }

        return deviceId;
    }

    /**
     * 采集CPU不可用率(被hapervisor占用的CPU利用率,用与云监控)
     */
    public Vector<TblATO_KPIDETAIL> getUnavailableCpu(HashMap<String, String> params){
        init(params);
        CollBase collResult = new CollBase();
        // 进程关键字
        String processKey = params.get("PROCESS_KEY");
        String cmd = "sh linux/specprocess.sh " + processKey;
        Vector<String> vResult = rpctarget.getKPISet(cmd);
        if(vResult == null || vResult.size() == 0){
            return collResult.KPISet;
        }

        double virtualCpuUsage = 0;
        for(String line : vResult){
            String processUsage = split(line, 2);
            virtualCpuUsage += Double.parseDouble(processUsage);
        }

        // 设置unitId,kpiId
        String unitId = kbpClass + "-10:" + deviceId + "-total";
        collResult.addKPI(unitId, "PM-00-01-800-06", Formater.formatDecimalKpivalue(virtualCpuUsage+""));

        return collResult.KPISet;
    }

    /**
     * 采集不可用内存大小(被hapervisor占用的内存大小,用与云监控),单位KB
     * qemu为进程关键字,本次测试使用
     */
    public Vector<TblATO_KPIDETAIL> getUnavailableMem(HashMap<String, String> params){
        init(params);
        CollBase collResult = new CollBase();
        // 进程关键字
        String processKey = params.get("PROCESS_KEY");
        String cmd = "sh linux/specprocess.sh " + processKey;
        Vector<String> vResult = rpctarget.getKPISet(cmd);
        if(vResult == null || vResult.size() == 0){
            return collResult.KPISet;
        }

        double virtualCpuUsage = 0;
        for(String line : vResult){
            String processUsage = split(line, 4);
            virtualCpuUsage += Double.parseDouble(processUsage);
        }

        // 设置unitId,kpiId
        String unitId =kbpClass + "-10:" + deviceId + "-total";
        collResult.addKPI(unitId, "PM-00-01-800-07", Formater.formatDecimalKpivalue(virtualCpuUsage+""));

        return collResult.KPISet;
    }

    /**
     * 采集宿主机的IO性能指标(用于云监控),包括
     * 磁盘命令时延
     * 每秒磁盘I/O命令数量
     * 磁盘I/O速率
     */
    public Vector<TblATO_KPIDETAIL> collIO(HashMap<String, String> params) {
        init(params);
        CollBase collResult = new CollBase();
        String interval = params.get("");
        String deviceId = Formater.neatenunitid(getHostName(params));
        String preUnitId = "10-10-24-30:" + deviceId + "-";

        String command = "sar -pd 1 3";

        Vector<String> vResult = rpctarget.getKPISet(command);

        for (String line : vResult) {
            if (line.indexOf("Average:") < 0) {
                continue;
            }

            if (line.indexOf("DEV") > 0) {
                continue;
            }

            String diskName = split(line, 1);
            String neatDiskName = Formater.neatenunitid(diskName);

            String unitId = preUnitId + "-" + neatDiskName;

            // 每秒钟磁盘I/0命令的数量
//			String tps = split(line, 2);

            // 磁盘I/O速率
            double kbps = 0;
            try{
                // 每秒读扇区的数量
                String sRdSec = split(line, 3);
                // 每秒写扇区的数量
                String sWrSec = split(line, 4);

                kbps = (Double.parseDouble(sRdSec) + Double.parseDouble(sWrSec)) / 2;
            }catch (Exception e) {
                kbps = -1;
                logger.error("Error", e);
            }
            String sKbps = Formater.formatDecimalKpivalue(kbps + "");

            // 磁盘命令时延
            String await = split(line, 7);

			/*collResult.addKPI(unitId, "PM-00-00-001-01", diskName, interval);
			collResult.addKPI(unitId, "PM-00-00-001-02", tps, interval);*/
            collResult.addKPI(unitId, "PM-00-00-001-03", sKbps, interval);
            collResult.addKPI(unitId, "PM-00-00-001-03", await, interval);
        }
        return collResult.KPISet;
    }

    public void  getHapervisor(HashMap<String, String> params){
        init(params);
        if (null == params) {
            params = new HashMap<String, String> ();
        }
        String deviceId = Formater.neatenunitid(getHostName(params));
        params.put("PHYSICALDEVICEID", deviceId);
        VirtualScheduleManager.refreshVirtualSchedule(params);
    }

    /**
     * 采集虚拟机信息(kbp:10-10-24-40)
     * 虚拟机名称         CM-00-01-040-10
     * 虚拟机配置OS类型    CM-00-01-040-11
     * 虚拟机配置CPU个数   CM-00-01-040-12
     * 虚拟机配置内存大小   CM-00-01-040-13
     * 虚拟机状态         FM-00-01-040-10
     *
     * @author lianlian
     * @param params
     * @return
     */
    public Vector<TblATO_KPIDETAIL> collVMInfo(HashMap<String, String> params) {
        init(params);
        CollBase collResult = new CollBase();
        String uri = params.get("URI");
        Connect connect = null;

        String deviceId = Formater.neatenunitid(getHostName(params));
        String preUnitId = "10-10-24-40:" + deviceId;
        String unitId = "";

        try {
            connect = new Connect(uri);
            int domainIds[] = connect.listDomains();
            for (int domainId : domainIds) {
                Domain domain = connect.domainLookupByID(domainId);
                DomainInfo domainInfo = domain.getInfo();
                String vmName = domain.getName();
                unitId = preUnitId + "-" + vmName;
                collResult.addKPI(unitId, "CM-00-01-040-10", vmName);
                collResult.addKPI(unitId, "CM-00-01-040-11", domain.getOSType());
                // collResult.addKPI(unitId, "CM-00-01-040-12", domain.getVcpusInfo().length + "");
                collResult.addKPI(unitId, "CM-00-01-040-12", domainInfo.nrVirtCpu + "");
                collResult.addKPI(unitId, "CM-00-01-040-13", (domain.getMaxMemory() / 1024) + "");
                collResult.addKPI(unitId, "FM-00-01-040-10", domainInfo.state.toString());
            }

            connect.close();
        } catch (LibvirtException e) {
            e.printStackTrace();
            return collResult.KPISet;
        }
        return collResult.KPISet;
    }

    /**
     * 监控目录大小
     * @param params
     * @return
     */
    public Vector<TblATO_KPIDETAIL> getFileChange(HashMap<String, String> params) {
        logger.info("Begin getFileChange...");
        logger.info(params.toString());
        CollBase collResult = new CollBase();
        // 执行脚本
        exec(SH_COLL_FILE);
        // 获得脚本执行结果
        List<String> result = getResult(RESULT_FILE);
        if(null == result || result.isEmpty()){
            return collResult.KPISet;
        }
        List<List<String>> list = parseResult(result);
        String deviceId = params.get("DEVICE_ID");
        String UNIT_ID = params.get("KBP_CLASS");
        if(null == deviceId || "".equals(deviceId.trim())){
            // 获取主机名称 : uname -a
            List<String> vHostName = list.get(0);
            deviceId = split(vHostName.get(0), 1);
        }
        try {
            //得到filechange UnitId
            String filechangeUnitId = UNIT_ID + "-20:" +  deviceId + "-";

            /**
             * 分析传入的文件绝对路径参数
             * 如果传入的参数中是路径则采集该路径下所有的文件
             * 如果传入的参数中包含文件名则采集该文件
             */
            for(int n=2;n <list.size();n++){
                List<String> paths = list.get(n);
                if(paths.size()<2) continue;//如果某条指令结果不正常,跳过;
                String p = paths.get(0);
                //文件名称
                collResult.addKPI(filechangeUnitId+p, "CM-10-10-020-01", p);
                Boolean isChange = checkFileChange(paths,p,deviceId);
                //变动部分有结果,则生成告警指标
                collResult.addKPI(filechangeUnitId+ p, "FM-10-10-020-01",isChange.toString());

            }

        }catch (Exception e) {
            logger.error("Exception while get fileChange!",e);
        }
        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 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();
    }

    /**
     * 解析每个命令的执行结果
     *
     * @throws
     * @since Ver 1.1
     */
    private List<List<String>> parseResult(List<String> result) {
        //计算结果有多少个分割线分割的集合
        int num =1;
        for (String line : result) {
            if (line.trim().equals(SPLIT_LINE) || line.trim().endsWith(SPLIT_LINE)){
                num++;
            }
        }

        List<List<String>> list = new ArrayList<List<String>>();
        for (int i = 0; i < num; i++) {
            list.add(new ArrayList<String>());
        }

        int i = 0;
        for (String line : result) {
            if (line.trim().equals(SPLIT_LINE)) {
                i++;
                continue;
            }else if(line.trim().endsWith(SPLIT_LINE)){
                line = line.replace(SPLIT_LINE,"");
                list.get(i).add(line);
                i++;
            }else{
                list.get(i).add(line);
            }
        }
        return list;
    }

//    public static void main(String[] args) {
//        HashMap<String, String > params = new HashMap<String, String>();
//        params.put("KEYWORDS", "hald-addon-acpi");
//        CollLinuxWithCMDByCron coll = new CollLinuxWithCMDByCron();
//        Vector<TblATO_KPIDETAIL> result = coll.getProcessByKey(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);
//        }
//    }
//    public static void main(String[] args) {
//        CollLinuxWithCMDByCron coll = new CollLinuxWithCMDByCron();
//        ArrayList list =new ArrayList();
//        list.add(0,"Average:        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s");
//        list.add(1,"Average:           lo     17.05     17.05      4.79      4.79      0.00      0.00      0.00");
//        list.add(2,"Average:         eth0    212.66    218.05     18.79     19.96      0.00      0.00      2.69");
//        list.add(3,"Average:         eth1      0.00      0.00      0.00      0.00      0.00      0.00      0.00");
//        coll.get_rxValue(list);
//
//    }
    public static void main(String[] args) {
        // create an empty Vector vec with an initial capacity of 4
        Vector<String> vec = new Vector<String>(4);

        // use add() method to add elements in the vector
        vec.add("4 4 4");
        vec.add("Average:        IFACE   rxpck/s   txpck/s    rxkB/s    txkB/s   rxcmp/s   txcmp/s  rxmcst/s");
        vec.add("2");
        vec.add("1");

        // let us check the existence of number 4 in the vector
        for(int i=0;i<vec.size();i++){
            String vs=vec.get(i);
            if(vs.indexOf("Average")>-1){
                System.out.println("Checking the existence of number 4 :- Average");
            }
        }
        //System.out.println("Checking the existence of number 4 :- "+vec.contains("4"));
    }

}