Exemplo n.º 1
0
    def get_cpu_xml(mode, tmp_file):
        """
        Get CPU infomation and put it into a file.

        @param: mode: Test mode, decides file's detail.
        @param: tmp_file: File saves CPU infomation.
        """
        cpu_xml_file = open(tmp_file, 'wb')
        domxml = virsh.capabilities()
        dom = parseString(domxml)
        cpu_node = dom.getElementsByTagName('cpu')[0]
        if mode == "modify":
            vendor = cpu_node.getElementsByTagName('vendor')[0]
            for node in vendor.childNodes:
                if node.nodeType == node.TEXT_NODE:
                    vendor.removeChild(node)
                    break
            text_node = dom.createTextNode('test_vendor')
            vendor.appendChild(text_node)
            cpu_node.writexml(cpu_xml_file)
        elif mode == "clear":
            # Clear up file detail
            cpu_xml_file.truncate(0)
        else:
            cpu_node.writexml(cpu_xml_file)
        cpu_xml_file.close()
        dom.unlink()
Exemplo n.º 2
0
    def validate_host(to_file, test_feature):
        """
        Validate the host meets the test requirement which includes a
        certain feature

        :param to_file: the output to be written to
        :param test_feature: feature name to be searched
        :raises: test.cancel if the host does not include the tested feature
        """

        output = virsh.capabilities(to_file=to_file,
                                    ignore_status=False,
                                    debug=True)
        if not check_xml(output, test_feature):
            test.cancel("The capabilities do not include feature '%s'. "
                        "Skip the test" % test_feature)
Exemplo n.º 3
0
def run(test, params, env):
    """
    Test the command virsh capabilities

    (1) Call virsh capabilities
    (2) Call virsh capabilities with an unexpected option
    (3) Call virsh capabilities with libvirtd service stop
    """
    def compare_capabilities_xml(source):
        cap_xml = capability_xml.CapabilityXML()
        cap_xml.xml = source

        # Check that host has a non-empty UUID tag.
        xml_uuid = cap_xml.uuid
        logging.debug("Host UUID (capabilities_xml): %s" % xml_uuid)
        if xml_uuid == "":
            raise error.TestFail("The host uuid in capabilities_xml is none!")

        # Check the host arch.
        xml_arch = cap_xml.arch
        logging.debug("Host arch (capabilities_xml): %s", xml_arch)
        exp_arch = utils.run("arch", ignore_status=True).stdout.strip()
        if cmp(xml_arch, exp_arch) != 0:
            raise error.TestFail("The host arch in capabilities_xml is expected"
                                 " to be %s, but get %s" % (exp_arch, xml_arch))

        # Check the host cpu count.
        xml_cpu_count = cap_xml.cpu_count
        logging.debug("Host cpus count (capabilities_xml): %s", xml_cpu_count)
        cmd = "grep processor /proc/cpuinfo | wc -l"
        exp_cpu_count = int(utils.run(cmd, ignore_status=True).stdout.strip())
        if xml_cpu_count != exp_cpu_count:
            raise error.TestFail("Host cpus count is expected to be %s, but get "
                                 "%s" % (exp_cpu_count, xml_cpu_count))

        # Check the arch of guest supported.
        guest_capa = cap_xml.get_guest_capabilities()
        logging.debug(guest_capa)
        try:
            img = utils_misc.find_command("qemu-kvm")
        except ValueError:
            raise error.TestNAError("Cannot find qemu-kvm")
        if re.search("ppc", utils.run("arch").stdout):
            cmd = img + " --cpu ? | grep ppc"
        else:
            cmd = img + " --cpu ? | grep qemu"
        cmd_result = utils.run(cmd, ignore_status=True)
        for guest in cap_xml.xmltreefile.findall('guest'):
            guest_wordsize = guest.find('arch').find('wordsize').text
            logging.debug("Arch of guest supported (capabilities_xml):%s",
                          guest_wordsize)
            if not re.search(guest_wordsize, cmd_result.stdout.strip()):
                raise error.TestFail("The capabilities_xml gives an extra arch "
                                     "of guest to support!")

        # Check the type of hypervisor.
        first_guest = cap_xml.xmltreefile.findall('guest')[0]
        first_domain = first_guest.find('arch').findall('domain')[0]
        guest_domain_type = first_domain.get('type')
        logging.debug("Hypervisor (capabilities_xml):%s", guest_domain_type)
        cmd_result = utils.run("virsh uri", ignore_status=True)
        if not re.search(guest_domain_type, cmd_result.stdout.strip()):
            raise error.TestFail("The capabilities_xml gives an different "
                                 "hypervisor")

        # check power management support.
        try:
            pm_cmd = os_dep.command('pm-is-supported')
            pm_cap_map = {'suspend': 'suspend_mem',
                          'hibernate': 'suspend_disk',
                          'suspend-hybrid': 'suspend_hybrid',
                          }
            exp_pms = []
            for opt in pm_cap_map:
                cmd = '%s --%s' % (pm_cmd, opt)
                res = utils.run(cmd, ignore_status=True)
                if res.exit_status == 0:
                    exp_pms.append(pm_cap_map[opt])
            pms = cap_xml.power_management_list
            if set(exp_pms) != set(pms):
                raise error.TestFail("Expected supported PMs are %s, got %s "
                                     "instead." % (exp_pms, pms))
        except ValueError:
            logging.debug('Power management checking is skipped, since command '
                          'pm-is-supported is not found.')

    connect_uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                              "default"))

    # Prepare libvirtd service
    if "libvirtd" in params:
        libvirtd = params.get("libvirtd")
        if libvirtd == "off":
            utils_libvirtd.libvirtd_stop()

    # Run test case
    option = params.get("virsh_cap_options")
    try:
        output = virsh.capabilities(option, uri=connect_uri,
                                    ignore_status=False, debug=True)
        status = 0  # good
    except error.CmdError:
        status = 1  # bad
        output = ''

    # Recover libvirtd service start
    if libvirtd == "off":
        utils_libvirtd.libvirtd_start()

    # Check status_error
    status_error = params.get("status_error")
    if status_error == "yes":
        if status == 0:
            if libvirtd == "off":
                raise error.TestFail("Command 'virsh capabilities' succeeded "
                                     "with libvirtd service stopped, incorrect")
            else:
                raise error.TestFail("Command 'virsh capabilities %s' succeeded "
                                     "(incorrect command)" % option)
    elif status_error == "no":
        compare_capabilities_xml(output)
        if status != 0:
            raise error.TestFail("Command 'virsh capabilities %s' failed "
                                 "(correct command)" % option)
def run(test, params, env):
    """
    Test command: virsh hypervisor-cpu-compare

    Compare CPU provided by hypervisor on the host with a CPU described by an XML file
    1.Get all parameters from configuration.
    2.Prepare temp file saves of CPU information.
    3.Perform virsh hypervisor-cpu-compare operation.
    4.Confirm the result.
    """

    # Get all parameters.
    file_type = params.get("compare_file_type", "domxml")
    extract_mode = ("yes" == params.get("extract_mode", "no"))
    action_mode = params.get("action_mode")
    cpu_mode = params.get("cpu_mode", "custom")
    illegal_cpu_test = ("yes" == params.get("illegal_cpu_test", "no"))
    status_error = ("yes" == params.get("status_error", "no"))
    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)

    option_str = params.get("hypv_cpu_compare_option")
    invalid_option = params.get("invalid_option")
    invalid_value = params.get("invalid_value")
    if invalid_option:
        option_str = option_str.replace(invalid_option, "")

    if not libvirt_version.version_compare(4, 4, 0):
        test.cancel("hypervisor-cpu-compare does not support"
                    " in this libvirt version")

    if not vm.is_alive():
        vm.start()

    baseline_provider = params.get("baseline_provider", "libvirt")
    dom_xml = vm_xml.VMXML.new_from_dumpxml(vm_name)
    backup_xml = dom_xml.copy()
    compare_file = os.path.join(data_dir.get_tmp_dir(), "cpu.xml")
    domcapa_file = os.path.join(data_dir.get_tmp_dir(), "tmp_file")

    def get_domain_output(cpu_mode):
        """
        Prepare domain xml according cpu mode

        :param cpu_mode: The name of cpu mode
        :return: The domain xml data
        """
        try:
            cpuxml = dom_xml.cpu
            if not action_mode and cpuxml.mode == cpu_mode:
                return dom_xml.xmltreefile.get_element_string("/cpu")
            else:
                del dom_xml["cpu"]
        except LibvirtXMLNotFoundError:
            pass  # CPU already does not exist

        # Create new CPUXML
        cpuxml = vm_xml.VMCPUXML()
        cpuxml.mode = cpu_mode
        if cpu_mode == "custom":
            # Customize cpu according domcapabilities xml
            domcapa_output = get_domcapa_output(test)
            with open(domcapa_file, "w+") as tmp_f:
                tmp_f.write(domcapa_output)
            if "hypervisor" in baseline_provider:
                ret = virsh.hypervisor_cpu_baseline(domcapa_file)
            else:
                ret = virsh.cpu_baseline(domcapa_file)
            if ret.exit_status:
                test.fail("Fail to run virsh (hypervisor-)cpu-baseline: %s" %
                          ret.stderr.strip())
            cpuxml.xml = ret.stdout.strip()

        if cpu_mode == "host-passthrough":
            cpuxml.check = "none"

        dom_xml.cpu = cpuxml
        dom_xml.sync()
        vm.start()
        # VM start will change domxml content
        v_xml = vm_xml.VMXML.new_from_dumpxml(vm_name)
        return v_xml.xmltreefile.get_element_string("/cpu")

    def get_options(option_str):
        """
        Prepare virsh cmd options according input string

        :param option_str: Input option string contains option names
        :return: Virsh cmd options
        """
        options = ""
        emulator = dom_xml.devices.by_device_tag('emulator')[0]
        osxml = dom_xml.os
        if option_str.count("--virttype"):
            options += "--virttype %s " % dom_xml.hypervisor_type
        if option_str.count("--emulator"):
            options += "--emulator %s " % emulator.path
        if option_str.count("--arch"):
            options += "--arch %s " % osxml.arch
        if option_str.count("--machine"):
            options += "--machine %s " % osxml.machine
        if option_str.count("--error"):
            options += "--error "
        return options

    try:
        # Prepare options
        options = get_options(option_str)
        if invalid_option:
            options += "%s %s " % (invalid_option, invalid_value)

        # Prepare cpu compare file.
        cpu_data = ""
        if file_type == "domxml":
            cpu_data = get_domain_output(cpu_mode)
        elif file_type == "domcapa_xml":
            cpu_data = get_domcapa_output(test)
        elif file_type == "capa_xml":
            cpu_data = virsh.capabilities()
        else:
            test.error("The compare file type %s is unsupported" % file_type)

        # Extract cpu definition
        if extract_mode:
            cpu_data = get_cpu_definition(file_type, vm_name, test)
            if illegal_cpu_test and file_type == "domxml":
                # Make invalid cpu data by adding <host> outside of <cpu>
                cpu_data = "<host>{}</host>".format(cpu_data)

        with open(compare_file, "w+") as compare_file_f:
            compare_file_f.write(cpu_data)
            compare_file_f.flush()
            compare_file_f.seek(0)
            logging.debug("CPU description XML:\n%s", compare_file_f.read())

        # Perform virsh cpu-compare operation.
        result = virsh.hypervisor_cpu_compare(xml_file=compare_file,
                                              options=options,
                                              ignore_status=True,
                                              debug=True)
        msg_pattern = params.get("msg_pattern")

        # Check result
        if status_error and not result.exit_status:
            test.fail("Expect should fail but got:\n%s" % result.stdout)
        elif not status_error and result.exit_status:
            test.fail("Expect success but got:\n%s" % result.stderr)

        if msg_pattern:
            logging.debug("Expect key word in comand output: %s", msg_pattern)
            output = result.stdout.strip()
            if not output:
                output = result.stderr.strip()
            if not re.findall(msg_pattern, output):
                test.fail("Not find expect key word '%s' in command "
                          "output '%s'" % (msg_pattern, output))
    finally:
        backup_xml.sync()
        if os.path.exists(domcapa_file):
            os.remove(domcapa_file)
        if os.path.exists(compare_file):
            os.remove(compare_file)
Exemplo n.º 5
0
def run(test, params, env):
    """
    Test the command virsh capabilities

    (1) Call virsh capabilities
    (2) Call virsh capabilities with an unexpected option
    (3) Call virsh capabilities with libvirtd service stop
    """
    def compare_capabilities_xml(source):
        dom = parseString(source)
        host = dom.getElementsByTagName('host')[0]
        # check that host has a non-empty UUID tag.
        uuid = host.getElementsByTagName('uuid')[0]
        host_uuid_output = uuid.firstChild.data
        logging.info("Host uuid (capabilities_xml):%s", host_uuid_output)
        if host_uuid_output == "":
            raise error.TestFail("The host uuid in capabilities_xml is none!")

        # check the host arch.
        arch = host.getElementsByTagName('arch')[0]
        host_arch_output = arch.firstChild.data
        logging.info("Host arch (capabilities_xml):%s", host_arch_output)
        cmd_result = utils.run("arch", ignore_status=True)
        if cmp(host_arch_output, cmd_result.stdout.strip()) != 0:
            raise error.TestFail("The host arch in capabilities_xml is wrong!")

        # check the host cpus num.
        cpus = dom.getElementsByTagName('cpus')
        host_cpus = 0
        for cpu in cpus:
            host_cpus += int(cpu.getAttribute('num'))
        logging.info("Host cpus num (capabilities_xml):%s", host_cpus)
        cmd = "less /proc/cpuinfo | grep processor | wc -l"
        cmd_result = utils.run(cmd, ignore_status=True)
        if cmp(host_cpus, int(cmd_result.stdout.strip())) != 0:
            raise error.TestFail("Host cpus num (capabilities_xml) is "
                                 "wrong")

        # check the arch of guest supported.
        try:
            img = utils_misc.find_command("qemu-kvm")
        except ValueError:
            raise error.TestNAError("Cannot find qemu-kvm")
        cmd = img + " --cpu ? | grep qemu"
        cmd_result = utils.run(cmd, ignore_status=True)
        guest_wordsize_array = dom.getElementsByTagName('wordsize')
        length = len(guest_wordsize_array)
        for i in range(length):
            element = guest_wordsize_array[i]
            guest_wordsize = element.firstChild.data
            logging.info("Arch of guest supported (capabilities_xml):%s",
                         guest_wordsize)
            if not re.search(guest_wordsize, cmd_result.stdout.strip()):
                raise error.TestFail("The capabilities_xml gives an extra arch "
                                     "of guest to support!")

        # check the type of hyperviosr.
        guest_domain_type = dom.getElementsByTagName('domain')[0]
        guest_domain_type_output = guest_domain_type.getAttribute('type')
        logging.info("Hypervisor (capabilities_xml):%s",
                     guest_domain_type_output)
        cmd_result = utils.run("virsh uri", ignore_status=True)
        if not re.search(guest_domain_type_output, cmd_result.stdout.strip()):
            raise error.TestFail("The capabilities_xml gives an different "
                                 "hypervisor")

    connect_uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                              "default"))

    # Prepare libvirtd service
    if params.has_key("libvirtd"):
        libvirtd = params.get("libvirtd")
        if libvirtd == "off":
            utils_libvirtd.libvirtd_stop()

    # Run test case
    option = params.get("virsh_cap_options")
    try:
        output = virsh.capabilities(option, uri=connect_uri,
                                    ignore_status=False, debug=True)
        status = 0  # good
    except error.CmdError:
        status = 1  # bad
        output = ''

    # Recover libvirtd service start
    if libvirtd == "off":
        utils_libvirtd.libvirtd_start()

    # Check status_error
    status_error = params.get("status_error")
    if status_error == "yes":
        if status == 0:
            if libvirtd == "off":
                raise error.TestFail("Command 'virsh capabilities' succeeded "
                                     "with libvirtd service stopped, incorrect")
            else:
                raise error.TestFail("Command 'virsh capabilities %s' succeeded "
                                     "(incorrect command)" % option)
    elif status_error == "no":
        compare_capabilities_xml(output)
        if status != 0:
            raise error.TestFail("Command 'virsh capabilities %s' failed "
                                 "(correct command)" % option)
Exemplo n.º 6
0
def run(test, params, env):
    """
    Test misc tests of virtual cpu features

    1) check dumpxml after snapshot-create/revert
    2) check vendor_id
    3) check maximum vcpus with topology settings

    :param test: test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """
    def update_cpu_xml():
        """
        Update cpu xml for test
        """
        vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)

        # Create cpu xml for test
        if vmxml.xmltreefile.find('cpu'):
            cpu_xml = vmxml.cpu
        else:
            cpu_xml = vm_xml.VMCPUXML()
        if cpu_mode:
            cpu_xml.mode = cpu_mode
        if cpu_vendor_id:
            cpu_xml.vendor_id = cpu_vendor_id

        # Update vm's cpu
        vmxml.cpu = cpu_xml
        vmxml.sync()

        if vcpu_max:
            if with_topology:
                vm_xml.VMXML.set_vm_vcpus(vm_name,
                                          int(vcpu_max),
                                          cores=int(vcpu_max),
                                          sockets=1,
                                          threads=1,
                                          add_topology=with_topology,
                                          topology_correction=with_topology)
            else:
                vm_xml.VMXML.set_vm_vcpus(vm_name, int(vcpu_max))

    def do_snapshot(vm_name, expected_str):
        """
        Run snapshot related commands: snapshot-create-as, snapshot-list
        snapshot-dumpxml, snapshot-revert

        :param vm_name: vm name
        :param expected_str: expected string in snapshot-dumpxml
        :raise: test.fail if virsh command failed
        """
        snapshot_name = vm_name + "-snap"
        virsh_dargs = {'debug': True}

        cmd_result = virsh.snapshot_create_as(vm_name, snapshot_name,
                                              **virsh_dargs)
        libvirt.check_exit_status(cmd_result)

        try:
            snapshots = virsh.snapshot_list(vm_name, **virsh_dargs)
        except process.CmdError:
            test.fail("Failed to get snapshots list for %s" % vm_name)
        if snapshot_name not in snapshots:
            test.fail("The snapshot '%s' was not in snapshot-list." %
                      snapshot_name)
        cmd_result = virsh.snapshot_dumpxml(vm_name, snapshot_name,
                                            **virsh_dargs)
        libvirt.check_result(cmd_result, expected_match=expected_str)

        cmd_result = virsh.snapshot_revert(vm_name, "", "--current",
                                           **virsh_dargs)
        libvirt.check_exit_status(cmd_result)

    libvirt_version.is_libvirt_feature_supported(params)
    vm_name = params.get('main_vm')
    vm = env.get_vm(vm_name)

    cpu_mode = params.get('cpu_mode')
    vcpu_max = params.get('vcpu_max')
    expected_str_before_startup = params.get("expected_str_before_startup")
    expected_str_after_startup = params.get("expected_str_after_startup")

    test_operations = params.get("test_operations")
    check_vendor_id = "yes" == params.get("check_vendor_id", "no")
    virsh_edit_cmd = params.get("virsh_edit_cmd")
    with_topology = "yes" == params.get("with_topology", "no")

    status_error = "yes" == params.get("status_error", "no")
    err_msg = params.get("err_msg")

    cpu_vendor_id = None
    expected_qemuline = None
    cmd_in_guest = params.get("cmd_in_guest")

    bkxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)

    try:
        if check_vendor_id:
            output = virsh.capabilities(debug=True)
            host_vendor = re.findall(r'<vendor>(\w+)<', output)[0]

            cpu_vendor_id = 'GenuineIntel'
            if host_vendor != "Intel":
                cpu_vendor_id = 'AuthenticAMD'
            logging.debug("Set cpu vendor_id to %s on this host.",
                          cpu_vendor_id)

            expected_qemuline = "vendor=" + cpu_vendor_id
            cmd_in_guest = ("cat /proc/cpuinfo | grep vendor_id | grep {}".
                            format(cpu_vendor_id))

        # Update xml for test
        update_cpu_xml()

        vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
        logging.debug("Pre-test xml is %s", vmxml.xmltreefile)

        if expected_str_before_startup:
            libvirt.check_dumpxml(vm, expected_str_before_startup)

        if test_operations:
            for action in test_operations.split(","):
                if action == "do_snapshot":
                    do_snapshot(vm_name, expected_str_before_startup)

        if virsh_edit_cmd:
            status = libvirt.exec_virsh_edit(vm_name,
                                             virsh_edit_cmd.split(","))
            if status == status_error:
                test.fail("Virsh edit got unexpected result.")

        # Check if vm could start successfully
        if not status_error:
            result = virsh.start(vm_name, debug=True)
            libvirt.check_exit_status(result)

            if expected_str_after_startup:
                libvirt.check_dumpxml(vm, expected_str_after_startup)

            if expected_qemuline:
                libvirt.check_qemu_cmd_line(expected_qemuline)

            if cmd_in_guest:
                vm_session = vm.wait_for_login()
                status, output = vm_session.cmd_status_output(cmd_in_guest)
                if status:
                    vm_session.close()
                    test.fail("Failed to run '{}' in vm with "
                              "messages:\n{}".format(cmd_in_guest, output))
                vm_session.close()
                if cpu_mode == 'maximum':
                    check_vm_cpu_model(output.strip(), cmd_in_guest, test)
    finally:
        logging.debug("Recover test environment")
        if vm.is_alive():
            vm.destroy()

        libvirt.clean_up_snapshots(vm_name, domxml=bkxml)
        bkxml.sync()
Exemplo n.º 7
0
def capability_validate(file=None, **virsh_dargs):
    """
    Test for schema capability
    """
    cmd_result = virsh.capabilities(to_file=file, **virsh_dargs)
Exemplo n.º 8
0
def run(test, params, env):
    """
    Test the command virsh capabilities

    (1) Call virsh capabilities
    (2) Call virsh capabilities with an unexpected option
    (3) Call virsh capabilities with libvirtd service stop
    """
    def compare_capabilities_xml(source):
        cap_xml = capability_xml.CapabilityXML()
        cap_xml.xml = source

        # Check that host has a non-empty UUID tag.
        xml_uuid = cap_xml.uuid
        logging.debug("Host UUID (capabilities_xml): %s", xml_uuid)
        if xml_uuid == "":
            raise error.TestFail("The host uuid in capabilities_xml is none!")

        # Check the host arch.
        xml_arch = cap_xml.arch
        logging.debug("Host arch (capabilities_xml): %s", xml_arch)
        exp_arch = process.run("arch", shell=True).stdout.strip()
        if cmp(xml_arch, exp_arch) != 0:
            raise error.TestFail("The host arch in capabilities_xml is "
                                 "expected to be %s, but get %s" %
                                 (exp_arch, xml_arch))

        # Check the host cpu count.
        xml_cpu_count = cap_xml.cpu_count
        logging.debug("Host cpus count (capabilities_xml): %s", xml_cpu_count)
        cmd = "grep processor /proc/cpuinfo | wc -l"
        exp_cpu_count = int(process.run(cmd, shell=True).stdout.strip())
        if xml_cpu_count != exp_cpu_count:
            raise error.TestFail("Host cpus count is expected to be %s, "
                                 "but get %s" %
                                 (exp_cpu_count, xml_cpu_count))

        # Check the arch of guest supported.
        guest_capa = cap_xml.get_guest_capabilities()
        logging.debug(guest_capa)

        # libvirt track wordsize in hardcode struct virArchData
        wordsize = {}
        wordsize['64'] = ['alpha', 'aarch64', 'ia64', 'mips64', 'mips64el',
                          'parisc64', 'ppc64', 'ppc64le', 's390x', 'sh4eb',
                          'sparc64', 'x86_64']
        wordsize['32'] = ['armv6l', 'armv7l', 'armv7b', 'cris', 'i686', 'lm32',
                          'm68k', 'microblaze', 'microblazeel', 'mips',
                          'mipsel', 'openrisc', 'parisc', 'ppc', 'ppcle',
                          'ppcemb', 's390', 'sh4', 'sparc', 'unicore32',
                          'xtensa', 'xtensaeb']
        uri_type = process.run("virsh uri", shell=True).stdout.split(':')[0]
        domain_type = "domain_" + uri_type
        for arch_dict in guest_capa.values():
            for arch, val_dict in arch_dict.items():
                # Check wordsize
                if arch not in wordsize[val_dict['wordsize']]:
                    raise error.TestFail("'%s' wordsize '%s' in "
                                         "capabilities_xml not expected" %
                                         (arch, val_dict['wordsize']))
                # Check the type of hypervisor
                if domain_type not in val_dict.keys():
                    raise error.TestFail("domain type '%s' is not matched"
                                         " under arch '%s' in "
                                         "capabilities_xml" %
                                         (uri_type, arch))

        # check power management support.
        try:
            pm_cmd = os_dep.command('pm-is-supported')
            pm_cap_map = {'suspend': 'suspend_mem',
                          'hibernate': 'suspend_disk',
                          'suspend-hybrid': 'suspend_hybrid'}
            exp_pms = []
            for opt in pm_cap_map:
                cmd = '%s --%s' % (pm_cmd, opt)
                res = process.run(cmd, ignore_status=True, shell=True)
                if res.exit_status == 0:
                    exp_pms.append(pm_cap_map[opt])
            pms = cap_xml.power_management_list
            if set(exp_pms) != set(pms):
                raise error.TestFail("Expected supported PMs are %s, got %s "
                                     "instead." % (exp_pms, pms))
        except ValueError:
            logging.debug('Power management checking is skipped, since command'
                          ' pm-is-supported is not found.')

    connect_uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                              "default"))

    # Prepare libvirtd service
    if "libvirtd" in params:
        libvirtd = params.get("libvirtd")
        if libvirtd == "off":
            utils_libvirtd.libvirtd_stop()

    # Run test case
    option = params.get("virsh_cap_options")
    try:
        output = virsh.capabilities(option, uri=connect_uri,
                                    ignore_status=False, debug=True)
        status = 0  # good
    except process.CmdError:
        status = 1  # bad
        output = ''

    # Recover libvirtd service start
    if libvirtd == "off":
        utils_libvirtd.libvirtd_start()

    # Check status_error
    status_error = params.get("status_error")
    if status_error == "yes":
        if status == 0:
            if libvirtd == "off":
                raise error.TestFail("Command 'virsh capabilities' succeeded "
                                     "with libvirtd service stopped, "
                                     "incorrect")
            else:
                raise error.TestFail("Command 'virsh capabilities %s' "
                                     "succeeded (incorrect command)" % option)
    elif status_error == "no":
        compare_capabilities_xml(output)
        if status != 0:
            raise error.TestFail("Command 'virsh capabilities %s' failed "
                                 "(correct command)" % option)
Exemplo n.º 9
0
def run(test, params, env):
    """
    Test the command virsh capabilities

    (1) Call virsh capabilities
    (2) Call virsh capabilities with an unexpected option
    (3) Call virsh capabilities with libvirtd service stop
    """
    def compare_capabilities_xml(source):
        cap_xml = capability_xml.CapabilityXML()
        cap_xml.xml = source

        # Check that host has a non-empty UUID tag.
        xml_uuid = cap_xml.uuid
        logging.debug("Host UUID (capabilities_xml): %s", xml_uuid)
        if xml_uuid == "":
            test.fail("The host uuid in capabilities_xml is none!")

        # Check the host arch.
        xml_arch = cap_xml.arch
        logging.debug("Host arch (capabilities_xml): %s", xml_arch)
        exp_arch = process.run("arch", shell=True).stdout.strip()
        if cmp(xml_arch, exp_arch) != 0:
            test.fail("The host arch in capabilities_xml is "
                      "expected to be %s, but get %s" %
                      (exp_arch, xml_arch))

        # Check the host cpu count.
        xml_cpu_count = cap_xml.cpu_count
        logging.debug("Host cpus count (capabilities_xml): %s", xml_cpu_count)
        search_str = 'processor'
        if platform.machine() == 's390x':
            search_str = 'cpu number'
        cmd = "grep '%s' /proc/cpuinfo | wc -l" % search_str
        exp_cpu_count = int(process.run(cmd, shell=True).stdout.strip())
        if xml_cpu_count != exp_cpu_count:
            test.fail("Host cpus count is expected to be %s, "
                      "but get %s" %
                      (exp_cpu_count, xml_cpu_count))

        # Check the arch of guest supported.
        guest_capa = cap_xml.get_guest_capabilities()
        logging.debug(guest_capa)

        # libvirt track wordsize in hardcode struct virArchData
        wordsize = {}
        wordsize['64'] = ['alpha', 'aarch64', 'ia64', 'mips64', 'mips64el',
                          'parisc64', 'ppc64', 'ppc64le', 's390x', 'sh4eb',
                          'sparc64', 'x86_64']
        wordsize['32'] = ['armv6l', 'armv7l', 'armv7b', 'cris', 'i686', 'lm32',
                          'm68k', 'microblaze', 'microblazeel', 'mips',
                          'mipsel', 'openrisc', 'parisc', 'ppc', 'ppcle',
                          'ppcemb', 's390', 'sh4', 'sparc', 'unicore32',
                          'xtensa', 'xtensaeb']
        uri_type = process.run("virsh uri", shell=True).stdout.split(':')[0]
        domain_type = "domain_" + uri_type
        for arch_dict in list(itervalues(guest_capa)):
            for arch, val_dict in list(iteritems(arch_dict)):
                # Check wordsize
                if arch not in wordsize[val_dict['wordsize']]:
                    test.fail("'%s' wordsize '%s' in "
                              "capabilities_xml not expected" %
                              (arch, val_dict['wordsize']))
                # Check the type of hypervisor
                if domain_type not in list(val_dict.keys()):
                    test.fail("domain type '%s' is not matched"
                              " under arch '%s' in "
                              "capabilities_xml" %
                              (uri_type, arch))

        # check power management support.
        try:
            pm_cmd = path.find_command('pm-is-supported')
            pm_cap_map = {'suspend': 'suspend_mem',
                          'hibernate': 'suspend_disk',
                          'suspend-hybrid': 'suspend_hybrid'}
            exp_pms = []
            for opt in pm_cap_map:
                cmd = '%s --%s' % (pm_cmd, opt)
                res = process.run(cmd, ignore_status=True, shell=True)
                if res.exit_status == 0:
                    exp_pms.append(pm_cap_map[opt])
            pms = cap_xml.power_management_list
            if set(exp_pms) != set(pms):
                test.fail("Expected supported PMs are %s, got %s "
                          "instead." % (exp_pms, pms))
        except path.CmdNotFoundError:
            logging.debug('Power management checking is skipped, since command'
                          ' pm-is-supported is not found.')

    connect_uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                              "default"))

    # Prepare libvirtd service
    if "libvirtd" in params:
        libvirtd = params.get("libvirtd")
        if libvirtd == "off":
            utils_libvirtd.libvirtd_stop()

    # Run test case
    option = params.get("virsh_cap_options")
    try:
        output = virsh.capabilities(option, uri=connect_uri,
                                    ignore_status=False, debug=True)
        status = 0  # good
    except process.CmdError:
        status = 1  # bad
        output = ''

    # Recover libvirtd service start
    if libvirtd == "off":
        utils_libvirtd.libvirtd_start()

    # Check status_error
    status_error = params.get("status_error")
    if status_error == "yes":
        if status == 0:
            if libvirtd == "off":
                test.fail("Command 'virsh capabilities' succeeded "
                          "with libvirtd service stopped, "
                          "incorrect")
            else:
                test.fail("Command 'virsh capabilities %s' "
                          "succeeded (incorrect command)" % option)
    elif status_error == "no":
        compare_capabilities_xml(output)
        if status != 0:
            test.fail("Command 'virsh capabilities %s' failed "
                      "(correct command)" % option)
Exemplo n.º 10
0
def run(test, params, env):
    """
    Test misc tests of virtual cpu features

    1) check dumpxml after snapshot-create/revert

    :param test: test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """

    def do_snapshot(vm_name, expected_str):
        """
        Run snapshot related commands: snapshot-create-as, snapshot-list
        snapshot-dumpxml, snapshot-revert

        :param vm_name: vm name
        :param expected_str: expected string in snapshot-dumpxml
        :raise: test.fail if virsh command failed
        """
        snapshot_name = vm_name + "-snap"
        virsh_dargs = {'debug': True}

        cmd_result = virsh.snapshot_create_as(vm_name, snapshot_name,
                                              **virsh_dargs)
        libvirt.check_exit_status(cmd_result)

        try:
            snapshots = virsh.snapshot_list(vm_name, **virsh_dargs)
        except process.CmdError:
            test.fail("Failed to get snapshots list for %s" % vm_name)
        if snapshot_name not in snapshots:
            test.fail("The snapshot '%s' was not in snapshot-list."
                      % snapshot_name)
        cmd_result = virsh.snapshot_dumpxml(vm_name, snapshot_name,
                                            **virsh_dargs)
        libvirt.check_result(cmd_result, expected_match=expected_str)

        cmd_result = virsh.snapshot_revert(vm_name, "", "--current",
                                           **virsh_dargs)
        libvirt.check_exit_status(cmd_result)

    vm_name = params.get('main_vm')
    vm = env.get_vm(vm_name)

    cpu_mode = params.get('cpu_mode')
    cpu_vendor_id = params.get("vendor_id")
    expected_str_before_startup = params.get("expected_str_before_startup")
    expected_str_after_startup = params.get("expected_str_after_startup")
    expected_qemuline = params.get("expected_qemuline")
    cmd_in_guest = params.get("cmd_in_guest")
    test_operations = params.get("test_operations")
    status_error = "yes" == params.get("status_error", "no")
    err_msg = params.get("err_msg")

    bkxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)

    try:
        if cpu_vendor_id:
            output = virsh.capabilities(debug=True)
            host_vendor = re.findall(r'<vendor>(\w+)<', output)[0]
            if not re.search(host_vendor, cpu_vendor_id, re.IGNORECASE):
                test.cancel("Not supported cpu vendor_id {} on this host."
                            .format(cpu_vendor_id))

        vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)

        # Create cpu xml for test
        if vmxml.xmltreefile.find('cpu'):
            cpu_xml = vmxml.cpu
        else:
            cpu_xml = vm_xml.VMCPUXML()
        if cpu_mode:
            cpu_xml.mode = cpu_mode
        if cpu_vendor_id:
            cpu_xml.vendor_id = cpu_vendor_id

        # Update vm's cpu
        vmxml.cpu = cpu_xml

        vmxml.sync()

        if expected_str_before_startup:
            libvirt.check_dumpxml(vm, expected_str_before_startup)

        if test_operations:
            for action in test_operations.split(","):
                if action == "do_snapshot":
                    do_snapshot(vm_name, expected_str_before_startup)

        # Check if vm could start successfully
        result = virsh.start(vm_name, debug=True)
        libvirt.check_exit_status(result)

        if expected_str_after_startup:
            libvirt.check_dumpxml(vm, expected_str_after_startup)

        if expected_qemuline:
            libvirt.check_qemu_cmd_line(expected_qemuline)

        if cmd_in_guest:
            vm_session = vm.wait_for_login()
            if vm_session.cmd_status(cmd_in_guest):
                vm_session.close()
                test.fail("Failed to run '%s' in vm." % cmd_in_guest)
            vm_session.close()

    finally:
        logging.debug("Recover test environment")
        if vm.is_alive():
            vm.destroy()

        libvirt.clean_up_snapshots(vm_name, domxml=bkxml)
        bkxml.sync()
Exemplo n.º 11
0
def run(test, params, env):
    """
    Test misc tests of virtual cpu features

    1) check dumpxml after snapshot-create/revert
    2) check vendor_id
    3) check maximum vcpus with topology settings

    :param test: test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """
    def update_cpu_xml():
        """
        Update cpu xml for test
        """
        vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)

        # Create cpu xml for test
        if vmxml.xmltreefile.find('cpu'):
            cpu_xml = vmxml.cpu
        else:
            cpu_xml = vm_xml.VMCPUXML()

        if customize_cpu_features:
            for idx in range(len(cpu_xml.get_feature_list()) - 1, -1, -1):
                cpu_xml.remove_feature(idx)
            domcapa_xml = domcapability_xml.DomCapabilityXML()
            features = domcapa_xml.get_additional_feature_list(
                'host-model', ignore_features=None)
            for feature in features:
                for feature_name, feature_policy in feature.items():
                    # For host-passthrough mode, adding "invtsc" requires
                    # more settings, so it will be ignored.
                    if feature_name != "invtsc":
                        cpu_xml.add_feature(feature_name, feature_policy)

        if cpu_mode:
            cpu_xml.mode = cpu_mode
        if cpu_vendor_id:
            cpu_xml.vendor_id = cpu_vendor_id

        # Update vm's cpu
        vmxml.cpu = cpu_xml
        vmxml.sync()

        if vcpu_max:
            if with_topology:
                vm_xml.VMXML.set_vm_vcpus(vm_name,
                                          int(vcpu_max),
                                          cores=int(vcpu_max),
                                          sockets=1,
                                          threads=1,
                                          add_topology=with_topology,
                                          topology_correction=with_topology)
            else:
                vm_xml.VMXML.set_vm_vcpus(vm_name, int(vcpu_max))

    def do_snapshot(vm_name, expected_str):
        """
        Run snapshot related commands: snapshot-create-as, snapshot-list
        snapshot-dumpxml, snapshot-revert

        :param vm_name: vm name
        :param expected_str: expected string in snapshot-dumpxml
        :raise: test.fail if virsh command failed
        """
        snapshot_name = vm_name + "-snap"
        virsh_dargs = {'debug': True}

        cmd_result = virsh.snapshot_create_as(vm_name, snapshot_name,
                                              **virsh_dargs)
        libvirt.check_exit_status(cmd_result)

        try:
            snapshots = virsh.snapshot_list(vm_name, **virsh_dargs)
        except process.CmdError:
            test.fail("Failed to get snapshots list for %s" % vm_name)
        if snapshot_name not in snapshots:
            test.fail("The snapshot '%s' was not in snapshot-list." %
                      snapshot_name)
        cmd_result = virsh.snapshot_dumpxml(vm_name, snapshot_name,
                                            **virsh_dargs)
        libvirt.check_result(cmd_result, expected_match=expected_str)

        cmd_result = virsh.snapshot_revert(vm_name, "", "--current",
                                           **virsh_dargs)
        libvirt.check_exit_status(cmd_result)

    def check_feature_list(vm, original_dict):
        """
        Compare new cpu feature list and original cpu

        :param vm: VM object
        :original_dict: Cpu feature dict , {"name1":"policy1","name2":"policy2"}
        """
        new_cpu_xml = vm_xml.VMXML.new_from_dumpxml(vm.name).cpu
        new_feature_dict = new_cpu_xml.get_dict_type_feature()
        if new_feature_dict != original_dict:
            test.fail('CPU feature lists are different, original is :%s,'
                      ' new is %s:' % (original_dict, new_feature_dict))

    libvirt_version.is_libvirt_feature_supported(params)
    vm_name = params.get('main_vm')
    vm = env.get_vm(vm_name)

    cpu_mode = params.get('cpu_mode')
    vcpu_max = params.get('vcpu_max')
    expected_str_before_startup = params.get("expected_str_before_startup")
    expected_str_after_startup = params.get("expected_str_after_startup")

    test_operations = params.get("test_operations")
    check_vendor_id = "yes" == params.get("check_vendor_id", "no")
    virsh_edit_cmd = params.get("virsh_edit_cmd")
    with_topology = "yes" == params.get("with_topology", "no")

    status_error = "yes" == params.get("status_error", "no")
    err_msg = params.get("err_msg")

    cpu_vendor_id = None
    expected_qemuline = None
    cmd_in_guest = params.get("cmd_in_guest")
    customize_cpu_features = "yes" == params.get("customize_cpu_features",
                                                 "no")
    bkxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
    managed_save_file = "/var/lib/libvirt/qemu/save/%s.save" % vm_name

    try:
        if check_vendor_id:
            output = virsh.capabilities(debug=True)
            host_vendor = re.findall(r'<vendor>(\w+)<', output)[0]

            cpu_vendor_id = 'GenuineIntel'
            if host_vendor != "Intel":
                cpu_vendor_id = 'AuthenticAMD'
            logging.debug("Set cpu vendor_id to %s on this host.",
                          cpu_vendor_id)

            expected_qemuline = "vendor=" + cpu_vendor_id
            cmd_in_guest = ("cat /proc/cpuinfo | grep vendor_id | grep {}".
                            format(cpu_vendor_id))

        # Update xml for test
        update_cpu_xml()

        vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
        logging.debug("Pre-test xml is %s", vmxml.xmltreefile)
        cpu_xml = vmxml.cpu
        feature_dict = cpu_xml.get_dict_type_feature()

        if expected_str_before_startup:
            libvirt.check_dumpxml(vm, expected_str_before_startup)

        if test_operations:
            for action in test_operations.split(","):
                if action == "do_snapshot":
                    do_snapshot(vm_name, expected_str_before_startup)

        if virsh_edit_cmd:
            status = libvirt.exec_virsh_edit(vm_name,
                                             virsh_edit_cmd.split(","))
            if status == status_error:
                test.fail("Virsh edit got unexpected result.")

        # Check if vm could start successfully
        if not status_error:
            result = virsh.start(vm_name, debug=True)
            libvirt.check_exit_status(result)

            if expected_str_after_startup:
                libvirt.check_dumpxml(vm, expected_str_after_startup)

            if expected_qemuline:
                libvirt.check_qemu_cmd_line(expected_qemuline)

            if cmd_in_guest:
                vm_session = vm.wait_for_login()
                status, output = vm_session.cmd_status_output(cmd_in_guest)
                if status:
                    vm_session.close()
                    test.fail("Failed to run '{}' in vm with "
                              "messages:\n{}".format(cmd_in_guest, output))
                vm_session.close()
                if cpu_mode == 'maximum':
                    check_vm_cpu_model(output.strip(), cmd_in_guest, test)

            # Add case: Check cpu xml after domain Managedsaved and restored
            if test_operations:
                for item in test_operations.split(','):
                    if item == "managedsave_restore":
                        # (1)Domain Manage saved
                        virsh.managedsave(vm_name,
                                          ignore_status=False,
                                          debug=True)
                        check_feature_list(vm, feature_dict)
                        # (2)Domain Restore
                        virsh.restore(managed_save_file,
                                      ignore_status=False,
                                      debug=True)
                        # (5)Check mode and feature list here
                        libvirt.check_dumpxml(vm, cpu_mode)
                        check_feature_list(vm, feature_dict)

    finally:
        logging.debug("Recover test environment")
        if os.path.exists(managed_save_file):
            virsh.managedsave_remove(vm_name, debug=True)
        if vm.is_alive():
            vm.destroy()
        libvirt.clean_up_snapshots(vm_name, domxml=bkxml)
        bkxml.sync()
def run(test, params, env):
    """
    Test command: virsh hypervisor-cpu-compare

    Compare CPU provided by hypervisor on the host with a CPU described by an XML file
    1.Get all parameters from configuration.
    2.Prepare temp file saves of CPU information.
    3.Perform virsh hypervisor-cpu-compare operation.
    4.Confirm the result.
    """

    # Get all parameters.
    file_type = params.get("compare_file_type", "domxml")
    extract_mode = ("yes" == params.get("extract_mode", "no"))
    action_mode = params.get("action_mode")
    cpu_mode = params.get("cpu_mode", "custom")
    illegal_cpu_test = ("yes" == params.get("illegal_cpu_test", "no"))
    status_error = ("yes" == params.get("status_error", "no"))
    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)

    option_str = params.get("hypv_cpu_compare_option")
    invalid_option = params.get("invalid_option")
    invalid_value = params.get("invalid_value")
    if invalid_option:
        option_str = option_str.replace(invalid_option, "")

    if not libvirt_version.version_compare(4, 4, 0):
        test.cancel("hypervisor-cpu-compare does not support"
                    " in this libvirt version")

    if not vm.is_alive():
        vm.start()

    dom_xml = vm_xml.VMXML.new_from_dumpxml(vm_name)
    backup_xml = dom_xml.copy()
    compare_file = os.path.join(data_dir.get_tmp_dir(), "cpu.xml")
    domcapa_file = os.path.join(data_dir.get_tmp_dir(), "tmp_file")

    def get_domain_output(cpu_mode):
        """
        Prepare domain xml according cpu mode

        :param cpu_mode: The name of cpu mode
        :return: The domain xml data
        """
        try:
            cpuxml = dom_xml.cpu
            if not action_mode and cpuxml.mode == cpu_mode:
                return dom_xml.xmltreefile.get_element_string("/")
            else:
                del dom_xml["cpu"]
        except LibvirtXMLNotFoundError:
            pass  # CPU already does not exist

        # Create new CPUXML
        cpuxml = vm_xml.VMCPUXML()
        cpuxml.mode = cpu_mode
        if cpu_mode == "custom":
            # Customize cpu according domcapabilities xml
            domcapa_output = get_domcapa_output(test)
            with open(domcapa_file, "w+") as tmp_f:
                tmp_f.write(domcapa_output)
            ret = virsh.cpu_baseline(domcapa_file)
            if ret.exit_status:
                test.fail("Fail to run virsh cpu-baseline: %s"
                          % ret.stderr.strip())
            cpuxml.xml = ret.stdout.strip()

        if cpu_mode == "host-passthrough":
            cpuxml.check = "none"

        dom_xml.cpu = cpuxml
        dom_xml.sync()
        vm.start()
        # VM start will change domxml content
        v_xml = vm_xml.VMXML.new_from_dumpxml(vm_name)
        return v_xml.xmltreefile.get_element_string("/")

    def get_options(option_str):
        """
        Prepare virsh cmd options according input string

        :param option_str: Input option string contains option names
        :return: Virsh cmd options
        """
        options = ""
        emulator = dom_xml.devices.by_device_tag('emulator')[0]
        osxml = dom_xml.os
        if option_str.count("--virttype"):
            options += "--virttype %s " % dom_xml.hypervisor_type
        if option_str.count("--emulator"):
            options += "--emulator %s " % emulator.path
        if option_str.count("--arch"):
            options += "--arch %s " % osxml.arch
        if option_str.count("--machine"):
            options += "--machine %s " % osxml.machine
        if option_str.count("--error"):
            options += "--error "
        return options

    try:
        # Prepare options
        options = get_options(option_str)
        if invalid_option:
            options += "%s %s " % (invalid_option, invalid_value)

        # Prepare cpu compare file.
        cpu_data = ""
        if file_type == "domxml":
            cpu_data = get_domain_output(cpu_mode)
        elif file_type == "domcapa_xml":
            cpu_data = get_domcapa_output(test)
        elif file_type == "capa_xml":
            cpu_data = virsh.capabilities()
        else:
            test.error("The compare file type %s is unsupported" % file_type)

        # Extract cpu definition
        if extract_mode:
            cpu_data = get_cpu_definition(file_type, vm_name, test)
            if illegal_cpu_test and file_type == "domxml":
                # Make invalid cpu data by adding <host> outside of <cpu>
                cpu_data = "<host>{}</host>".format(cpu_data)

        with open(compare_file, "w+") as compare_file_f:
            compare_file_f.write(cpu_data)
            compare_file_f.flush()
            compare_file_f.seek(0)
            logging.debug("CPU description XML:\n%s", compare_file_f.read())

        # Perform virsh cpu-compare operation.
        result = virsh.hypervisor_cpu_compare(xml_file=compare_file, options=options, ignore_status=True, debug=True)
        msg_pattern = params.get("msg_pattern")

        # Check result
        if status_error and not result.exit_status:
            test.fail("Expect should fail but got:\n%s" % result.stdout)
        elif not status_error and result.exit_status:
            test.fail("Expect success but got:\n%s" % result.stderr)

        if msg_pattern:
            logging.debug("Expect key word in comand output: %s", msg_pattern)
            output = result.stdout.strip()
            if not output:
                output = result.stderr.strip()
            if not output.count(msg_pattern):
                test.fail("Not find expect key word in command output")
    finally:
        backup_xml.sync()
        if os.path.exists(domcapa_file):
            os.remove(domcapa_file)
        if os.path.exists(compare_file):
            os.remove(compare_file)
Exemplo n.º 13
0
def run(test, params, env):
    """
    Test the command virsh capabilities

    (1) Call virsh capabilities
    (2) Call virsh capabilities with an unexpected option
    (3) Call virsh capabilities with libvirtd service stop
    """
    def compare_capabilities_xml(source):
        cap_xml = capability_xml.CapabilityXML()
        cap_xml.xml = source

        # Check that host has a non-empty UUID tag.
        xml_uuid = cap_xml.uuid
        logging.debug("Host UUID (capabilities_xml): %s" % xml_uuid)
        if xml_uuid == "":
            raise error.TestFail("The host uuid in capabilities_xml is none!")

        # Check the host arch.
        xml_arch = cap_xml.arch
        logging.debug("Host arch (capabilities_xml): %s", xml_arch)
        exp_arch = utils.run("arch", ignore_status=True).stdout.strip()
        if cmp(xml_arch, exp_arch) != 0:
            raise error.TestFail("The host arch in capabilities_xml is expected"
                                 " to be %s, but get %s" % (exp_arch, xml_arch))

        # Check the host cpu count.
        xml_cpu_count = cap_xml.cpu_count
        logging.debug("Host cpus count (capabilities_xml): %s", xml_cpu_count)
        cmd = "grep processor /proc/cpuinfo | wc -l"
        exp_cpu_count = int(utils.run(cmd, ignore_status=True).stdout.strip())
        if xml_cpu_count != exp_cpu_count:
            raise error.TestFail("Host cpus count is expected to be %s, but get "
                                 "%s" % (exp_cpu_count, xml_cpu_count))

        # Check the arch of guest supported.
        xmltreefile = cap_xml.__dict_get__('xml')
        xml_os_arch_machine_map = cap_xml.os_arch_machine_map
        logging.debug(xml_os_arch_machine_map['hvm'])
        try:
            img = utils_misc.find_command("qemu-kvm")
        except ValueError:
            raise error.TestNAError("Cannot find qemu-kvm")
        cmd = img + " --cpu ? | grep qemu"
        cmd_result = utils.run(cmd, ignore_status=True)
        for guest in xmltreefile.findall('guest'):
            guest_wordsize = guest.find('arch').find('wordsize').text
            logging.debug("Arch of guest supported (capabilities_xml):%s",
                          guest_wordsize)
            if not re.search(guest_wordsize, cmd_result.stdout.strip()):
                raise error.TestFail("The capabilities_xml gives an extra arch "
                                     "of guest to support!")

        # Check the type of hypervisor.
        first_guest = xmltreefile.findall('guest')[0]
        first_domain = first_guest.find('arch').findall('domain')[0]
        guest_domain_type = first_domain.get('type')
        logging.debug("Hypervisor (capabilities_xml):%s", guest_domain_type)
        cmd_result = utils.run("virsh uri", ignore_status=True)
        if not re.search(guest_domain_type, cmd_result.stdout.strip()):
            raise error.TestFail("The capabilities_xml gives an different "
                                 "hypervisor")

        # check power management support.
        try:
            pm_cmd = os_dep.command('pm-is-supported')
            pm_cap_map = {'suspend': 'suspend_mem',
                          'hibernate': 'suspend_disk',
                          'suspend-hybrid': 'suspend_hybrid',
                          }
            exp_pms = []
            for opt in pm_cap_map:
                cmd = '%s --%s' % (pm_cmd, opt)
                res = utils.run(cmd, ignore_status=True)
                if res.exit_status == 0:
                    exp_pms.append(pm_cap_map[opt])
            pms = cap_xml.power_management_list
            if set(exp_pms) != set(pms):
                raise error.TestFail("Expected supported PMs are %s, got %s "
                                     "instead." % (exp_pms, pms))
        except ValueError:
            logging.debug('Power management checking is skipped, since command '
                          'pm-is-supported is not found.')

    connect_uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                              "default"))

    # Prepare libvirtd service
    if "libvirtd" in params:
        libvirtd = params.get("libvirtd")
        if libvirtd == "off":
            utils_libvirtd.libvirtd_stop()

    # Run test case
    option = params.get("virsh_cap_options")
    try:
        output = virsh.capabilities(option, uri=connect_uri,
                                    ignore_status=False, debug=True)
        status = 0  # good
    except error.CmdError:
        status = 1  # bad
        output = ''

    # Recover libvirtd service start
    if libvirtd == "off":
        utils_libvirtd.libvirtd_start()

    # Check status_error
    status_error = params.get("status_error")
    if status_error == "yes":
        if status == 0:
            if libvirtd == "off":
                raise error.TestFail("Command 'virsh capabilities' succeeded "
                                     "with libvirtd service stopped, incorrect")
            else:
                raise error.TestFail("Command 'virsh capabilities %s' succeeded "
                                     "(incorrect command)" % option)
    elif status_error == "no":
        compare_capabilities_xml(output)
        if status != 0:
            raise error.TestFail("Command 'virsh capabilities %s' failed "
                                 "(correct command)" % option)
Exemplo n.º 14
0
 def __new__(cls):
     if cls._XML is None:
         cls._XML = virsh.capabilities()
     # older python super doesn't work on class objects
     return LibvirtXMLBase.__new__(cls)
Exemplo n.º 15
0
def run_virsh_capabilities(test, params, env):
    """
    Test the command virsh capabilities

    (1) Call virsh capabilities
    (2) Call virsh capabilities with an unexpected option
    (3) Call virsh capabilities with libvirtd service stop
    """
    def compare_capabilities_xml(source):
        dom = parseString(source)
        host = dom.getElementsByTagName('host')[0]
        # check that host has a non-empty UUID tag.
        uuid = host.getElementsByTagName('uuid')[0]
        host_uuid_output = uuid.firstChild.data
        logging.info("Host uuid (capabilities_xml):%s", host_uuid_output)
        if host_uuid_output == "":
            raise error.TestFail("The host uuid in capabilities_xml is none!")

        # check the host arch.
        arch = host.getElementsByTagName('arch')[0]
        host_arch_output = arch.firstChild.data
        logging.info("Host arch (capabilities_xml):%s", host_arch_output)
        cmd_result = utils.run("arch", ignore_status=True)
        if cmp(host_arch_output, cmd_result.stdout.strip()) != 0:
            raise error.TestFail("The host arch in capabilities_xml is wrong!")

        # check the host cpus num.
        cpus = dom.getElementsByTagName('cpus')[0]
        host_cpus_output = cpus.getAttribute('num')
        logging.info("Host cpus num (capabilities_xml):%s",
                      host_cpus_output)
        cmd = "less /proc/cpuinfo | grep processor | wc -l"
        cmd_result = utils.run(cmd, ignore_status=True)
        if cmp(host_cpus_output, cmd_result.stdout.strip()) != 0:
            raise error.TestFail("Host cpus num (capabilities_xml) is "
                                 "wrong")

        # check the arch of guest supported.
        cmd = "/usr/libexec/qemu-kvm  --cpu ? | grep qemu"
        cmd_result = utils.run(cmd, ignore_status=True)
        guest_wordsize_array = dom.getElementsByTagName('wordsize')
        length = len(guest_wordsize_array)
        for i in range(length):
            element = guest_wordsize_array[i]
            guest_wordsize = element.firstChild.data
            logging.info("Arch of guest supported (capabilities_xml):%s",
                         guest_wordsize)
            if not re.search(guest_wordsize, cmd_result.stdout.strip()):
                raise error.TestFail("The capabilities_xml gives an extra arch "
                                     "of guest to support!")

        # check the type of hyperviosr.
        guest_domain_type = dom.getElementsByTagName('domain')[0]
        guest_domain_type_output = guest_domain_type.getAttribute('type')
        logging.info("Hypervisor (capabilities_xml):%s",
                     guest_domain_type_output)
        cmd_result = utils.run("virsh uri", ignore_status=True)
        if not re.search(guest_domain_type_output, cmd_result.stdout.strip()):
            raise error.TestFail("The capabilities_xml gives an different "
                                 "hypervisor")


    connect_uri = libvirt_vm.normalize_connect_uri( params.get("connect_uri",
                                                               "default") )

    # Prepare libvirtd service
    if params.has_key("libvirtd"):
        libvirtd = params.get("libvirtd")
        if libvirtd == "off":
            utils_libvirtd.libvirtd_stop()

    # Run test case
    option = params.get("virsh_cap_options")
    try:
        output = virsh.capabilities(option, uri=connect_uri,
                                    ignore_status=False, debug=True)
        status = 0 # good
    except error.CmdError:
        status = 1 # bad
        output = ''

    # Recover libvirtd service start
    if libvirtd == "off":
        utils_libvirtd.libvirtd_start()

    # Check status_error
    status_error = params.get("status_error")
    if status_error == "yes":
        if status == 0:
            if libvirtd == "off":
                raise error.TestFail("Command 'virsh capabilities' succeeded "
                                     "with libvirtd service stopped, incorrect")
            else:
                raise error.TestFail("Command 'virsh capabilities %s' succeeded "
                                     "(incorrect command)" % option)
    elif status_error == "no":
        compare_capabilities_xml(output)
        if status != 0:
            raise error.TestFail("Command 'virsh capabilities %s' failed "
                                 "(correct command)" % option)