CollIBMWithCMD.java 56.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 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
package com.sitech.ismp.coll.host;

import com.sitech.ismp.coll.CollBase;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.util.Formater;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

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

public class CollIBMWithCMD {
	static Logger logger = Logger.getLogger("COLL");
	
	static final String RESULT_PATH = "../result/";
	static final String SH_COLL_CPU = "getCpu.sh";
	static final String RESULT_CPU = "cpuResult";
	
	static final String SH_COLL_MEMORY = "getMemory.sh";
	static final String RESULT_MEMORY = "memResult";
	
	static final String SH_COLL_CONFIG = "getConfig.sh";
	static final String RESULT_CONFIG = "configResult";
	
	static final String SH_COLL_DISK = "getDisk.sh";
	static final String RESULT_DISK = "diskResult";
	
	static final String SH_COLL_FILE_SYSTEM = "getFileSystem.sh";
	static final String RESULT_FILE_SYSTEM = "fileSystemResult";

	static final String SH_COLL_PROCESS = "getIBMProcessTop10.sh";
	static final String RESULT_PROCESS = "IBMProcessTop10Result";

	static final String SH_COLL_HARDWARE = "getIBMHardware.sh";
	static final String RESULT_HARDWARE = "errDiffResult";

	static final String SH_COLL_KEY_PROCESS = "getIBMProcess.sh";
	static final String RESULT_KEY_PROCESS = "IBMProcessResult";

	static final String SH_COLL_NET = "getIBMNet.sh";
	static final String RESULT_NET = "ibmNetResult";

    static final String SH_COLL_FILE = "getFile.sh";
    static final String RESULT_FILE = "fileResult";
	/** 分隔线 */
	static final String SPLIT_LINE = "*******************************************************************************************#";

	public Vector<TblATO_KPIDETAIL> getConfig(HashMap<String, String> params) {
		CollBase collResult = new CollBase();
		String deviceId = params.get("HOST_NAME");
		String totalUnitId = "10-10-20-10:" + deviceId + "-total";
        try{
            // 主机类型
            collResult.addKPI(totalUnitId, "CM-00-01-001-03", "IBM");

            // 执行脚本
            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, 19);
            // 主机名称(uname -a)
            List<String> unameResult = list.get(0);
            // CPU个数(prtconf |grep 'Number Of Processors:')
            List<String> cpuNumResult = list.get(1);
            // CPU类型(sar -b 2 2)
            List<String> cpuTypeResult = list.get(2);
            // 内存大小(prtconf |grep 'Good Memory Size:')
            List<String> memSizeResult = list.get(3);
            // CPU主频(prtconf |grep 'Processor Clock Speed:')
            List<String> cpuClockResult = list.get(4);
            // 操作系统版本(oslevel)
            List<String> osVersionResult = list.get(5);
            // 主机内置盘大小
            List<String> pvResult = list.get(6);
            // 逻辑卷
    //		List<String> lvResult = list.get(7);
            // 集群(lssrc -a | grep cluster)
            List<String> clusterResult = list.get(8);
            // 交换空间(lsps -s | grep -v 'Paging Space' | awk '{print $1}')
            List<String> swapResult = list.get(9);
            // 网卡(netstat -in | grep 127.0.0.1 | awk '{print $1}' | read loopbackName
            //     netstat -in | grep -v Mtu | grep -v 127.0.0.1 | grep -v '*' | grep -v $loopbackName)
            List<String> netcardResult = list.get(10);
            // 文件系统
            List<String> fileSystemResult = list.get(11);
            // 系统启动时间
            List<String> upTime = list.get(12);
            // LV状态
            List<String> LVInfos = list.get(13);
            // CPU状态
            List<String> CPUInfos = list.get(14);
            // 操作系统维护版本
            List<String> maintainVersion = list.get(15);
            //syslog status
            List<String> syslogStatus = list.get(16);
            //ntp status
            List<String> ntpStatus = list.get(17);
            //主机序列号
            List<String> machineSerialNum = list.get(18);

            if(unameResult != null && unameResult.size() > 0){
                // 主机名称
                String hostName = unameResult.get(0).trim();
                collResult.addKPI(totalUnitId, "CM-00-01-001-01", hostName);
            }

            if(cpuNumResult != null && cpuNumResult.size() > 0){
                // CPU个数
                String cpuNum = split(cpuNumResult.get(0), 3);
                collResult.addKPI(totalUnitId, "CM-00-01-001-04", cpuNum);
            }

            if(cpuTypeResult != null && cpuTypeResult.size() > 0){
                // CPU类型(sar -b 2 2)
                String cpuType = split(cpuTypeResult.get(0), 2).trim();
                collResult.addKPI(totalUnitId, "CM-00-01-001-05", cpuType);
            }

            if(memSizeResult != null && memSizeResult.size() > 0){
                // 内存大小
                String memSize = split(memSizeResult.get(0), 3);
                collResult.addKPI(totalUnitId, "CM-00-01-001-07", memSize);
            }

            if(cpuClockResult != null && cpuClockResult.size() > 0){
                // CPU主频(prtconf |grep 'Processor Clock Speed:')
                collResult.addKPI(totalUnitId, "CM-00-01-001-06", split(cpuClockResult.get(0), 3));
            }

            if(osVersionResult != null && osVersionResult.size() > 0){
                // 操作系统版本(oslevel)
                collResult.addKPI(totalUnitId, "CM-00-01-001-08", split(osVersionResult.get(0), 0));
            }

            if(pvResult != null && pvResult.size() > 0){
                // 主机内置盘大小
                int size = 0;
                for(String elem : pvResult){
                    size += Integer.parseInt(split(elem,1).trim());
                }
                collResult.addKPI(totalUnitId, "CM-00-01-001-09", String.valueOf(size));
            }

    //		if(lvResult != null && lvResult.size() > 0){
    //			// 逻辑卷名称与大小
    //			for(String line : lvResult){
    //				String lvName = split(line, 0);
    //				String lvSize = split(line, 1);
    //				String lvUnitId = "10-10-20-17:" + deviceId + "-" + Formater.neatenunitid(lvName);
    //				collResult.addKPI(lvUnitId, "CM-00-01-001-14", lvName);
    //				collResult.addKPI(lvUnitId, "CM-00-01-001-15", lvSize);
    //			}
    //		}

            /**
             * $ lssrc -a | grep cluster
             * trmgrES		cluster		381252		active
             * clinfoES		cluster		225346		active
             */
            if(clusterResult != null && clusterResult.size() > 0){
                // 集群状态
                for(String line : clusterResult){
                    String clusterName = collResult.split(line, 0);
                    String clusterState = collResult.split(line, 3);

                    // cluster信息
                    String clusterUnitId = "10-10-20-18:" + deviceId + "-" + Formater.neatenunitid(clusterName);

                    if (clusterState == null || "".equals(clusterState)) {
                        clusterState = "-";
                    }
                    // 集群名称
                    collResult.addKPI(clusterUnitId, "CM-00-01-001-18", clusterName);
                    // 集群状态
                    collResult.addKPI(clusterUnitId, "FM-00-01-001-04", clusterState);
                }
            }

            if(swapResult != null && swapResult.size() > 0){
                // 交换空间大小(lsps -s | grep -v 'Paging Space' | awk '{print $1}')
                // 单位: MB
                String swapSize = split(swapResult.get(0), 0).trim();
                swapSize = swapSize.substring(0, swapSize.length() - 2); // 去掉后面的
                // 交换分区大小
                collResult.addKPI(totalUnitId, "CM-00-01-001-13", swapSize);
            }


//            // 网卡(netstat -in | grep 127.0.0.1 | awk '{print $1}' | read loopbackName
//            //     netstat -in | grep -v Mtu | grep -v 127.0.0.1 | grep -v '*' | grep -v $loopbackName)
//            logger.debug("[NETWORK] Command's result's size:" + netcardResult.size());
//            if(netcardResult != null && netcardResult.size() > 0){
//                logger.debug("[NETWORK] Command's result's size:" + netcardResult.size());
//                Set<String> lancardSet = new HashSet<String>();
//                String serviceIp = "";
//                long lan_ipkts_total = 0;
//                long lan_opkts_total = 0;
//                for(String line : netcardResult){
//                    String lanName = split(line, 0).trim();
//                    String network = split(line, 2).trim();
//                    lan_ipkts_total = lan_ipkts_total+ Long.parseLong(split(line, 4));
//                    lan_opkts_total = lan_opkts_total+ Long.parseLong(split(line, 6));
//                    // id 使用 -16 网络
//                    String netUnitId = "10-10-20-16:" + deviceId + "-" + Formater.neatenunitid(lanName);
//
//                    // 如果含有link,则为物理地址,否则为本地地址
//                    if (network.indexOf("link") > -1 && (network.indexOf("*")) == -1) {
//                        // 物理地址
//                        String macAddress = split(line, 3);
//                        collResult.addKPI(netUnitId, "CM-00-01-001-12", macAddress);
//                    } else {
//                        String ipAddress = split(line, 3);
//                        collResult.addKPI(netUnitId, "CM-00-01-001-11", ipAddress);
//                        serviceIp = serviceIp + "," + ipAddress;
//                    }
//                    lancardSet.add(lanName);
//                }
//                //网卡总出包数
//                collResult.addKPI(totalUnitId, "PM-00-01-001-17", String.valueOf(lan_opkts_total));
//                //网卡总入包数
//                collResult.addKPI(totalUnitId, "PM-00-01-001-18", String.valueOf(lan_ipkts_total));
//
//                // 主机(服务)地址 CM-00-01-001-02, 将所有ip地址累加
//                collResult.addKPI(totalUnitId, "CM-00-01-001-02", serviceIp.substring(1, serviceIp.length()));
//                // KPI: CM-00-01-001-10 系统网络接口数
//                collResult.addKPI(totalUnitId, "CM-00-01-001-10", String.valueOf(lancardSet.size()));
//            }


            // 文件系统
            if(fileSystemResult != null && fileSystemResult.size() > 0){
                long totalSize= 0; // 文件系统总空间,单位:M
                for(String line : fileSystemResult){
                    String fileSystemName = split(line, 6).trim();
                    String fileSystemUnitId = "";
                    if (fileSystemName != null && fileSystemName.equals("/")) {
                        fileSystemUnitId = "10-10-20-14:" + deviceId + "-//" ;
                    } else {
                        fileSystemUnitId = "10-10-20-14:" + deviceId + "-" + Formater.neatenunitid(fileSystemName) ;
                    }
                    collResult.addKPI(fileSystemUnitId, "CM-00-01-001-16", fileSystemName);

                    String size = split(line, 1).trim();
                    size = (size == null || size.length() == 0 || size.equals("-")) ? "0" : size;
                    totalSize = totalSize + Long.parseLong(size);
                }

                collResult.addKPI(totalUnitId, "CM-00-01-001-17", Formater.formatDecimalKpivalue(String.valueOf(totalSize / 1024)));
            }

            if(upTime != null && upTime.size() > 0){
                // 系统运行时长 PM-20-20-001-52
                String uptime = upTime.get(0).trim();
                collResult.addKPI(totalUnitId, "PM-20-20-001-52", uptime);
            }

            // 逻辑卷状态
            if(LVInfos != null && LVInfos.size() > 0){
                for(String LVInfo : LVInfos){
                    String LVName = split(LVInfo, 0).trim();
                    String LVState = split(LVInfo, 5).trim();
                    String LVUnitId = "10-10-20-28:" + deviceId + "-" + Formater.neatenunitid(LVName) ;
                    //逻辑卷名称
                    collResult.addKPI(LVUnitId, "CM-00-01-001-57", LVName);
                    //逻辑卷状态
                    collResult.addKPI(LVUnitId, "FM-00-01-001-14", LVState);
                }
            }
            // CPU状态
            if(CPUInfos != null && CPUInfos.size() > 0){
                for(String CPUInfo : CPUInfos){
                    String CPUName = split(CPUInfo, 0).trim();
                    String CPUState = split(CPUInfo, 1).trim();
                    String CPUUnitId = "10-10-20-29:" + deviceId + "-" + Formater.neatenunitid(CPUName) ;
                    //CPU名称
                    collResult.addKPI(CPUUnitId, "CM-00-01-001-58", CPUName);
                    //CPU状态
                    collResult.addKPI(CPUUnitId, "FM-00-01-001-15", CPUState);
                }
            }
            if(maintainVersion != null && maintainVersion.size() > 0){
                // 操作系统维护版本
                collResult.addKPI(totalUnitId, "CM-00-01-001-62", maintainVersion.get(0).trim());
            }
            if(syslogStatus != null && syslogStatus.size() > 0){
                // syslog状态
                collResult.addKPI(totalUnitId, "FM-00-01-001-16", split(syslogStatus.get(0),3));
            }
            if(ntpStatus != null && ntpStatus.size() > 0){

                for(String temp : ntpStatus){
                    if(temp.contains("0513-036")){
                        // ntp状态
                        collResult.addKPI(totalUnitId, "FM-00-01-001-13", "stoped");
                        break;
                    }else if (temp.contains("Subsystem         Group            PID          Status")){
                        // ntp状态
                        collResult.addKPI(totalUnitId, "FM-00-01-001-13", "active");
                        break;
                    }
                }
            }
            if(machineSerialNum !=null && machineSerialNum.size()>0){
                collResult.addKPI(totalUnitId,"CM-01-03-001-08",split(machineSerialNum.get(0),3));
            }
        }catch (Exception e){
            logger.error("[IBM COLL] Exception while getConfig()", e);
        }

		collResult.displayKPI();
		return collResult.KPISet;
	}
	
	/**
	 * 采集内存指标
	 * @throws 
	 * @since Ver 1.1
	 */
	public Vector<TblATO_KPIDETAIL> getMemory(HashMap<String, String> params) {
		CollBase collResult = new CollBase();
		String deviceId = params.get("HOST_NAME");
		String memoryUnitId = "10-10-20-12:" + deviceId + "-memory";
		
		// 执行脚本
		exec(SH_COLL_MEMORY);
		try{
			// 获得脚本执行结果
			List<String> result = getResult(RESULT_MEMORY);
			if(result == null || result.size() == 0){
				return collResult.KPISet;
			}
			
			// 分隔每个命令的执行结果
			List<List<String>> list = parseResult(result, 6);
			// vmstat 2 10 执行结果
			List<String> vmstatResult = list.get(0);
			// prtconf |grep 'Good Memory Size:' 执行结果
			List<String> prtconfResult = list.get(1);
			// sar -b 2 2 执行结果
			List<String> sarResult = list.get(2);
			// svmon|grep memory|awk '{print $2}' 执行结果
			List<String> svmonMemoryResult = list.get(3);
			// svmon|grep "in use"|awk '{print $3}' 执行结果
			List<String> svmonInUseResult = list.get(4);
            //page space使用信息
			List<String> pageSpaceResult = list.get(5);

			// 内存总大小
			int totalSize = Integer.parseInt(split(prtconfResult.get(0), 3));
			logger.debug("[IBM COLL] Total memory size :" + totalSize);
			
			String memoryRun = vmstatResult.get(vmstatResult.size() - 1);
			// 剩余内存大小
			int freeSize = Integer.parseInt(split(memoryRun, 3)) * 4 / 1024;
			logger.debug("[IBM COLL] Free memory size :" + freeSize);
			
			 // 内存使用率
			double useRate = 100.0 - (freeSize * 100.0) / totalSize;
			String sUseRate = this.getByScale(Double.toString(useRate));
			logger.debug("[IBM COLL] Memory useRate :" + useRate);
			
			collResult.addKPI(memoryUnitId, "PM-00-01-002-01", Formater.formatDecimalKpivalue(sUseRate));
			
			String sysRate = useRate * 0.7 + "";
			String userRate = useRate * 0.3 + "";
			collResult.addKPI(memoryUnitId, "PM-00-01-002-07", Formater.formatDecimalKpivalue(sysRate));
			collResult.addKPI(memoryUnitId, "PM-00-01-002-06", Formater.formatDecimalKpivalue(userRate));
			
			// M-00-01-002-02 内存交换请求数
			collResult.addKPI(memoryUnitId, "PM-00-01-002-02", split(memoryRun, 7));
			// PM-00-01-002-03 内存交换页换进率
			collResult.addKPI(memoryUnitId, "PM-00-01-002-03", split(memoryRun, 5));
			// PM-00-01-002-04 内存交换页换出率
			collResult.addKPI(memoryUnitId, "PM-00-01-002-04", split(memoryRun, 6));
			// PM-00-01-002-05 内存队列数
			collResult.addKPI(memoryUnitId, "PM-00-01-002-05", split(memoryRun, 0));


			if(null != svmonMemoryResult && !svmonMemoryResult.isEmpty()){
				try{
					String total_memory = svmonMemoryResult.get(0).trim();
					int vm_total_mem = Integer.parseInt(total_memory);
					String use_memory = svmonInUseResult.get(0).trim();
					int use_mem = Integer.parseInt(use_memory);
					double vm_use_per = ((double)use_mem * 100D) / (double)vm_total_mem;
					String vm_mem_use_per = getByScale((new Double(vm_use_per)).toString());
					collResult.addKPI(memoryUnitId, "PM-00-01-002-09", Formater.formatDecimalKpivalue(vm_mem_use_per));
				}catch(Exception e){
					logger.error("Error when exe 'svmon|grep memory|awk '{print $2}' , null or nothing return");
				}
			}

			
			// PM-00-01-002-08 文件系统数据缓冲命中率			
			if (sarResult != null && sarResult.size() > 0) {
				String filerate = sarResult.get(sarResult.size() - 1);
				int r_rate = Integer.parseInt(split(filerate, 3));
				int w_rate = Integer.parseInt(split(filerate, 6));
				String value = String.valueOf((r_rate + w_rate) / 2);
				collResult.addKPI(memoryUnitId, "PM-00-01-002-08", Formater.formatDecimalKpivalue(value));
			} else {
				logger.error("Error when exe 'sar -b 2 2' , null or nothing return");
			}

            String pageUnitId = "10-10-20-30:"+deviceId+"-";
            for(int i = 1;i< pageSpaceResult.size();i++){
                String name = split(pageSpaceResult.get(i), 1);
                //换页空间物理卷
                collResult.addKPI(pageUnitId+name, "CM-00-01-001-61", name);
                //换页空间大小
                collResult.addKPI(pageUnitId+name, "PM-00-01-001-19", split(pageSpaceResult.get(i), 3));
                //换页空间使用率
                collResult.addKPI(pageUnitId+name, "PM-00-01-001-20", split(pageSpaceResult.get(i), 4));
                //换页空间是否活动
                collResult.addKPI(pageUnitId+name, "PM-00-01-001-21", split(pageSpaceResult.get(i), 5));
                //换页空间是否自动
                collResult.addKPI(pageUnitId+name, "PM-00-01-001-22", split(pageSpaceResult.get(i), 6));
                //换页空间类型
                collResult.addKPI(pageUnitId+name, "PM-00-01-001-23", split(pageSpaceResult.get(i), 7));
            }
	
		}catch (Exception e) {
			logger.error("[IBM COLL] Exception while getMemory()", e);
		}
		return collResult.KPISet;
	}
	
	/**
	 * 采集CPU指标
	 * @throws 
	 * @since Ver 1.1
	 */
	public Vector<TblATO_KPIDETAIL> getCpu(HashMap<String, String> params) {
		CollBase collResult = new CollBase();
		String deviceId = params.get("HOST_NAME");
		String unitId = "10-10-20-11:" + deviceId + "-cpu";
		
		// 执行脚本
		exec(SH_COLL_CPU);		
		try {
			// 获得脚本执行结果
			List<String> result = getResult(RESULT_CPU);
			if(result == null || result.size() == 0){
				return collResult.KPISet;
			}
			
			// 分隔每个命令的执行结果
			List<List<String>> list = parseResult(result, 2);
			List<String> vmstatResult = list.get(0);
			List<String> ifconfigResult = list.get(1);
			
			String cpuRun = vmstatResult.get(vmstatResult.size() - 1);
			// CPU时间:空闲百分比
			collResult.addKPI(unitId, "PM-00-01-001-01", split(cpuRun, 15));
			// CPU时间:系统百分比
			collResult.addKPI(unitId, "PM-00-01-001-02", split(cpuRun, 14));
			// CPU时间:用户百分比
			collResult.addKPI(unitId, "PM-00-01-001-03", split(cpuRun, 13));
			// CPU时间:等待百分比
			collResult.addKPI(unitId, "PM-00-01-001-04", split(cpuRun, 16));
			// CPU运行队列中进程个数
			collResult.addKPI(unitId, "PM-00-01-001-06", split(cpuRun, 0));
            // CPU阻塞队列中进程个数
            collResult.addKPI(unitId, "PM-00-01-001-11", split(cpuRun, 1));
			// CPU利用率
			collResult.addKPI(unitId, "PM-00-01-001-05", getCpuUsage(vmstatResult));

			// 网卡状态
//			if (ifconfigResult != null && ifconfigResult.size() > 0) {
//				for (String ifconfigInfo : ifconfigResult) {
//					if (ifconfigInfo.indexOf("flags") < 0
//							|| ifconfigInfo.indexOf("lo0") > -1
//							|| ifconfigInfo.indexOf("<UP") < 0) {
//						continue;
//					}
//					String lan_name = ifconfigInfo.substring(0, ifconfigInfo
//							.indexOf(':'));
//					String lan_state = " ";
//					try {
//						lan_state = ifconfigInfo.substring(ifconfigInfo
//								.indexOf('<') + 1, ifconfigInfo.indexOf(',',
//								ifconfigInfo.indexOf('<')));
//					} catch (Exception e) {
//						e.printStackTrace();
//						lan_state = "DOWN";
//					}
//					collResult.addKPI("10-10-20-16:" + deviceId + "-"
//							+ Formater.neatenunitid(lan_name),
//							"FM-00-01-001-03", lan_state);
//				}
//			}
			
		} catch (Exception e) {
			logger.error("[IBM COLL] Exception while getCpu()", e);
		}

		return collResult.KPISet;
	}
	
	
	private String getCpuUsage(List<String> vmstatResult) {
		try {
			StringBuffer sb = new StringBuffer();
			for(String line : vmstatResult){
				sb.append(line + "\n");
			}
			logger.info("vmstat\n" + sb.toString());
			
			float cpu_value = 0;

			sb = new StringBuffer();
			for (int i = 7; i <= 25 && i < vmstatResult.size(); i++) {
				String line = vmstatResult.get(i);
				sb.append(line + "\n");

//				String cpu1 = split(line, 13);
//				String cpu2 = split(line, 14);
//
//				cpu_value = (Integer.parseInt(cpu1) + Integer.parseInt(cpu2))
//						+ cpu_value;

                String cpu = split(line, 15);
                cpu_value =(100-Integer.parseInt(cpu))+ cpu_value;
            }
			logger.info("-- \n" + sb.toString());
			cpu_value = cpu_value / 19;
			logger.info("cpu_value=" + cpu_value);

			return Formater.formatDecimalKpivalue(Float.toString(cpu_value));
		} catch (Exception e) {
			logger.error("Exception while getCpuUsage", e);
			return "0.0";
		}

	}

	/**
	 * 采集硬盘指标 KBP_CLASS: 10-10-20-13
	 * PM-00-01-003-01 磁盘物理IO操作速率 磁盘物理IO操作速率(秒) 
	 * PM-00-01-003-02 平均磁盘请求数量 单位时间内平均磁盘请求数量 
	 * PM-00-01-003-03 磁盘忙的百分比 磁盘读写的时间占用总时间的百分比 
	 * PM-00-01-003-04 每秒磁盘读请求 每秒磁盘读请求字节数 
	 * PM-00-01-003-05 每秒磁盘写请求 每秒磁盘写请求字节数 
	 * PM-00-01-003-06 磁盘访问平均等待时间 磁盘访问平均等待时间(毫秒) 
	 * PM-00-01-003-07 等待I/O进程线程数 等待系统I/O(disk、inode、cache、CDFS等)的进程和线程数
	 */
	public Vector<TblATO_KPIDETAIL> getDisk(HashMap<String, String> params) {
		logger.info("[IBM COLL] Begin getDisk...");
		CollBase collResult = new CollBase();
		String deviceId = params.get("HOST_NAME");
		String unitId = "10-10-20-13:" + deviceId;

		// 执行脚本
		exec(SH_COLL_DISK);		
		try {
			// 获得脚本执行结果
			List<String> result = getResult(RESULT_DISK);
			if(result == null || result.size() == 0){
				return collResult.KPISet;
			}
			
			// 分隔每个命令的执行结果
			List<List<String>> list = parseResult(result, 2);
			
			// lspv | grep -v vpath | grep -v None | awk '{print $1}'
			List<String> vDisk = list.get(0);
			/****************************************************/
			Map<String, Map<String, Double>> tmp = new HashMap<String, Map<String, Double>>();

			Map<String, Double> map;
			for (int i = 0; i < vDisk.size(); i++) {
				String line = vDisk.get(i);

				if (line.indexOf("Disks:") >= 0) {
					int j = i + 1;
					String line1 = vDisk.get(j);

					while (null != line1 && !"".equals(line1.trim())) {
						
						String key = split(line1, 0);
						map = tmp.get(key);
						if (map == null) {
							map = new HashMap<String, Double>();
							tmp.put(key, map);
						}
						
						logger.info("-iostat:" + line1);
						String column1 = split(line1, 1);
						String column2 = split(line1, 2);

						double tmActTotal = map.get("tm_act") == null ? 0D : map
								.get("tm_act");
						double kbpsTotal = map.get("Kbps") == null ? 0D : map
								.get("Kbps");

						tmActTotal += Double.parseDouble(column1);
						kbpsTotal += Double.parseDouble(column2);

						map.put("tm_act", tmActTotal);
						map.put("Kbps", kbpsTotal);

						j++;
						if(j >= vDisk.size()){
							break;
						}else{
							line1 = vDisk.get(j);
						}
					}
				}
			}
			
			for (String key : tmp.keySet()) {
				Map<String, Double> value = tmp.get(key);

				String tmAct = String.valueOf(value.get("tm_act") / 20);
				String kbps = String.valueOf(value.get("Kbps") / 20);

				String diskUnitId = unitId + "-" + Formater.neatenunitid(key);
				// 磁盘名称
				collResult.addKPI(diskUnitId, "CM-00-01-001-20", key);
				// 磁盘物理IO操作速率
				collResult.addKPI(diskUnitId, "PM-00-01-003-01", Formater.formatDecimalKpivalue(kbps));
				// 磁盘忙的百分比
				collResult.addKPI(diskUnitId, "PM-00-01-003-03", Formater.formatDecimalKpivalue(tmAct));
			}
			/****************************************************/

			try {
				List<String> diskV = list.get(1);
				boolean checkAverage = true; // 是否检查Average这个字符串
				for (int i = 0; i < diskV.size(); i++) {
					String device_valueInfo = diskV.get(i);

					String device_name = "inital";

					// 设定checkAverage的值
					if (checkAverage) {
						int iPos = device_valueInfo.indexOf("Average");
						if (iPos > -1) {
							checkAverage = false;
							device_name = "Average_row";
						}
					}

					// 如果不用检查,那么本行就是一个磁盘
					if (!checkAverage) {
						if (device_name.equals("Average_row")) {
							// 说明是Average_row
							device_name = split(device_valueInfo, 1);
						} else {
							device_name = split(device_valueInfo, 0);
						}

						// System.out.println("device_valueInfo:"+device_valueInfo);
						// System.out.println("device_name :"+device_name);
						// 在指标获取前,判断该设备是否是磁盘设备,不是的话,不采集
						if (!tmp.containsKey(device_name.trim())) {
							System.out.println("not contains : " + device_name);
							continue;
						}

						String neat_disk_name = Formater.neatenunitid(device_name);
						
						String diskUnitId = unitId + "-" + Formater.neatenunitid(neat_disk_name);

						// 等待磁盘系统进程线程数
						String value = split(device_valueInfo, 3);
						collResult.addKPI(diskUnitId,
								"PM-00-01-003-02", Formater
										.formatDecimalKpivalue(value));

						// 每秒读请求
						value = split(device_valueInfo, 4);
						collResult.addKPI(diskUnitId,
								"PM-00-01-003-04", Formater
										.formatDecimalKpivalue(value));

						// 每秒写请求
						value = split(device_valueInfo, 4);
						collResult.addKPI(diskUnitId,
								"PM-00-01-003-05", Formater
										.formatDecimalKpivalue(value));
					}

				}
			} catch (Exception e) {
				logger.error("[IBM COLL] Exception while getDisk()", e);
			}
		}catch (Exception e) {
			logger.error("[IBM COLL] Exception while getDisk()", e);
		}
		collResult.displayKPI();
		logger.info("[IBM COLL] End getDisk!");
		return collResult.KPISet;
	}
	
	/**
	 * 采集文件系统 
	 * KBP_CLASS
	 * 		文件系统:10-10-20-14
	 *    	交换空间:10-10-20-22
	 * PM-00-01-004-01	文件系统使用比率	文件系统已使用的空间与总空间的比值
	 * PM-00-01-004-02	交换区使用百分比	交换区使用百分比
	 * PM-00-01-004-03	逻辑卷(裸设备)文件系统使用率	各逻辑卷上文件系统的使用率
	 */
	public Vector<TblATO_KPIDETAIL> getFileSystem(HashMap<String, String> params) {
		logger.info("[IBM COLL] Begin getFileSystem...");
		CollBase collResult = new CollBase();
		String deviceId = params.get("HOST_NAME");

		// 执行脚本
		exec(SH_COLL_FILE_SYSTEM);
		try {
			// 获得脚本执行结果
			List<String> result = getResult(RESULT_FILE_SYSTEM);
			if(result == null || result.size() == 0){
				return collResult.KPISet;
			}
			
			// 分隔每个命令的执行结果
			List<List<String>> list = parseResult(result, 3);
			
			// df -k
			List<String> vFilseSystem = list.get(0);
			// lsps -s
			List<String> vSwap = list.get(1);
			// vmstat -v
			List<String> vFilesysSwap = list.get(2);
			
			// 文件系统总大小
			long totalSize = 0L;
			// 文件系统总的空闲空间
			long freeSize = 0L;
			if (vFilseSystem != null & vFilseSystem.size() > 1) {
				for (int i = 1; i < vFilseSystem.size(); i++) {
					String line = vFilseSystem.get(i);
					String fileSystemName = split(line, 6).trim();
					String usedPercent = split(line, 3).trim();
					if (usedPercent.equals("-")) {
						usedPercent = "0";
					} else {
						usedPercent = usedPercent.substring(0, usedPercent.length() - 1);
					}
					
					String fileSystemSize = split(line, 1).trim();
					String fileSystemFree = split(line, 2).trim();
					fileSystemSize = fileSystemSize.equals("-") ? "0" : fileSystemSize;
					fileSystemFree = fileSystemFree.equals("-") ? "0" : fileSystemFree;
					
					totalSize = totalSize + Long.parseLong(fileSystemSize);
					freeSize = freeSize + Long.parseLong(fileSystemFree);					
					
					if(fileSystemName.equals("/")){
						fileSystemName = "//";
					}
					
					// 文件系统使用率
					String fsUnitId = "10-10-20-14:" + deviceId + "-" + Formater.neatenunitid(fileSystemName);
					collResult.addKPI(fsUnitId, "PM-00-01-004-03", Formater.formatDecimalKpivalue(usedPercent));
					
					// 文件系统可用空间
					float temp = Float.parseFloat(fileSystemFree.trim()) / 1024;
					collResult.addKPI(fsUnitId, "PM-00-01-004-04", Formater.formatDecimalKpivalue(Float.toString(temp)));
					
					// 文件系统挂载磁盘 PM-00-01-004-14
					collResult.addKPI(fsUnitId, "CM-00-01-001-42", split(line, 0).trim());
				}
				
				// 文件系统总的已使用空间/文件系统的总大小
				String totalUnitId = "10-10-20-10:" + deviceId + "-total";
				collResult.addKPI(totalUnitId, "PM-00-01-004-01", Formater
						.formatDecimalKpivalue(String.valueOf(100 - freeSize
								* 100.0 / totalSize)));
				
				// 交换区使用百分比 
				String swapUnitId = "10-10-20-10:" + deviceId + "-total";
				if (vSwap.size() > 1) {
					String swapPercent = split(vSwap.get(vSwap.size()-1), 1).trim();
					String totalSwap = split(vSwap.get(vSwap.size()-1), 0).trim();
					// 去除百分号
					swapPercent = swapPercent.substring(0, swapPercent.length() - 1); 					
					// 去除单位MB
                    totalSwap = totalSwap.substring(0, totalSwap.length() - 2);
                    Double usedSwap = Integer.parseInt(totalSwap)*Integer.parseInt(swapPercent)/100.0;
                    Double freeSwap = Integer.parseInt(totalSwap)-usedSwap;

					collResult.addKPI(swapUnitId, "PM-00-01-004-02", swapPercent);
                    //交换分区大小
					collResult.addKPI(swapUnitId, "CM-00-01-001-13", totalSwap);
                    //交换分区已用大小
					collResult.addKPI(swapUnitId, "PM-00-01-004-19", usedSwap.toString());
                    //交换分区空闲大小
					collResult.addKPI(swapUnitId, "PM-00-01-004-22", freeSwap.toString());
				}
			}
			
			// 文件系统缓存 PM-00-01-004-16
			String fileSwapUnitId = "10-10-20-10:" + deviceId + "-total";
			if (vFilesysSwap != null && vFilesysSwap.size() > 0) {
				String fsysSwapRate = vFilesysSwap.get(0);
				String swapRate = split(fsysSwapRate, 0);
				collResult.addKPI(fileSwapUnitId, "PM-00-01-004-16", swapRate);
			} else {
				collResult.addKPI(fileSwapUnitId, "PM-00-01-004-16", "0");
			}
		}catch (Exception e) {
			logger.error("[IBM COLL] Exception while getFileSystem...");
		}
		
		logger.info("[IBM COLL] End getFileSystem!");
		return collResult.KPISet;
	}

    public Vector getProcessTop10(HashMap<String, String> params) {
        logger.info("begin getProcessTop10");
        CollBase collResult = new CollBase();
        String deviceId = params.get("HOST_NAME");
        // 获得脚本执行结果
        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, 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 getProcessTop10Mem");
            String pro_PRE_UNITID = "10-10-20-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 = StringUtils.substringAfter(processInfo, split(processInfo, 10));
                    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 getProcessByKey(HashMap<String, String> params) {
        logger.info("begin getProcessByKey");
        CollBase collResult = new CollBase();
        String deviceId = params.get("HOST_NAME");
        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 {
            String pro_PRE_UNITID = "10-10-20-25:" + deviceId;
            List<String> processInfos = list.get(1);
            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 = StringUtils.substringAfter(processInfo, split(processInfo, 10));
                        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("getProcessByKey has error", e);
        }
        logger.info("end getProcessByKey");
        return collResult.getKPISet();
    }

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

        // 执行脚本
        exec(SH_COLL_HARDWARE);
        try {
            // 获得脚本执行结果
            List<String> result = getResult(RESULT_HARDWARE);
            if(result == null || result.size() == 0){
                return collResult.KPISet;
            }

            // 分隔每个命令的执行结果
            List<List<String>> list = parseResult(result, 2);

            String deviceId = params.get("HOST_NAME");
            // 获取主机名称
            if(null==deviceId || "".equals(deviceId.trim())){
                // 获取主机名称 : uname -a
                List<String> vHostName = list.get(0);
                deviceId = split(vHostName.get(0), 1);
            }
            String unitId = "10-10-20-10:" + deviceId + "-hardware";

            List<String> errorInfos = list.get(1);
            int H_NUM= 0;
            int S_NUM= 0;
            int O_NUM= 0;
            int U_NUM= 0;
            for(String tempLine : errorInfos){
                if("H".equals(split(tempLine,2))){
                    H_NUM++;
                }else if("S".equals(split(tempLine,2))){
                    S_NUM++;
                }else if("O".equals(split(tempLine,2))){
                    O_NUM++;
                }else if("U".equals(split(tempLine,2))){
                    U_NUM++;
                }
            }
            //新增硬件或介质故障数
            collResult.addKPI(unitId,"FM-00-01-001-09",Integer.toString(H_NUM));
            //新增软件故障数
            collResult.addKPI(unitId,"FM-00-01-001-10",Integer.toString(S_NUM));
            //新增人为错误数
            collResult.addKPI(unitId,"FM-00-01-001-11",Integer.toString(O_NUM));
            //新增其他错误数
            collResult.addKPI(unitId,"FM-00-01-001-12",Integer.toString(U_NUM));

        } catch (Exception e) {
            logger.error("[IBM COLL] Exception while getHardware()", e);
        }

        return collResult.KPISet;
    }

    /**
     * 采集网络指标
     * @throws
     * @since Ver 1.1
     */
    public Vector<TblATO_KPIDETAIL> getNet(HashMap<String, String> params) {
        CollBase collResult = new CollBase();
        String deviceId = params.get("HOST_NAME");
        String unitId = "10-10-20-10:" + deviceId + "-net";
        String totalUnitId = "10-10-20-10:" + deviceId + "-total";
        try {
            logger.info("----------------begin getNet-------------");
            // 执行脚本
            exec(SH_COLL_NET);
            // 获得脚本执行结果
            List<String> result = getResult(RESULT_NET);
            if(result == null || result.size() == 0){
                return collResult.KPISet;
            }

            // 分隔每个命令的执行结果
            List<List<String>> list = parseResult(result, 4);
            // 获取主机名称
            if(null==deviceId || "".equals(deviceId.trim())){
                // 获取主机名称 : uname -a
                List<String> vHostName = list.get(0);
                deviceId = split(vHostName.get(0), 1);
            }

            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> netcardResult = list.get(2);
            logger.debug("[NETWORK] Command's result's size:" + netcardResult.size());
            if(netcardResult != null && netcardResult.size() > 0){
                logger.debug("[NETWORK] Command's result's size:" + netcardResult.size());
                Set<String> lancardSet = new HashSet<String>();
                String serviceIp = "";
                long lan_ipkts_total = 0;
                long lan_opkts_total = 0;
                for(String line : netcardResult){
                    String lanName = split(line, 0).trim();
                    String network = split(line, 2).trim();
                    lan_ipkts_total = lan_ipkts_total+ Long.parseLong(split(line, 4));
                    lan_opkts_total = lan_opkts_total+ Long.parseLong(split(line, 6));
                    // id 使用 -16 网络
                    String netUnitId = "10-10-20-16:" + deviceId + "-" + Formater.neatenunitid(lanName);

                    // 如果含有link,则为物理地址,否则为本地地址
                    if (network.indexOf("link") > -1 && (network.indexOf("*")) == -1) {
                        // 物理地址
                        String macAddress = split(line, 3);
                        collResult.addKPI(netUnitId, "CM-00-01-001-12", macAddress);
                    } else {
                        String ipAddress = split(line, 3);
                        collResult.addKPI(netUnitId, "CM-00-01-001-11", ipAddress);
                        serviceIp = serviceIp + "," + ipAddress;
                    }
                    lancardSet.add(lanName);
                }
                //网卡总出包数
                collResult.addKPI(totalUnitId, "PM-00-01-001-17", String.valueOf(lan_opkts_total));
                //网卡总入包数
                collResult.addKPI(totalUnitId, "PM-00-01-001-18", String.valueOf(lan_ipkts_total));

                // 主机(服务)地址 CM-00-01-001-02, 将所有ip地址累加
                collResult.addKPI(totalUnitId, "CM-00-01-001-02", serviceIp.substring(1, serviceIp.length()));
                // KPI: CM-00-01-001-10 系统网络接口数
                collResult.addKPI(totalUnitId, "CM-00-01-001-10", String.valueOf(lancardSet.size()));
            }
            // 网卡状态
            List<String> ifconfigResult = list.get(3);
            if (ifconfigResult != null && ifconfigResult.size() > 0) {
                for (String ifconfigInfo : ifconfigResult) {
                    if (ifconfigInfo.indexOf("flags") < 0
                            || ifconfigInfo.indexOf("lo0") > -1
                            || ifconfigInfo.indexOf("<UP") < 0) {
                        continue;
                    }
                    String lan_name = ifconfigInfo.substring(0, ifconfigInfo
                            .indexOf(':'));
                    String lan_state = " ";
                    try {
                        lan_state = ifconfigInfo.substring(ifconfigInfo
                                .indexOf('<') + 1, ifconfigInfo.indexOf(',',
                                ifconfigInfo.indexOf('<')));
                    } catch (Exception e) {
                        e.printStackTrace();
                        lan_state = "DOWN";
                    }
                    collResult.addKPI("10-10-20-16:" + deviceId + "-"
                            + Formater.neatenunitid(lan_name),
                            "FM-00-01-001-03", lan_state);
                }
            }

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

        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;
    }
    /**
	 * 解析每个命令的执行结果
	 * @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.equals(SPLIT_LINE)) {
				i++;
				continue;
			}
			list.get(i).add(line);
		}
		return list;
	}
	
	/**
	 * 获得脚本执行结果
	 * @throws 
	 * @since Ver 1.1
	 */
	private List<String> getResult(String resultFileName){
		try {
			Thread.sleep(20 * 1000L);
		} catch (InterruptedException e) {
			logger.warn("[IBM 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("[IBM COLL] Timeout, exit.");
				break;
			}
			
			File[] filelist = file.listFiles();
			if (filelist == null || filelist.length == 0) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					logger.error("[IBM 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("[IBM COLL] Exception while readFile:" + resultFileName, e);
				}finally{
					if(br != null){
						try {
							br.close();
						} catch (IOException e) {
							logger.error("[IBM COLL] IOException:", e);
						}
					}
					logger.info("[IBM COLL] Delete coll result file : " + resultFile.getName());
                    logger.info(RESULT_PATH + ":\n" + sb.toString());
                    resultFile.delete();
				}
			}
		}// end while

		return result;
	}

	/**
	 * 通知执行脚本
	 * 通知方式:写一个文件(文件名为采集脚本名称,如: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("[IBM COLL] Exception while exec("+shellName+")", e);
		}finally{
			if(kpiFileStream != null){
				kpiFileStream.flush();
				kpiFileStream.close();
			}
		}
	}
	
	public String split(String str, int pos) {
		StringTokenizer st = new StringTokenizer(str);
		List<String> values = new ArrayList<String>();
		while (st.hasMoreTokens()) {
			values.add(st.nextToken());
		}
		if (pos >= 0 && pos < values.size()) {
			return values.get(pos);
		}
		return "";
	}
	
	/**
	 * 得到指定精度的double类型数值
	 * 
	 * @param doubleValue
	 * @return
	 */
	private String getByScale(String doubleValue) {
		int scale = 2;
		return Formater.getByScale(doubleValue, scale);
	}
	
	public static void main(String[] args) {
        System.out.print(Long.parseLong("3577652391"));

		HashMap<String, String > params = new HashMap<String, String>();
		params.put("HOST_NAME", "dssyf");
		params.put("KEYWORDS", "qsacenl");
//		new CollIBMWithCMD().getCpu(params);
//		new CollIBMWithCMD().getMemory(params);
//		new CollIBMWithCMD().getDisk(params);
        CollIBMWithCMD coll = new CollIBMWithCMD();
        //Vector<TblATO_KPIDETAIL> result = coll.getFileSystem(params);
        Vector<TblATO_KPIDETAIL> result = coll.getConfig(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);
        }
//        List<String> result = coll.getResult(RESULT_CONFIG);
//        List<List<String>> list = coll.parseResult(result, 13);
	}


	
}