• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python utils_misc.find_command函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中virttest.utils_misc.find_command函数的典型用法代码示例。如果您正苦于以下问题:Python find_command函数的具体用法?Python find_command怎么用?Python find_command使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了find_command函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: create_scsi_disk

def create_scsi_disk(scsi_option, scsi_size="2048"):
    """
    Get the scsi device created by scsi_debug kernel module

    :param scsi_option. The scsi_debug kernel module options.
    :return: scsi device if it is created successfully.
    """
    try:
        utils_misc.find_command("lsscsi")
    except ValueError:
        raise error.TestNAError("Missing command 'lsscsi'.")

    try:
        # Load scsi_debug kernel module.
        # Unload it first if it's already loaded.
        if utils.module_is_loaded("scsi_debug"):
            utils.unload_module("scsi_debug")
        utils.load_module("scsi_debug dev_size_mb=%s %s"
                          % (scsi_size, scsi_option))
        # Get the scsi device name
        scsi_disk = utils.run("lsscsi|grep scsi_debug|"
                              "awk '{print $6}'").stdout.strip()
        logging.info("scsi disk: %s" % scsi_disk)
        return scsi_disk
    except Exception, e:
        logging.error(str(e))
        return None
开发者ID:giuseppe,项目名称:virt-test,代码行数:27,代码来源:libvirt.py


示例2: package_jeos

def package_jeos(img):
    """
    Package JeOS and make it ready for upload.

    Steps:
    1) Move /path/to/jeos.qcow2 to /path/to/jeos.qcow2.backup
    2) Sparsify the image, creating a new, trimmed down /path/to/jeos.qcow2
    3) Compress the sparsified image with 7za

    :param img: Path to a qcow2 image
    """
    basedir = os.path.dirname(img)
    backup = img + '.backup'
    qemu_img = utils_misc.find_command('qemu-img')
    shutil.move(img, backup)
    logging.info("Backup %s saved", backup)

    process.system("%s convert -f qcow2 -O qcow2 %s %s" % (qemu_img, backup, img))
    logging.info("Sparse file %s created successfully", img)

    archiver = utils_misc.find_command('7za')
    compressed_img = img + ".7z"
    process.system("%s a %s %s" % (archiver, compressed_img, img))
    logging.info("JeOS compressed file %s created successfuly",
                 compressed_img)
开发者ID:ChenFanFnst,项目名称:avocado-vt,代码行数:25,代码来源:package_jeos.py


示例3: get_storage_devices

def get_storage_devices():
    """
    Retrieve storage devices list from sysfs.

    :return:      A list contains retrieved storage device names with
                  the same format in virsh.
    """
    devices = []
    try:
        utils_misc.find_command('udevadm')
        storage_path = '/sys/class/block'
        if not os.path.exists(storage_path):
            logging.debug(
                'Storage device path %s doesn`t exists!', storage_path)
            return []
        for device in os.listdir(storage_path):
            info = utils.run(
                'udevadm info %s' % os.path.join(storage_path, device),
                timeout=5, ignore_status=True).stdout
            # Only disk devices are list, not partition
            dev_type = re.search(r'(?<=E: DEVTYPE=)\S*', info)
            if dev_type:
                if dev_type.group(0) == 'disk':
                    # Get disk serial
                    dev_id = re.search(r'(?<=E: ID_SERIAL=)\S*', info)
                    if dev_id:
                        serial = dev_id.group(0)
                        dev_name = 'block_' + device.replace(':', '_')
                        dev_name = re.sub(
                            r'\W', '_', 'block_%s_%s' % (device, serial))
                        devices.append(dev_name)
    except ValueError:
        logging.warning('udevadm not found! Skipping storage test!')
        logging.warning('You can try install it using `yum install udev`')
    return devices
开发者ID:Acidburn0zzz,项目名称:tp-libvirt,代码行数:35,代码来源:virsh_nodedev_list.py


示例4: setup_or_cleanup_iscsi

def setup_or_cleanup_iscsi(is_setup, is_login=True,
                           emulated_image="emulated_iscsi", image_size="1G"):
    """
    Set up(and login iscsi target) or clean up iscsi service on localhost.

    :param is_setup: Boolean value, true for setup, false for cleanup
    :param is_login: Boolean value, true for login, false for not login
    :param emulated_image: name of iscsi device
    :param image_size: emulated image's size
    :return: iscsi device name or iscsi target
    """
    try:
        utils_misc.find_command("tgtadm")
        utils_misc.find_command("iscsiadm")
    except ValueError:
        raise error.TestNAError("Missing command 'tgtadm' and/or 'iscsiadm'.")

    tmpdir = os.path.join(data_dir.get_root_dir(), 'tmp')
    emulated_path = os.path.join(tmpdir, emulated_image)
    emulated_target = "iqn.2001-01.com.virttest:%s.target" % emulated_image
    iscsi_params = {"emulated_image": emulated_path, "target": emulated_target,
                    "image_size": image_size, "iscsi_thread_id": "virt"}
    _iscsi = iscsi.Iscsi(iscsi_params)
    if is_setup:
        sv_status = None
        if utils_misc.selinux_enforcing():
            sv_status = utils_selinux.get_status()
            utils_selinux.set_status("permissive")
        _iscsi.export_target()
        if sv_status is not None:
            utils_selinux.set_status(sv_status)
        if is_login:
            _iscsi.login()
            # The device doesn't necessarily appear instantaneously, so give
            # about 5 seconds for it to appear before giving up
            iscsi_device = utils_misc.wait_for(_iscsi.get_device_name, 5, 0, 1,
                                               "Searching iscsi device name.")
            if iscsi_device:
                logging.debug("iscsi device: %s", iscsi_device)
                return iscsi_device
            if not iscsi_device:
                logging.error("Not find iscsi device.")
            # Cleanup and return "" - caller needs to handle that
            # _iscsi.export_target() will have set the emulated_id and
            # export_flag already on success...
            _iscsi.cleanup()
            utils.run("rm -f %s" % emulated_path)
        else:
            return emulated_target
    else:
        _iscsi.export_flag = True
        _iscsi.emulated_id = _iscsi.get_target_id()
        _iscsi.cleanup()
        utils.run("rm -f %s" % emulated_path)
    return ""
开发者ID:draculus,项目名称:virt-test,代码行数:55,代码来源:libvirt.py


示例5: run

def run(test, params, env):
    """
    Test command: virsh find-storage-pool-sources-as

    1. Prepare env to provide source storage:
       1). For 'netfs' source type, setup nfs server
       2). For 'iscsi' source type, setup iscsi server
       3). For 'logcial' type pool, setup iscsi storage to create vg
    2. Find the pool source by running virsh cmd
    """

    source_type = params.get("source_type", "")
    source_host = params.get("source_host", "localhost")
    source_port = params.get("source_port", "")
    options = params.get("extra_options", "")
    vg_name = params.get("vg_name", "virttest_vg_0")
    ro_flag = "yes" == params.get("readonly_mode", "no")
    status_error = "yes" == params.get("status_error", "no")

    if not source_type:
        raise error.TestFail("Command requires <type> value")

    cleanup_nfs = False
    cleanup_iscsi = False
    cleanup_logical = False

    if source_host == "localhost":
        if source_type == "netfs":
            # Set up nfs
            res = utils_test.libvirt.setup_or_cleanup_nfs(True)
            selinux_bak = res["selinux_status_bak"]
            cleanup_nfs = True
        if source_type in ["iscsi", "logical"]:
            # Do we have the necessary tools?
            try:
                utils_misc.find_command("tgtadm")
                utils_misc.find_command("iscsiadm")
            except ValueError:
                raise error.TestNAError("Command 'tgtadm' and/or 'iscsiadm' "
                                        "is missing. You must install it.")
            # Set up iscsi
            try:
                iscsi_device = utils_test.libvirt.setup_or_cleanup_iscsi(True)
                # If we got nothing, force failure
                if not iscsi_device:
                    raise error.TestFail("Did not setup an iscsi device")
                cleanup_iscsi = True
                if source_type == "logical":
                    # Create VG by using iscsi device
                    lv_utils.vg_create(vg_name, iscsi_device)
                    cleanup_logical = True
            except Exception, detail:
                if cleanup_iscsi:
                    utils_test.libvirt.setup_or_cleanup_iscsi(False)
                raise error.TestFail("iscsi setup failed:\n%s" % detail)
开发者ID:Acidburn0zzz,项目名称:tp-libvirt,代码行数:55,代码来源:virsh_find_storage_pool_sources_as.py


示例6: run

def run(test, params, env):
    """
    Test svirt in virt-clone.
    """
    VIRT_CLONE = None
    try:
        VIRT_CLONE = utils_misc.find_command("virt-clone")
    except ValueError:
        raise error.TestNAError("No virt-clone command found.")

    # Get general variables.
    status_error = ('yes' == params.get("status_error", 'no'))
    host_sestatus = params.get("svirt_virt_clone_host_selinux", "enforcing")
    # Get variables about seclabel for VM.
    sec_type = params.get("svirt_virt_clone_vm_sec_type", "dynamic")
    sec_model = params.get("svirt_virt_clone_vm_sec_model", "selinux")
    sec_label = params.get("svirt_virt_clone_vm_sec_label", None)
    sec_relabel = params.get("svirt_virt_clone_vm_sec_relabel", "yes")
    sec_dict = {'type': sec_type, 'model': sec_model, 'label': sec_label,
                'relabel': sec_relabel}
    # Get variables about VM and get a VM object and VMXML instance.
    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    vmxml = VMXML.new_from_inactive_dumpxml(vm_name)
    backup_xml = vmxml.copy()

    # Get varialbles about image.
    img_label = params.get('svirt_virt_clone_disk_label')
    # Label the disks of VM with img_label.
    disks = vm.get_disk_devices()
    backup_labels_of_disks = {}
    for disk in disks.values():
        disk_path = disk['source']
        backup_labels_of_disks[disk_path] = utils_selinux.get_context_of_file(
            filename=disk_path)
        utils_selinux.set_context_of_file(filename=disk_path,
                                          context=img_label)
    # Set selinux of host.
    backup_sestatus = utils_selinux.get_status()
    utils_selinux.set_status(host_sestatus)
    # Set the context of the VM.
    vmxml.set_seclabel([sec_dict])
    vmxml.sync()

    clone_name = ("%s-clone" % vm.name)
    try:
        cmd = ("%s --original %s --name %s --auto-clone" %
               (VIRT_CLONE, vm.name, clone_name))
        cmd_result = utils.run(cmd, ignore_status=True)
        if cmd_result.exit_status:
            raise error.TestFail("Failed to execute virt-clone command."
                                 "Detail: %s." % cmd_result)
    finally:
        # clean up
        for path, label in backup_labels_of_disks.items():
            utils_selinux.set_context_of_file(filename=path, context=label)
        backup_xml.sync()
        utils_selinux.set_status(backup_sestatus)
        if not virsh.domstate(clone_name).exit_status:
            libvirt_vm.VM(clone_name, params, None, None).remove_with_storage()
开发者ID:Antique,项目名称:tp-libvirt,代码行数:60,代码来源:svirt_virt_clone.py


示例7: compare_capabilities_xml

    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")
开发者ID:Guannan-Ren,项目名称:tp-libvirt,代码行数:57,代码来源:virsh_capabilities.py


示例8: get_page_size

def get_page_size():
    """
    Get the current memory page size using getconf.
    If getconf doesn't exist, assume it's 4096.

    :return: An integer of current page size bytes.
    """
    try:
        getconf_path = utils_misc.find_command("getconf")
        return int(utils.run(getconf_path + " PAGESIZE").stdout)
    except ValueError:
        logging.warning("getconf not found! Assuming 4K for PAGESIZE")
        return 4096
开发者ID:uni-peter-zheng,项目名称:tp-libvirt,代码行数:13,代码来源:virsh_migrate_compcache.py


示例9: memory_lack

def memory_lack(params):
    """
    Lower the available memory of host
    """
    tmp_c_file = params.get("tmp_c_file", "/tmp/test.c")
    tmp_exe_file = params.get("tmp_exe_file", "/tmp/test")
    c_str = """
#include <stdio.h>
#include <malloc.h>
#define MAX 1024*4
int main(void){
    char *a;
    while(1) {
        a = malloc(MAX);
        if (a == NULL) {
            break;
        }
    }
    while (1){
    }
    return 0;
}"""
    c_file = open(tmp_c_file, 'w')
    c_file.write(c_str)
    c_file.close()
    try:
        utils_misc.find_command('gcc')
    except ValueError:
        raise error.TestNAError('gcc command is needed!')
    result = utils.run("gcc %s -o %s" % (tmp_c_file, tmp_exe_file))
    if result.exit_status:
        raise error.TestError("Compile C file failed: %s"
                              % result.stderr.strip())
    # Set swap off before fill memory
    utils.run("swapoff -a")
    utils.run("%s &" % tmp_exe_file)
    result = utils.run("ps -ef | grep %s | grep -v grep" % tmp_exe_file)
    pid = result.stdout.strip().split()[1]
    params['memory_pid'] = pid
开发者ID:noxdafox,项目名称:tp-libvirt,代码行数:39,代码来源:resource_abnormal.py


示例10: netcf_trans_control

def netcf_trans_control(command="status"):
    """
    Control current network configuration
    :param: command: it may be 'status', 'snapshot-dir', restart,
            change-begin, etc, Note that is the netcf-libs is required
    :returns: return command result
    """
    try:
        # For OS using systemd, this command usually located in /usr/libexec/.
        cmd = utils_misc.find_command("netcf-transaction.sh")
    except ValueError:
        # This is the default location for sysV init.
        old_path = "/etc/rc.d/init.d/netcf-transaction"
        if os.path.isfile(old_path):
            cmd = old_path
        else:
            raise error.TestNAError("Cannot find netcf-transaction! "
                                    "Make sure you have netcf-libs installed!")
    logging.debug(cmd)

    return commands.getoutput(cmd + " " + command)
开发者ID:Hao-Liu,项目名称:tp-libvirt,代码行数:21,代码来源:virsh_iface_trans.py


示例11: run


#.........这里部分代码省略.........
                    raise exceptions.TestFail("Inactive domain XML not updated "
                                              "when --current options used for "
                                              "detachment")

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

    # Test parameters
    uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                      "default"))
    vm_ref = params.get("at_detach_iface_vm_ref", "domname")
    at_options_suffix = params.get("at_dt_iface_at_options", "")
    dt_options_suffix = params.get("at_dt_iface_dt_options", "")
    at_status_error = "yes" == params.get("at_status_error", "no")
    dt_status_error = "yes" == params.get("dt_status_error", "no")
    pre_vm_state = params.get("at_dt_iface_pre_vm_state")

    # Skip if libvirt doesn't support --live/--current.
    if (at_options_suffix.count("--live") or
            dt_options_suffix.count("--live")):
        if not libvirt_version.version_compare(1, 0, 5):
            raise exceptions.TestSkipError("update-device doesn't"
                                           " support --live")
    if (at_options_suffix.count("--current") or
            dt_options_suffix.count("--current")):
        if not libvirt_version.version_compare(1, 0, 5):
            raise exceptions.TestSkipError("virsh update-device "
                                           "doesn't support --current")

    # Interface specific attributes.
    iface_type = params.get("at_detach_iface_type", "network")
    if iface_type == "bridge":
        try:
            utils_misc.find_command("brctl")
        except ValueError:
            raise exceptions.TestSkipError("Command 'brctl' is missing."
                                           " You must install it.")

    iface_source = params.get("at_detach_iface_source", "default")
    iface_mac = params.get("at_detach_iface_mac", "created")
    virsh_dargs = {'ignore_status': True, 'uri': uri, 'debug': True}

    # Check host version.
    rhel6_host = False
    if not process.run("grep 'Red Hat Enterprise Linux Server "
                       "release 6' /etc/redhat-release",
                       ignore_status=True, shell=True).exit_status:
        rhel6_host = True

    # Back up xml file.
    if vm.is_alive():
        vm.destroy(gracefully=False)
    backup_xml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)

    # Get a bridge name for test if iface_type is bridge.
    # If there is no bridge other than virbr0, raise TestSkipError
    if iface_type == "bridge":
        host_bridge = utils_net.Bridge()
        bridge_list = host_bridge.list_br()
        try:
            bridge_list.remove("virbr0")
        except AttributeError:
            pass  # If no virbr0, just pass is ok
        logging.debug("Useful bridges:%s", bridge_list)
        # just choosing one bridge on host.
        if len(bridge_list):
开发者ID:lento-sun,项目名称:tp-libvirt,代码行数:67,代码来源:virsh_attach_detach_interface_matrix.py


示例12: compare_capabilities_xml

    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.')
开发者ID:noxdafox,项目名称:tp-libvirt,代码行数:77,代码来源:virsh_capabilities.py


示例13: run


#.........这里部分代码省略.........
        update_iso_file.write(snippet)
        update_iso_file.close()

        cmd_options = "--force "
        if options == "--config" or start_vm == "no":
            cmd_options += " --config"

        # Give domain the ISO image file
        return virsh.update_device(domainarg=vm_name,
                                   filearg=update_iso_xml, flagstr=cmd_options,
                                   debug=True)

    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    vm_ref = params.get("change_media_vm_ref")
    action = params.get("change_media_action")
    start_vm = params.get("start_vm")
    options = params.get("change_media_options")
    device_type = params.get("change_media_device_type", "cdrom")
    target_device = params.get("change_media_target_device", "hdc")
    source_name = params.get("change_media_source")
    status_error = params.get("status_error", "no")
    check_file = params.get("change_media_check_file")
    update_iso_xml_name = params.get("change_media_update_iso_xml")
    init_iso_name = params.get("change_media_init_iso")
    old_iso_name = params.get("change_media_old_iso")
    new_iso_name = params.get("change_media_new_iso")
    source_path = params.get("change_media_source_path", "yes")

    if device_type not in ['cdrom', 'floppy']:
        raise error.TestNAError("Got a invalid device type:/n%s" % device_type)

    try:
        utils_misc.find_command("mkisofs")
    except ValueError:
        raise error.TestNAError("Command 'mkisofs' is missing. You must "
                                "install it (try 'genisoimage' package.")

    # Backup for recovery.
    vmxml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)

    iso_dir = os.path.join(data_dir.get_tmp_dir(), "tmp")
    old_iso = os.path.join(iso_dir, old_iso_name)
    new_iso = os.path.join(iso_dir, new_iso_name)
    update_iso_xml = os.path.join(iso_dir, update_iso_xml_name)
    if not os.path.exists(iso_dir):
        os.mkdir(iso_dir)
    if not init_iso_name:
        init_iso = ""
    else:
        init_iso = os.path.join(iso_dir, init_iso_name)

    if vm_ref == "name":
        vm_ref = vm_name

    env_pre(old_iso, new_iso)
    # Check domain's disk device
    disk_blk = vm_xml.VMXML.get_disk_blk(vm_name)
    logging.info("disk_blk %s", disk_blk)
    if target_device not in disk_blk:
        logging.info("Adding device")
        add_device(vm_name)

    if vm.is_alive() and start_vm == "no":
        logging.info("Destroying guest...")
        vm.destroy()
开发者ID:Antique,项目名称:tp-libvirt,代码行数:67,代码来源:virsh_change_media.py


示例14: run

def run(test, params, env):
    """
    Test virsh {at|de}tach-interface command.

    1) Prepare test environment and its parameters
    2) Attach the required interface
    3) According test type(only attach or both attach and detach):
       a.Go on to test detach(if attaching is correct)
       b.Return GOOD or raise TestFail(if attaching is wrong)
    4) Check if attached interface is correct:
       a.Try to catch it in vm's XML file
       b.Try to catch it in vm
    5) Detach the attached interface
    6) Check result
    """

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

    # Test parameters
    uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri",
                                                      "default"))
    vm_ref = params.get("at_detach_iface_vm_ref", "domname")
    options_suffix = params.get("at_detach_iface_options_suffix", "")
    status_error = "yes" == params.get("status_error", "no")
    start_vm = params.get("start_vm")
    # Should attach must be pass for detach test.
    correct_attach = "yes" == params.get("correct_attach", "no")

    # Interface specific attributes.
    iface_type = params.get("at_detach_iface_type", "network")
    if iface_type == "bridge":
        try:
            utils_misc.find_command("brctl")
        except ValueError:
            raise error.TestNAError("Command 'brctl' is missing. You must "
                                    "install it.")

    iface_source = params.get("at_detach_iface_source", "default")
    iface_mac = params.get("at_detach_iface_mac", "created")
    virsh_dargs = {'ignore_status': True, 'uri': uri}

    # Get a bridge name for test if iface_type is bridge.
    # If there is no bridge other than virbr0, raise TestNAError
    if iface_type == "bridge":
        host_bridge = utils_net.Bridge()
        bridge_list = host_bridge.list_br()
        try:
            bridge_list.remove("virbr0")
        except AttributeError:
            pass  # If no virbr0, just pass is ok
        logging.debug("Useful bridges:%s", bridge_list)
        # just choosing one bridge on host.
        if len(bridge_list):
            iface_source = bridge_list[0]
        else:
            raise error.TestNAError("No useful bridge on host "
                                    "other than 'virbr0'.")

    dom_uuid = vm.get_uuid()
    dom_id = vm.get_id()

    # To confirm vm's state
    if start_vm == "no" and vm.is_alive():
        vm.destroy()

    # Test both detach and attach, So collect info
    # both of them for result check.
    # When something wrong with interface, set it to 1
    fail_flag = 0
    result_info = []

    # Set attach-interface domain
    if vm_ref == "domname":
        vm_ref = vm_name
    elif vm_ref == "domid":
        vm_ref = dom_id
    elif vm_ref == "domuuid":
        vm_ref = dom_uuid
    elif vm_ref == "hexdomid" and dom_id is not None:
        vm_ref = hex(int(dom_id))

    # Get a mac address if iface_mac is 'created'.
    if iface_mac == "created" or correct_attach:
        iface_mac = utils_net.generate_mac_address_simple()

    # Set attach-interface options and Start attach-interface test
    if correct_attach:
        options = set_options("network", "default", iface_mac, "", "attach")
        attach_result = virsh.attach_interface(vm_name, options,
                                               **virsh_dargs)
    else:
        options = set_options(iface_type, iface_source, iface_mac,
                              options_suffix, "attach")
        attach_result = virsh.attach_interface(vm_ref, options, **virsh_dargs)
    attach_status = attach_result.exit_status
    logging.debug(attach_result)

    # If attach interface failed.
    if attach_status:
#.........这里部分代码省略.........
开发者ID:Acidburn0zzz,项目名称:tp-libvirt,代码行数:101,代码来源:virsh_attach_detach_interface.py


示例15: run

def run(test, params, env):
    """
    Test virsh interface related commands.

    (1) If using given exist interface for testing(eg. lo or ethX):
        1.1 Dumpxml for the interface(with --inactive option)
        1.2 Destroy the interface
        1.3 Undefine the interface
    (2) Define an interface from XML file
    (3) List interfaces with '--inactive' optioin
    (4) Start the interface
    (5) List interfaces with no option
    (6) Dumpxml for the interface
    (7) Get interface MAC address by interface name
    (8) Get interface name by interface MAC address
    (9) Delete interface if not use the exist interface for testing
        9.1 Destroy the interface
        9.2 Undefine the interface

    Caveat, this test may affect the host network, so using the loopback(lo)
    device by default. You can specify the interface which you want, but be
    careful.
    """

    iface_name = params.get("iface_name")
    iface_xml = params.get("iface_xml")
    ping_ip = params.get("ping_ip", "localhost")
    use_exist_iface = "yes" == params.get("use_exist_iface", "no")
    status_error = "yes" == params.get("status_error", "no")
    iface_script = NETWORK_SCRIPT + iface_name
    iface_script_bk = os.path.join(test.tmpdir, "iface-%s.bk" % iface_name)
    net_iface = utils_net.Interface(name=iface_name)
    iface_is_up = True
    list_option = "--all"
    if use_exist_iface:
        if not libvirt.check_iface(iface_name, "exists", "--all"):
            raise error.TestError("Interface '%s' not exists" % iface_name)
        iface_xml = os.path.join(test.tmpdir, "iface.xml.tmp")
        iface_is_up = net_iface.is_up()
    else:
        # Note, if not use the interface which already exists, iface_name must
        # be equal to the value specified in XML file
        if libvirt.check_iface(iface_name, "exists", "--all"):
            raise error.TestError("Interface '%s' already exists" % iface_name)
        if not iface_xml:
            raise error.TestError("XML file is needed.")

    # Stop NetworkManager as which may conflict with virsh iface commands
    try:
        NM = utils_misc.find_command("NetworkManager")
    except ValueError:
        logging.debug("No NetworkManager service.")
        NM = None
    NM_is_running = False
    if NM is not None:
        NM_service = service.Factory.create_service("NetworkManager")
        NM_is_running = NM_service.status()
        if NM_is_running:
            NM_service.stop()

    # run test cases
    try:
        if use_exist_iface:
            # back up the interface script
            utils.run("cp %s %s" % (iface_script, iface_script_bk))
            # step 1.1
            # dumpxml for interface
            xml = virsh.iface_dumpxml(iface_name, "--inactive",
                                      to_file=iface_xml, debug=True)
            # Step 1.2
            # Destroy interface
            if iface_is_up:
                result = virsh.iface_destroy(iface_name, debug=True)
                libvirt.check_exit_status(result, status_error)

            # Step 1.3
            # Undefine interface
            result = virsh.iface_undefine(iface_name, debug=True)
            libvirt.check_exit_status(result, status_error)
            if not status_error:
                if libvirt.check_iface(iface_name, "exists", list_option):
                    raise error.TestFail("%s is still present." % iface_name)

        # Step 2
        # Define interface
        result = virsh.iface_define(iface_xml, debug=True)
        libvirt.check_exit_status(result, status_error)

        # Step 3
        # List inactive interfaces
        list_option = "--inactive"
        if not status_error:
            if not libvirt.check_iface(iface_name, "exists", list_option):
                raise error.TestFail("Fail to find %s." % iface_name)

        # Step 4
        # Start interface
        result = virsh.iface_start(iface_name, debug=True)
        libvirt.check_exit_status(result, status_error)
        if not status_error:
#.........这里部分代码省略.........
开发者ID:libvirt-qe,项目名称:tp-libvirt,代码行数:101,代码来源:virsh_iface.py


示例16: run

def run(test, params, env):
    """
    Test suspend commands in qemu guest agent.

    :param test: kvm test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environmen.
    """
    clock_server = params.get("clock_server", "clock.redhat.com")
    ntputil_install = params.get("ntputil_install", "yum install -y ntpdate")
    login_timeout = int(params.get("login_timeout", "240"))
    date_time_command = params.get("date_time_command",
                                   r"date -u +'TIME: %a %m/%d/%Y %H:%M:%S.%N'")
    date_time_filter_re = params.get("date_time_filter_re",
                                     r"(?:TIME: \w\w\w )(.{19})(.+)")
    date_time_format = params.get("date_time_format",
                                  "%m/%d/%Y %H:%M:%S")

    tolerance = float(params.get("time_diff_tolerance", "0.5"))

    sub_work = params["sub_work"]
    test_type = params["timedrift_sub_work"]

    vm_name = params.get("vms")
    vm = env.get_vm(vm_name)
    error.context("Check if ntp utils are host in system.", logging.info)
    try:
        utils_misc.find_command("ntpdate")
    except ValueError:
        error.context("Install ntp utils `%s`." % (ntputil_install),
                      logging.info)
        utils.run(ntputil_install)
    error.context("Sync host machine with clock server %s" % (clock_server),
                  logging.info)
    utils.run("ntpdate %s" % (clock_server))

    session = vm.wait_for_login(timeout=login_timeout)
    error.context("Get clock from host and guest VM using `date`",
                  logging.info)

    before_date = utils_test.get_time(session,
                                      date_time_command,
                                      date_time_filter_re,
                                      date_time_format)
    logging.debug("date: host time=%ss guest time=%ss",
                  *before_date)

    session.close()

    if sub_work in globals():  # Try to find sub work function.
        globals()[sub_work](params, vm, session)
    else:
        raise error.TestNAError("Unable to found subwork %s in %s test file." %
                                (sub_work, __file__))

    vm = env.get_vm(vm_name)
    session = vm.wait_for_login(timeout=login_timeout)
    error.context("Get clock from host and guest VM using `date`",
                  logging.info)
    after_date = utils_test.get_time(session,
                                     date_time_command,
                                     date_time_filter_re,
                                     date_time_format)
    logging.debug("date: host time=%ss guest time=%ss",
                  *after_date)

    if test_type == 'guest_suspend':
        date_diff = time_diff(before_date, after_date)
        if date_diff > tolerance:
            raise error.TestFail("date %ss difference is"
                                 "'guest_diff_time != host_diff_time'"
                                 " out of tolerance %ss" % (date_diff[1],
                                                            tolerance))
    elif test_type == "guest_pause_resume":
        date_diff = time_diff_host_guest(before_date, after_date)
        if date_diff[1] > tolerance:
            raise error.TestFail("date %ss difference is "
                                 "'guest_time_after-guest_time_before'"
                                 " out of tolerance %ss" % (date_diff[1],
                                                            tolerance))
开发者ID:MiriamDeng,项目名称:tp-qemu,代码行数:80,代码来源:timedrift_no_net_win.py


示例17: run

def run(test, params, env):
    """
    This case check error messages in libvirtd logging.

    Implemetent test cases:
    with_iptables:  Simply start libvirtd when using iptables service
                          as firewall.
    with_firewalld: Simply start libvirtd when using firewalld service
                          as firewall.
    """
    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils_misc.find_free_port函数代码示例发布时间:2022-05-26
下一篇:
Python utils_libvirtd.libvirtd_stop函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap