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

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: mooker
 * Date: 14-6-19
 * Time: 下午2:01
 * To change this template use File | Settings | File Templates.
 */
public class CollCitrixXenWithCMD {

    private Logger logger = Logger.getLogger(CollCitrixXenWithCMD.class);

    protected static final XenServerConnectionPool _connPool = XenServerConnectionPool.getInstance();

    protected XsHost _host = new XsHost();
    protected String _username;
    protected Queue<String> _password = new LinkedList<String>();

    protected String _consolidationFunction = "AVERAGE";
    protected int _pollingIntervalInSeconds = 1;
    // 获取性能指标开始时间的延迟, 默认不延迟,但不可忽略网络传输速度
    protected int _stateTime=100;
    // 取多少的平均值,也就是性能的反应速度 -1为不设置
    protected int _vmColumns=1;
    protected int _hostColumns=1;

    Connection conn = null;
    Host.Record hr = null;
    VM.Record vr = null;
    HostStatusEntry hse = null;
    HashMap<String, VmStatusEntry> vse = null;
    String deviceId = "";
    String hostUuid = "";
    String vmUuid = "";

    // Xen主机的标识
    String PRE_HOST_UNITID = "10-10-26";

    public Vector<TblATO_KPIDETAIL> getHostConfig(HashMap<String, String> params) {
        logger.info("BEGIN getHostConfig");

        // 保存采集结果,并返回值
        CollBase collResult = new CollBase();

        // 获取主机名称device_id
        String neat_host_name = Formater.neatenunitid((String) params.get("HOSTUUID"));

        // 初始化参数
        try {
            init(params);
            if (deviceId != null && deviceId.length() > 0) {
                neat_host_name = Formater.neatenunitid(deviceId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 主机状态
            collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "FM-00-01-001-01", "DISCONNECTED");
            return collResult.getKPISet();
        }

        // uuid CM-00-01-001-60
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-60", hr.uuid);

        // 主机名称 CM-00-01-001-01
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-01", hr.nameLabel);

        // 主机状态 FM-00-01-001-01  与vmware的采集值一致 : poweredOn  poweredOff
        String host_status = "";
        if("true".equals(hr.enabled.toString())){
            host_status = "poweredOn";
        }else {host_status = "poweredOff";}
        //collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "FM-00-01-001-01", hr.enabled + "");
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "FM-00-01-001-01", host_status);

        // 主机操作系统版本 CM-00-01-001-08
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-08", hr.softwareVersion.get("product_version"));

        // 主机启动时间 CM-00-01-001-22
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-22", Formater.devDayHourSecond(Long.parseLong(hr.otherConfig.get("boot_time").replace(".", ""))));

        // 虚拟机个数 CM-10-10-11-63
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-10-10-11-63", hr.residentVMs.size() + "");

        // 系统网络接口数 CM-00-01-001-10
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-10", hr.PIFs.size() + "");

        // 主机CPU个数 CM-00-01-001-04
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-04", hr.cpuInfo.get("cpu_count"));

        // 主机CPU型号 CM-00-01-001-05
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-05", hr.cpuInfo.get("modelname"));

        // 主机CPU主频 CM-00-01-001-06
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-06", hr.cpuInfo.get("speed"));

        // 设备全名 CM-00-01-001-42
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-42", hr.hostname);

        // 主机IP地址 CM-00-01-001-02
        collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "CM-00-01-001-02", hr.address);

        return collResult.getKPISet();
    }

    public Vector<TblATO_KPIDETAIL> getHostCpu(HashMap<String, String> params) {
        logger.info("BEGIN getHostCpu");

        // 保存采集结果,并返回值
        CollBase collResult = new CollBase();

        // 获取主机名称device_id
        String neat_host_name = Formater.neatenunitid((String) params.get("HOSTUUID"));

        // 初始化参数
        try {
            init(params);
            if (deviceId != null && deviceId.length() > 0) {
                neat_host_name = Formater.neatenunitid(deviceId);
            }
        } catch (Exception e) {
            // 主机状态
            collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "FM-00-01-001-01", "DISCONNECTED");
            return collResult.getKPISet();
        }

        // CPU利用率 PM-00-01-001-05
        collResult.addKPI(PRE_HOST_UNITID + "-11:" + neat_host_name + "-cpu", "PM-00-01-001-05", Formater.formatDecimalKpivalue(String.valueOf(hse.getCpuUtilization())));

        return collResult.getKPISet();
    }

    public Vector<TblATO_KPIDETAIL> getHostMemory(HashMap<String, String> params) {
        logger.info("BEGIN getHostMemory");

        // 保存采集结果,并返回值
        CollBase collResult = new CollBase();

        // 获取主机名称device_id
        String neat_host_name = Formater.neatenunitid((String) params.get("HOSTUUID"));

        // 初始化参数
        try {
            init(params);
            if (deviceId != null && deviceId.length() > 0) {
                neat_host_name = Formater.neatenunitid(deviceId);
            }
        } catch (Exception e) {
            // 主机状态
            collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_host_name + "-total", "FM-00-01-001-01", "DISCONNECTED");
            return collResult.getKPISet();
        }

        // 主机内存大小 CM-00-01-001-07
        Double totalMemoryKBs = hse.getTotalMemoryKBs() / 1024.0;
        collResult.addKPI(PRE_HOST_UNITID + "-12:" + neat_host_name + "-mem", "CM-00-01-001-07", Formater.formatDecimalByScale(String.valueOf(totalMemoryKBs), 2));

        // 剩余可使用主机内存 PM-00-01-002-14
        Double freeMemoryKBs = hse.getFreeMemoryKBs() / 1024.0;
        collResult.addKPI(PRE_HOST_UNITID + "-12:" + neat_host_name + "-mem", "PM-00-01-002-14", Formater.formatDecimalByScale(String.valueOf(freeMemoryKBs), 2));

        // 已消耗的主机内存 PM-00-01-002-12
        Double usedMemoryKBs = totalMemoryKBs - freeMemoryKBs;
        collResult.addKPI(PRE_HOST_UNITID + "-12:" + neat_host_name + "-mem", "PM-00-01-002-12", Formater.formatDecimalByScale(String.valueOf(usedMemoryKBs), 2));

        // 内存使用率 PM-00-01-002-01
        collResult.addKPI(PRE_HOST_UNITID + "-12:" + neat_host_name + "-mem", "PM-00-01-002-01", Formater.formatDecimalByScale(String.valueOf(usedMemoryKBs * 100 / totalMemoryKBs), 2));

        return collResult.getKPISet();
    }

    public Vector<TblATO_KPIDETAIL> getVmConfig(HashMap<String, String> params) {
        logger.info("BEGIN getVmConfig");

        // 保存采集结果,并返回值
        CollBase collResult = new CollBase();

        // 获取主机名称device_id
        String neat_vm_name = Formater.neatenunitid((String) params.get("VMUUID"));

        // 初始化参数
        try {
            init(params);
            if (deviceId != null && deviceId.length() > 0) {
                neat_vm_name = Formater.neatenunitid(deviceId);
            }
        } catch (Exception e) {
            logger.error("can't get vm's OS, because XenServer Tools not installed", e);
//            // 主机状态
//            collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_vm_name + "-total", "FM-00-01-001-01", "DISCONNECTED");
            return collResult.getKPISet();
        }

        // 客户机操作系统
        String osversion = "";
        try {
            osversion = vr.guestMetrics.getOsVersion(conn).get("name");
        } catch (Exception e) {
            logger.error("can't get vm's OS, because XenServer Tools not installed", e);
            return null;
        }
        String p_unit_id = getPREVMKbp(osversion);

        // uuid CM-00-01-001-60
        collResult.addKPI(p_unit_id + "-10:" + neat_vm_name + "-total", "CM-00-01-001-60", vr.uuid);

        // 电源状态 FM-00-01-001-07   与vmware的采集值一致 : poweredOn  poweredOff  ,另KPI_ID也改为 FM-00-05-002-12
        //collResult.addKPI(p_unit_id + "-10:" + neat_vm_name + "-total", "FM-00-01-001-07", vr.powerState.toString());
        String power_status = "";
        if("Running".equals(vr.powerState.toString())){
            power_status = "poweredOn";
        }else {power_status = "poweredOff";}
        collResult.addKPI(p_unit_id + "-10:" + neat_vm_name + "-total", "FM-00-05-002-12", power_status);

        // 主机名称 CM-00-01-001-01
        collResult.addKPI(p_unit_id + "-10:" + neat_vm_name + "-total", "CM-00-01-001-01", vr.nameLabel);

//        // Home Server
//        try {
//            collResult.addKPI(p_unit_id + "-10:" + neat_vm_name + "-total", "CM-00-01-001-01", vr.residentOn.getNameLabel(conn));
//        } catch (Exception e) {
//            logger.error("", e);
//        }

        // 客户机内存 CM-00-01-001-26
        collResult.addKPI(p_unit_id + "-10:" + neat_vm_name + "-total", "CM-00-01-001-26", Formater.formatDecimalByScale(String.valueOf(vr.memoryTarget / 1024.0 / 1024.0), 2));

        // 虚拟CPU个数 CM-00-01-001-27
        collResult.addKPI(p_unit_id + "-10:" + neat_vm_name + "-total", "CM-00-01-001-27", vr.VCPUsMax + "");

        // 虚拟网卡个数 CM-00-01-001-28
        collResult.addKPI(p_unit_id + "-10:" + neat_vm_name + "-total", "CM-00-01-001-28", vr.VIFs.size() + "");

        // 主机启动时间 CM-00-01-001-22
        try {
            Date devTime = vr.metrics.getStartTime(conn);
            collResult.addKPI(p_unit_id + "-10:" + neat_vm_name + "-total", "CM-00-01-001-22",  Formater.devDayHourSecond((new Date()).getTime() - devTime.getTime()));
        } catch (Exception e) {
            logger.error("", e);
        }

        return collResult.getKPISet();
    }

    public Vector<TblATO_KPIDETAIL> getVmCpu(HashMap<String, String> params) {
        logger.info("BEGIN getVmCpu");

        // 保存采集结果,并返回值
        CollBase collResult = new CollBase();

        // 获取主机名称device_id
        String neat_vm_name = Formater.neatenunitid((String) params.get("VMUUID"));

        // 初始化参数
        try {
            init(params);
            if (deviceId != null && deviceId.length() > 0) {
                neat_vm_name = Formater.neatenunitid(deviceId);
            }
        } catch (Exception e) {
            logger.error("can't get vm's OS, because XenServer Tools not installed", e);
//            // 主机状态
//            collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_vm_name + "-total", "FM-00-01-001-01", "DISCONNECTED");
            return collResult.getKPISet();
        }

        // 客户机操作系统
        String osversion = "";
        try {
            osversion = vr.guestMetrics.getOsVersion(conn).get("name");
        } catch (Exception e) {
            logger.error("can't get vm's OS, because XenServer Tools not installed", e);
            return collResult.getKPISet();
        }
        String p_unit_id = getPREVMKbp(osversion);

        // CPU利用率 PM-00-01-001-05
        collResult.addKPI(p_unit_id + "-11:" + neat_vm_name + "-cpu", "PM-00-01-001-05", vse.get(vmUuid).getCPUUtilization() + "");

        return collResult.getKPISet();
    }

    public Vector<TblATO_KPIDETAIL> getVmMemory(HashMap<String, String> params) {
        logger.info("BEGIN getVmCpu");

        // 保存采集结果,并返回值
        CollBase collResult = new CollBase();

        // 获取主机名称device_id
        String neat_vm_name = Formater.neatenunitid((String) params.get("VMUUID"));

        // 初始化参数
        try {
            init(params);
            if (deviceId != null && deviceId.length() > 0) {
                neat_vm_name = Formater.neatenunitid(deviceId);
            }
        } catch (Exception e) {
            logger.error("can't get vm's OS, because XenServer Tools not installed", e);
//            // 主机状态
//            collResult.addKPI(PRE_HOST_UNITID + "-10:" + neat_vm_name + "-total", "FM-00-01-001-01", "DISCONNECTED");
            return collResult.getKPISet();
        }

        // 客户机操作系统
        String osversion = "";
        try {
            osversion = vr.guestMetrics.getOsVersion(conn).get("name");
        } catch (Exception e) {
            logger.error("can't get vm's OS, because XenServer Tools not installed", e);
            return null;
        }
        String p_unit_id = getPREVMKbp(osversion);

        // 主机内存大小 CM-00-01-001-07
        Double totalMemoryKBs = vse.get(vmUuid).getMemoryTarget() / 1024.0 / 1024.0;
        collResult.addKPI(p_unit_id + "-12:" + neat_vm_name + "-mem", "CM-00-01-001-07", Formater.formatDecimalByScale(String.valueOf(totalMemoryKBs), 2));

        // 剩余可使用主机内存 PM-00-01-002-14
        Double freeMemoryKBs = vse.get(vmUuid).getMemoryInternalFree() / 1024.0 / 1024.0;
        collResult.addKPI(p_unit_id + "-12:" + neat_vm_name + "-mem", "PM-00-01-002-14", Formater.formatDecimalByScale(String.valueOf(freeMemoryKBs), 2));

        // 已消耗的主机内存 PM-00-01-002-12
        Double usedMemoryKBs = totalMemoryKBs - freeMemoryKBs;
        collResult.addKPI(p_unit_id + "-12:" + neat_vm_name + "-mem", "PM-00-01-002-12", Formater.formatDecimalByScale(String.valueOf(usedMemoryKBs), 2));

        // 内存使用率 PM-00-01-002-01
        collResult.addKPI(p_unit_id + "-12:" + neat_vm_name + "-mem", "PM-00-01-002-01", Formater.formatDecimalByScale(String.valueOf(usedMemoryKBs * 100 / totalMemoryKBs), 2));

        return collResult.getKPISet();
    }

    protected class XsHost {
        public String name;
        public String systemvmisouuid;
        public String deveiceisoUuid;
        public String uuid;
        public String ip;
        public String publicNetwork;
        public String privateNetwork;
        public String linkLocalNetwork;
        public String storageNetwork1;
        public String storageNetwork2;
        public String guestNetwork;
        public String guestPif;
        public String publicPif;
        public String privatePif;
        public String storagePif1;
        public String storagePif2;
        public String pool;
        public String poolName;
        public int speed;
        public int cpus;
        public String product_version;
    }

    public Host.Record getHostInfo(Connection conn, String hostUuid) throws Exception {
        Host host = Host.getByUuid(conn, hostUuid);
        if(isRefNull(host)){
            String msg="‘Host’ uuid 无效. uuid: " + hostUuid ;
            logger.error(msg);
            throw new CloudRuntimeException(msg);
        }
        return host.getRecord(conn);
    }

    protected String getRRDByHttp(String url, boolean collectHostStats, String consolidationFunction, int interval, String startTime) {
        if (collectHostStats) {
            url += "&start=" + startTime + "&host=" + collectHostStats + "&cf=" + consolidationFunction + "&interval=" + interval;
        } else {
            url += "&start=" + startTime + "&cf=" + consolidationFunction + "&interval=" + interval;
        }
        System.out.println("getRRDByHttp URL is: " + url);
        return HttpClientUtils.executeGet(url);
    }

    /**
     * 获取Host RRD XML性能数据
     *
     * @param conn
     * @return
     */
    public String getHostStatusRawXML(Connection conn, String ip) {
        Date currentDate = new Date();
        String startTime = String.valueOf(currentDate.getTime() / 1000 - _stateTime);
        String url = "http://" + ip + "/rrd_updates?session_id=" + conn.getSessionReference();
        return getRRDByHttp(url, true, _consolidationFunction, _pollingIntervalInSeconds, startTime);
    }

    /**
     * 获取VM RRD XML性能数据
     *
     * @param conn
     * @return
     */
    protected String getVmStatusRawXML(Connection conn, String ip) {
        Date currentDate = new Date();
        String startTime = String.valueOf(currentDate.getTime() / 1000 - _stateTime);
        String url = "http://" + ip + "/rrd_updates?session_id=" + conn.getSessionReference();
        return getRRDByHttp(url, false, _consolidationFunction, _pollingIntervalInSeconds, startTime);
    }

    protected String getXMLNodeValue(Node n) {
        return n.getChildNodes().item(0).getNodeValue();
    }

    protected Object[] getRRDData(int flag, Connection conn, String ip) {
        String status = "";
        try {
            if (flag == 1) {
                status = getHostStatusRawXML(conn, ip);
            }
            if (flag == 2) {
                status = getVmStatusRawXML(conn, ip);
            }
        } catch (Exception e1) {
            logger.warn("Error whilst collecting raw stats from plugin: ", e1);
            return null;
        }

        // stats are null when the host plugin call fails (host down state)
        if (status == null) {
            return null;
        }

        StringReader statsReader = new StringReader(status);
        InputSource statsSource = new InputSource(statsReader);

        Document doc = null;
        try {
            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(statsSource);
        } catch (Exception e) {
            logger.warn("Exception caught whilst processing the document via document factory:", e);
            return null;
        }

        if (doc == null) {
            logger.warn("Null document found after tryinh to parse the stats source");
            return null;
        }

        NodeList firstLevelChildren = doc.getChildNodes();
        NodeList secondLevelChildren = (firstLevelChildren.item(0)).getChildNodes();
        Node metaNode = secondLevelChildren.item(0);
        Node dataNode = secondLevelChildren.item(1);

        Integer numRows = 0;
        Integer numColumns = 0;
        Node legend = null;
        NodeList metaNodeChildren = metaNode.getChildNodes();
        for (int i = 0; i < metaNodeChildren.getLength(); i++) {
            Node n = metaNodeChildren.item(i);
            if (n.getNodeName().equals("rows")) {
                numRows = Integer.valueOf(getXMLNodeValue(n));
            } else if (n.getNodeName().equals("columns")) {
                numColumns = Integer.valueOf(getXMLNodeValue(n));
            } else if (n.getNodeName().equals("legend")) {
                legend = n;
            }
        }

        return new Object[] { numRows, numColumns, legend, dataNode };
    }

    public VM.Record getVmInfo(Connection conn, String vmUuid) throws Exception {
        VM vm = VM.getByUuid(conn, vmUuid);
        if(isRefNull(vm)){
            String msg="‘VM’ uuid 无效. uuid: " + vmUuid ;
            logger.error(msg);
            throw new CloudRuntimeException(msg);
        }
        return vm.getRecord(conn);
    }

    /**
     * 计算平均值
     *
     * @param dataNode
     * @param col
     * @param numRows
     * @return
     */
    protected double getDataAverage(Node dataNode, int col, int numRows) {
        double value = 0;
        double dummy = 0;
        int numRowsUsed = 0;
        for (int row = 0; row < numRows; row++) {
            Node data = dataNode.getChildNodes().item(numRows - 1 - row).getChildNodes().item(col + 1);
            Double currentDataAsDouble = Double.valueOf(getXMLNodeValue(data));
            if (!currentDataAsDouble.equals(Double.NaN)) {
                numRowsUsed += 1;
                value += currentDataAsDouble;
            }
        }

        if (numRowsUsed == 0) {
            if ((!Double.isInfinite(value)) && (!Double.isNaN(value))) {
                return value;
            } else {
                logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows=0");
                return dummy;
            }
        } else {
            if ((!Double.isInfinite(value / numRowsUsed)) && (!Double.isNaN(value / numRowsUsed))) {
                return (value / numRowsUsed);
            } else {
                logger.warn("Found an invalid value (infinity/NaN) in getDataAverage(), numRows>0");
                return dummy;
            }
        }
    }

    public HostStatusEntry getHostStatus(Connection conn, String hostUuid) throws Exception {
        try {
            Host host = Host.getByUuid(conn, hostUuid);
            if (isRefNull(host)) {
                throw new CloudRuntimeException("Host 主机不存在:Host UUID:" + hostUuid);
            }
            String hostIp = host.getAddress(conn);
            HostStatusEntry hostStatus = new HostStatusEntry(0, 0, 0, 0, "host",0, 0, 0, 0);
            // call rrd method with 1 for host
            Object[] rrdData = getRRDData(1, conn, hostIp);

            if (rrdData == null) {
                return null;
            }

            Integer numRows = (Integer) rrdData[0];
            Integer numColumns = (Integer) rrdData[1];
            Node legend = (Node) rrdData[2];
            Node dataNode = (Node) rrdData[3];
            if (_hostColumns != -1 && numRows > _hostColumns) {
                numRows = _hostColumns;
            }
            NodeList legendChildren = legend.getChildNodes();
            for (int col = 0; col < numColumns; col++) {
                if (legendChildren == null || legendChildren.item(col) == null) {
                    continue;
                }
                String columnMetadata = getXMLNodeValue(legendChildren.item(col));
                if (columnMetadata == null) {
                    continue;
                }
                String[] columnMetadataList = columnMetadata.split(":");
                if (columnMetadataList.length != 4) {
                    continue;
                }
                String type = columnMetadataList[1];
                String param = columnMetadataList[3];

                if (type.equalsIgnoreCase("host")) {

                    if (param.contains("pif_eth0_rx")) {
                        hostStatus.setNetworkReadKBs(getDataAverage(dataNode, col, numRows));
                    }

                    if (param.contains("pif_eth0_tx")) {
                        hostStatus.setNetworkWriteKBs(getDataAverage(dataNode, col, numRows));
                    }

                    if (param.contains("memory_total_kib")) {
                        hostStatus.setTotalMemoryKBs(getDataAverage(dataNode, col, numRows));
                    }

                    if (param.contains("memory_free_kib")) {
                        hostStatus.setFreeMemoryKBs(getDataAverage(dataNode, col, numRows));
                    }

                    if (param.contains("cpu")) {
                        hostStatus.setNumCpus(hostStatus.getNumCpus() + 1);
                        hostStatus.setCpuUtilization(hostStatus.getCpuUtilization() + getDataAverage(dataNode, col, numRows));
                    }
                }
            }
            if (hostStatus.getNumCpus() != 0) {
                logger.info("Host cpu utilization " + hostStatus.getCpuUtilization());
                hostStatus.setCpuUtilization(hostStatus.getCpuUtilization() * 100 / hostStatus.getNumCpus());
                logger.info("Host cpu utilization " + hostStatus.getCpuUtilization());
            }
            return hostStatus;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 查询虚拟机在哪个主机下运行。
     * @return
     * @throws Exception
     */
    private Map<String, List<String>> getVmsAndHostsMaps(Connection conn, String[] vmUuids) throws Exception {
        Map<String, List<String>> maps = new HashMap<String, List<String>>();
        try {
            for (String uuid : vmUuids) {
                try {
                    VM vm = VM.getByUuid(conn, uuid);
                    VM.Record vmr = vm.getRecord(conn);
                    Types.VmPowerState ps = vmr.powerState;
                    if (ps != Types.VmPowerState.HALTED) {
                        Host host = vmr.residentOn;
                        String residentUuid = host.getUuid(conn);
                        if (residentUuid != null && !residentUuid.equals("")) {
                            List<String> listVms = maps.get(residentUuid);
                            if (listVms != null && listVms.size() > 0) {
                                listVms.add(uuid);
                            } else {
                                List<String> lists = new ArrayList<String>();
                                lists.add(uuid);
                                maps.put(residentUuid, lists);
                            }
                        }
                    }
                } catch (Exception e) {
                }
            }
            return maps;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 获取虚拟机的性能信息,两种方式,
     * 第一种:如果你确定主机和虚拟机的关系,那么通过传递主机HostUuid和虚拟机Vmuuids,来获取运行状态下虚拟机的性能信息
     * 第二种:如果你无法确定主机和虚拟机之间的关系,那么不需要传递hostUuid,程序会自动判断虚拟机所对应的主机,
     * 注意:第二种方式会导致获取性能信息服务器性能的下降。
     * 此方法为第一种方法
     * @param vmUUIDs
     * @return
     * @throws Exception
     */
    public HashMap<String, VmStatusEntry> getVmStatus(Connection conn, String hostUuid, String[] vmUUIDs) throws Exception {
        try {
            Host host = Host.getByUuid(conn, hostUuid);
            if (isRefNull(host)) {
                throw new CloudRuntimeException("Host 主机不存在:Host UUID:" + hostUuid);
            }
            String hostIp = host.getAddress(conn);
            HashMap<String, VmStatusEntry> vmResponseMap = new HashMap<String, VmStatusEntry>();
            for (String vmUUID : vmUUIDs) {
                vmResponseMap.put(vmUUID, new VmStatusEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, "vm"));
            }
            Object[] rrdData = getRRDData(2, conn, hostIp); // call rrddata with 2 for vm

            if (rrdData == null) {
                return null;
            }
            Integer numRows = (Integer) rrdData[0];
            Integer numColumns = (Integer) rrdData[1];
            Node legend = (Node) rrdData[2];
            Node dataNode = (Node) rrdData[3];
            if (_vmColumns != -1 && numRows > _vmColumns) {
                numRows = _vmColumns;
            }
            NodeList legendChildren = legend.getChildNodes();
            for (int col = 0; col < numColumns; col++) {
                if (legendChildren == null || legendChildren.item(col) == null) {
                    continue;
                }
                String columnMetadata = getXMLNodeValue(legendChildren.item(col));
                if (columnMetadata == null) {
                    continue;
                }
                String[] columnMetadataList = columnMetadata.split(":");
                if (columnMetadataList.length != 4) {
                    continue;
                }
                String type = columnMetadataList[1];
                String uuid = columnMetadataList[2];
                String param = columnMetadataList[3];
                if (type.equals("vm") && vmResponseMap.keySet().contains(uuid)) {
                    VmStatusEntry vmStatusAnswer = vmResponseMap.get(uuid);
                    vmStatusAnswer.setEntityType("vm");
                    vmStatusAnswer.setExistPer(true);
                    /**
                     * 待修改 待验证
                     */
                    if (param.contains("cpu")) {
                        vmStatusAnswer.setNumCPUs(vmStatusAnswer.getNumCPUs() + 1);
                        vmStatusAnswer.setCPUUtilization(((vmStatusAnswer.getCPUUtilization() + getDataAverage(dataNode, col, numRows))));
                    } else if (param.matches("vif_\\d_rx")) {
                        vmStatusAnswer.setNetworkReadKBs(vmStatusAnswer.getNetworkReadKBs() + (getDataAverage(dataNode, col, numRows) / (8 * 2)));
                    } else if (param.matches("vif_\\d_tx")) {
                        vmStatusAnswer.setNetworkWriteKBs(vmStatusAnswer.getNetworkWriteKBs() + (getDataAverage(dataNode, col, numRows) / (8 * 2)));
                    } else if (param.matches("vbd_.*?_write")) {
                        vmStatusAnswer.setDiskReadKBs(vmStatusAnswer.getDiskReadKBs() + (getDataAverage(dataNode, col, numRows)));
                    } else if (param.matches("vbd_.*?_read")) {
                        vmStatusAnswer.setDiskWriteKBs(vmStatusAnswer.getDiskWriteKBs() + (getDataAverage(dataNode, col, numRows)));
                    } else if (param.equals("memory")) {
                        vmStatusAnswer.setMemory(vmStatusAnswer.getMemory() + (long) (getDataAverage(dataNode, col, numRows)));
                    } else if (param.equals("memory_target")) {
                        vmStatusAnswer.setMemoryTarget(vmStatusAnswer.getMemoryTarget() + (long) (getDataAverage(dataNode, col, numRows)));
                    } else if (param.matches("memory_internal_free")) {
                        vmStatusAnswer.setMemoryInternalFree(vmStatusAnswer.getMemoryInternalFree() + (long) (getDataAverage(dataNode, col, numRows)) * 1024);
                    }
                }
            }

            for (String vmUUID : vmResponseMap.keySet()) {
                VmStatusEntry vmStatusAnswer = vmResponseMap.get(vmUUID);
                try {
                    VM temp = VM.getByUuid(conn, vmUUID);
                    VM.Record re = temp.getRecord(conn);
                    vmStatusAnswer.setPowerState(re.powerState.toString());
                    if (isRefNull(re.guestMetrics)) {
                        vmStatusAnswer.setExistXenTools(false);
                    } else {
                        vmStatusAnswer.setExistXenTools(true);
                    }
                    vmStatusAnswer.setVmName(re.nameLabel);
                } catch (Exception e) {
                }

                if (vmStatusAnswer.getNumCPUs() != 0) {
                    vmStatusAnswer.setCPUUtilization(vmStatusAnswer.getCPUUtilization() / vmStatusAnswer.getNumCPUs());
                }

                vmStatusAnswer.setCPUUtilization(vmStatusAnswer.getCPUUtilization() * 100);
                if (logger.isDebugEnabled()) {
                    logger.debug("Vm cpu utilization " + vmStatusAnswer.getCPUUtilization());
                }
            }

            return vmResponseMap;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    public HashMap<String, VmStatusEntry> getVmsStatus(Connection conn, String[] vmUUIDs) throws Exception {
        HashMap<String, VmStatusEntry> vmResponseMap = new HashMap<String, VmStatusEntry>();
        try {
            Map<String, List<String>> maps = getVmsAndHostsMaps(conn, vmUUIDs);
            Set<String> hus = maps.keySet();
            try {
                for (String uuid : hus) {
                    List<String> lists = maps.get(uuid);
                    if (lists != null && lists.size() > 0) {
                        String[] vmuuids = CommonUtil.changeListToStringArrays(lists);
                        _host.uuid = uuid;
                        vmResponseMap.putAll(getVmStatus(conn, uuid, vmuuids));
                    }
                }
            } catch (Exception e) {
            }
            return vmResponseMap;
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 10-10-20	IBM
     * 10-10-21	HP
     * 10-10-22	SUN
     * 10-10-23	MicroSoft
     * 10-10-24	Red-Hat
     * 10-10-25	VMWare
     */
    public String getPREVMKbp(String osversion) {
        String _preVMKbp = "";
        if (osversion.toLowerCase().indexOf("aix") != -1 ) {
            _preVMKbp = "10-10-20";
        }
        if (osversion.toLowerCase().indexOf("hp") != -1 ) {
            _preVMKbp = "10-10-21";
        }
        if (osversion.toLowerCase().indexOf("sunos") != -1 ) {
            _preVMKbp = "10-10-22";
        }
        if (osversion.toLowerCase().indexOf("microsoft") != -1 ) {
            _preVMKbp = "10-10-23";
        }
        if (osversion.toLowerCase().indexOf("linux") != -1 ) {
            _preVMKbp = "10-10-24";
        }
        if (osversion.toLowerCase().indexOf("vmkernel") != -1 ) {
            _preVMKbp = "10-10-25";
        }
        return _preVMKbp;
    }

    /**
     * 初始化
     * @param params
     */
    public void init(HashMap<String, String> params) throws Exception {
        _host.ip = (String) params.get("HOSTIP");
        _username = (String) params.get("USERNAME");
        _password.add((String) params.get("PASSWORD"));

        deviceId = (String) params.get("DEVICEID");
        hostUuid = (String) params.get("HOSTUUID");
        vmUuid = (String) params.get("VMUUID");
        String[] vmUuids = new String[] {vmUuid};

        conn = _connPool.connect(_host.ip, _username, _password);
        logger.info("hostUuid is: [" + hostUuid + "], vmUuid is: [" + vmUuid + "], deviceId is: " + deviceId);
        if (hostUuid != null && hostUuid.length() > 0) {
            hr = getHostInfo(conn, hostUuid);
            hse = getHostStatus(conn, hostUuid);
        }
        if (vmUuid != null && vmUuid.length() > 0) {
            vr = getVmInfo(conn, vmUuid);
            vse = getVmsStatus(conn, vmUuids);
        }
        logger.info("End to connect Host");
    }

    public boolean isRefNull(XenAPIObject object) {
        return (object == null || object.toWireString().equals("OpaqueRef:NULL")
                || object.toWireString().trim().equals("")
                || !object.toWireString().contains("OpaqueRef")
                || object.toWireString().equals("<not in database>"));
    }

}