CollLinuxHostWithCMD.java 35 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
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.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

public class CollLinuxHostWithCMD {

    public static HashMap<Object, Object> vmMap;

    Logger logger = Logger.getLogger("COLL");

    String kbpClass = "10-10-24";

    RPCTarget rpctarget = new RPCTarget();

    String hostName;

    String deviceId;

    public CollLinuxHostWithCMD() {

    }

    private void init(HashMap<String, String> params){
        deviceId = params.get("DEVICE_ID");
        if (null == deviceId || "".equals(deviceId) || "null".equals(deviceId)) {
            deviceId = getHostName();
        }
        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());
        collResult.addKPI(unitId, "CM-00-01-001-03", "Linux");
        collResult.addKPI(unitId, "PM-20-20-001-52", getUptime());
        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");
        System.out.println("Formater.formatDecimalByScale(String.valueOf(Integer.parseInt(vMemSize.elementAt(0)) / 1024.0), 2) = " + Formater.formatDecimalByScale(String.valueOf(Integer.parseInt(vMemSize.elementAt(0)) / 1024.0), 2));
        collResult.addKPI(unitId, "CM-00-01-001-07", Formater.formatDecimalByScale(String.valueOf(Integer.parseInt(vMemSize.elementAt(0)) / 1024.0), 2));

        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(StringUtils.isBlank(map.get("rx_packets"))? "0":map.get("rx_packets"));
            long int_rxerrors = Long.parseLong(StringUtils.isBlank(map.get("rx_errors"))? "0":map.get("rx_errors"));
            long int_rxdropped = Long.parseLong(StringUtils.isBlank(map.get("rx_dropped"))? "0":map.get("rx_dropped"));
            long int_rxoverruns = Long.parseLong(StringUtils.isBlank(map.get("rx_overruns"))? "0":map.get("rx_overruns"));
            long int_rxframe = Long.parseLong(StringUtils.isBlank(map.get("rx_frame"))? "0":map.get("rx_frame"));

            long int_txpackets = Long.parseLong(StringUtils.isBlank(map.get("tx_packets"))? "0":map.get("tx_packets"));
            long int_txerrors = Long.parseLong(StringUtils.isBlank(map.get("tx_errors"))? "0":map.get("tx_errors"));
            long int_txdropped = Long.parseLong(StringUtils.isBlank(map.get("tx_dropped"))? "0":map.get("tx_dropped"));
            long int_txoverruns = Long.parseLong(StringUtils.isBlank(map.get("tx_overruns"))? "0":map.get("tx_overruns"));
            long int_txcarrier = Long.parseLong(StringUtils.isBlank(map.get("tx_carrier"))? "0":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) {
            // TODO Auto-generated catch block
            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();
                rx_bytes = StringUtils.isBlank(rx_bytes)? "0":rx_bytes;
                String tx_bytes = network.substring(network.indexOf("TX bytes:") + "TX bytes:".length(), network.lastIndexOf("(")).trim();
                tx_bytes = StringUtils.isBlank(tx_bytes)? "0":tx_bytes;
                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
            String rx_bytes = StringUtils.isBlank(map.get("rx_bytes"))? "0":map.get("rx_bytes");
            String tx_bytes = StringUtils.isBlank(map.get("tx_bytes"))? "0":map.get("tx_bytes");
            String rx_packets = StringUtils.isBlank(map.get("rx_packets"))? "0":map.get("rx_packets");
            String tx_packets = StringUtils.isBlank(map.get("tx_packets"))? "0":map.get("tx_packets");
            String rx_dropped = StringUtils.isBlank(map.get("rx_dropped"))? "0":map.get("rx_dropped");
            String tx_dropped = StringUtils.isBlank(map.get("tx_dropped"))? "0":map.get("tx_dropped");
            String rx_errors = StringUtils.isBlank(map.get("rx_errors"))? "0":map.get("rx_errors");
            String tx_errors = StringUtils.isBlank(map.get("tx_errors"))? "0":map.get("tx_errors");
            collResult.addKPI(unitId, "PM-00-01-900-04", Formater.formatDecimalByScale(String.valueOf(Long.parseLong(rx_bytes) + Long.parseLong(tx_bytes)/1024/sleepSeconds), 2));

            long long_packets = Long.parseLong(rx_packets) + Long.parseLong(tx_packets);
            long long_dropped = Long.parseLong(rx_dropped) + Long.parseLong(tx_dropped);
            long long_errors = Long.parseLong(rx_errors) + Long.parseLong(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 != 0? (swapTotal - swapFree) * 100 / swapTotal:100;
                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-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 buffers_total = buffers_used + buffers_free;
                long rate = buffers_total!=0? buffers_used * 100 /buffers_total:100;
                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));

        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) {
        BigDecimal cpuRate = BigDecimal.ZERO;
        Vector<String> topInfo = rpctarget.getKPISet("top -d1 -n1");
        for(String temp:topInfo){
            if(temp.startsWith("Cpu(s):")){
                String cpuFree = StringUtils.remove(split(temp, 4),"%id,");
                Double cpuUsed = 100- Double.parseDouble(cpuFree);
                cpuRate = BigDecimal.valueOf(cpuUsed).setScale(2, BigDecimal.ROUND_HALF_UP);
                break;
            }
        }
//        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(cpuRate.toString());
    }

    /**
     * 采集内存性能指标
     */
    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.formatDecimalByScale(String.valueOf(Integer.parseInt(value) / 1024.0), 2));

        value = split(sVmstat, 6);
        collResult.addKPI(unitId, "PM-00-01-002-03",
                Formater.formatDecimalByScale(String.valueOf(Integer.parseInt(value) / 1024.0), 2));

        value = split(sVmstat, 7);
        collResult.addKPI(unitId, "PM-00-01-002-04",
                Formater.formatDecimalByScale(String.valueOf(Integer.parseInt(value) / 1024.0), 2));

        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 used = split(fileSystem, 2).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);

            // CM-00-01-001-17 文件系统配置大小
            collResult.addKPI(unitId, "CM-00-01-001-17", Formater.formatDecimalKpivalue(Double.toString(Double.parseDouble(size) / 1024)));

            // 文件系统已使用大小
            collResult.addKPI(unitId, "PM-00-01-004-21", Formater.formatDecimalKpivalue(Double.toString(Double.parseDouble(used) / 1024)));

            // 文件系统挂载磁盘
            collResult.addKPI(unitId, "CM-00-01-001-42", fileSystemName);

            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)));

        //打开文件的句柄数 /usr/sbin/lsof |wc -l
        String fileHandle = "/usr/sbin/lsof | wc -l";
        Vector<String> vHandle = rpctarget.getKPISet(fileHandle);
        try {
            for (String line : vHandle) {
                String fileHandleNum = split(line, 0).trim();
                String unitId;
                unitId = kbpClass + "-10:" + deviceId + "-total";
                // PM-00-01-004-24 打开文件的句柄数
                collResult.addKPI(unitId, "PM-00-01-004-24", fileHandleNum);
            }
        } catch (Exception e) {
            logger.error("Exception while getFileSystem()", e);
        }

        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 -p 5 5");
        logger.info("---------------sar -d 5 5:"+sarResult.toString());
        if(sarResult == null || sarResult.size() == 0){
            return collResult.KPISet;
        }

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

        for(String disk : sarResult){
            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;
            logger.info("---------------"+diskName);
            logger.info("---------------"+disk);
            collResult.addKPI(unitId, "CM-00-01-001-20", diskName);
            collResult.addKPI(unitId, "FM-00-01-001-02", "CLAIMED");
            collResult.addKPI(unitId, "PM-00-01-003-01", split(disk, 2));
            collResult.addKPI(unitId, "PM-00-01-003-04", split(disk, 3));
            collResult.addKPI(unitId, "PM-00-01-003-05", split(disk, 4));
            collResult.addKPI(unitId, "PM-00-01-003-03", split(disk, 9));
            collResult.addKPI(unitId, "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);
            collResult.addKPI(unitId, "PM-00-01-003-07", await);

        }
        return collResult.KPISet;
    }
    private String getHostName() {
        Vector<String> host = rpctarget.getKPISet("uname -a");
        String hostName = host.elementAt(0);
        hostName = split(hostName, 1);
        return hostName;
    }

    private String getUptime() {
        Vector<String> host = rpctarget.getKPISet("uptime");
        String uptime = host.elementAt(0);
        String up_time = split(uptime, 2) + " " + split(uptime, 3);
        return up_time;
    }

    private String split(String str, int pos) {
        StringTokenizer st = new StringTokenizer(str);
        Vector<String> values = new Vector<String>();
        while (st.hasMoreTokens()) {
            values.add(st.nextToken());
        }
        if (pos >= 0 && pos < values.size()) {
            return values.elementAt(pos);
        }
        return "";
    }


    /**
     * 采集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);
        }

        // TODO 设置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);
        }

        // TODO 设置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 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.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 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) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return collResult.KPISet;
        }
        return collResult.KPISet;
    }

    public static void main(String args[]){
//        String tx_bytes = null;
//        System.out.println(StringUtils.isBlank(tx_bytes) ? "0" : tx_bytes);
//        System.out.println(Long.parseLong(StringUtils.isBlank(tx_bytes) ? "0" : tx_bytes));
//        tx_bytes="";
//        System.out.println(StringUtils.isBlank(tx_bytes) ? "0" : tx_bytes);
        CollLinuxHostWithCMD cmd = new CollLinuxHostWithCMD();
        System.out.println(cmd.getCpuRate(1,1));

//        HashMap<String, String> params = new HashMap<String, String>();
////        params.put("URI", args[0]);
//        CollLinuxHostWithCMD cmd = new CollLinuxHostWithCMD();
//        Vector<TblATO_KPIDETAIL> vector = cmd.collDisk(params);
//        for(TblATO_KPIDETAIL kpidetail : vector) {
//            System.out.println("unit_id:[" + kpidetail.UNIT_ID + "] kpi_id:[" + kpidetail.KPI_ID + "] kpi_value:[" + kpidetail.KPI_VALUE + "]");
//        }
    }
}