当前位置: 首页>>代码示例>>Python>>正文


Python virsh.attach_disk函数代码示例

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


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

示例1: attach_disk_test

    def attach_disk_test():
        """
        Attach-disk testcase.
        1.Attch a disk to guest.
        2.Perform domblkinfo operation.
        3.Detach the disk.

        :return: Command status and output.
        """
        try:
            source_file = open(test_disk_source, 'wb')
            source_file.seek((512 * 1024 * 1024) - 1)
            source_file.write(str(0))
            source_file.close()
            virsh.attach_disk(vm_name, test_disk_source, front_dev, debug=True)
            vm_ref = vm_name
            result_source = virsh.domblkinfo(vm_ref, test_disk_source,
                                             ignore_status=True, debug=True)
            status_source = result_source.exit_status
            output_source = result_source.stdout.strip()
            if driver == "qemu":
                result_target = virsh.domblkinfo(vm_ref, front_dev,
                                                 ignore_status=True, debug=True)
                status_target = result_target.exit_status
                output_target = result_target.stdout.strip()
            else:
                status_target = 0
                output_target = "Xen doesn't support domblkinfo target!"
            virsh.detach_disk(vm_name, front_dev, debug=True)
            return status_target, output_target, status_source, output_source
        except (error.CmdError, IOError):
            return 1, "", 1, ""
开发者ID:noxdafox,项目名称:tp-libvirt,代码行数:32,代码来源:virsh_domblkinfo.py

示例2: add_cdrom_device

    def add_cdrom_device(vm_name, init_cdrom):
        """
        Add cdrom device for test vm
        """
        if vm.is_alive():
            virsh.destroy(vm_name)

        virsh.attach_disk(vm_name, init_cdrom,
                          " hdc", " --type cdrom --sourcetype file --config",
                          debug=True)
开发者ID:FengYang,项目名称:virt-test,代码行数:10,代码来源:virsh_change_media.py

示例3: modify_source

 def modify_source(vm_name, target, dst_image):
     """
     Modify domain's configuration to change its disk source
     """
     try:
         virsh.detach_disk(vm_name, target, extra="--config",
                           ignore_status=False)
         virsh.attach_disk(vm_name, dst_image, target, extra="--config",
                           ignore_status=False)
     except (remote.LoginError, virt_vm.VMError, aexpect.ShellError), detail:
         raise error.TestFail("Modify guest source failed: %s" % detail)
开发者ID:ayiyaliing,项目名称:virt-test,代码行数:11,代码来源:virt_sysprep.py

示例4: attach_removable_media

 def attach_removable_media(type, source, dev):
     bus = {'cdrom': 'ide', 'floppy': 'fdc'}
     args = {'driver': 'qemu', 'subdriver': 'raw', 'sourcetype': 'file',
             'type': type, 'targetbus': bus[type]}
     if type == 'cdrom':
         args.update({'mode': 'readonly'})
     config = ''
     # Join all options together to get command line
     for key in args.keys():
         config += ' --%s %s' % (key, args[key])
     config += ' --current'
     virsh.attach_disk(vm_name, source, dev, extra=config)
开发者ID:waynesun09,项目名称:tp-libvirt,代码行数:12,代码来源:specific_kvm.py

示例5: add_cdrom_device

    def add_cdrom_device(vm_name, init_cdrom):
        """
        Add cdrom device for test vm

        @param: vm_name: guest name
        @param: init_cdrom: source file
        """
        if vm.is_alive():
            virsh.destroy(vm_name)

        virsh.attach_disk(vm_name, init_cdrom,
                          disk_device, " --type cdrom --sourcetype file --config",
                          debug=True)
开发者ID:bingbu,项目名称:virt-test,代码行数:13,代码来源:virsh_change_media.py

示例6: modify_source

 def modify_source(vm_name, target, dst_image):
     """
     Modify domain's configuration to change its disk source
     """
     try:
         virsh.detach_disk(vm_name, target, extra="--config",
                           ignore_status=False)
         dst_image_format = utils_test.get_image_info(dst_image)['format']
         options = "--config --subdriver %s" % dst_image_format
         virsh.attach_disk(vm_name, dst_image, target, extra=options,
                           ignore_status=False)
     except (remote.LoginError, virt_vm.VMError,
             aexpect.ShellError), detail:
         raise error.TestFail("Modify guest source failed: %s" % detail)
开发者ID:Guannan-Ren,项目名称:tp-libvirt,代码行数:14,代码来源:virt_sysprep.py

示例7: add_device

    def add_device(vm_name, init_source="''"):
        """
        Add device for test vm

        :param vm_name: guest name
        :param init_source: source file
        """
        if vm.is_alive():
            virsh.destroy(vm_name)

        virsh.attach_disk(vm_name, init_source,
                          target_device,
                          "--type %s --sourcetype file --config" % device_type,
                          debug=True)
开发者ID:Antique,项目名称:tp-libvirt,代码行数:14,代码来源:virsh_change_media.py

示例8: create_disk

def create_disk(vm_name, disk_iso, disk_type, target_dev, mode=""):
    """
    :param vm_name : vm_name
    :param disk_iso : disk's source backing file
    :param disk_type: disk's device type: cdrom or floppy
    :param target_dev: disk's target device name
    :param mode: readonly or shareable
    """
    libvirt.create_local_disk("iso", disk_iso)
    options = "--type %s --sourcetype=file --config" % disk_type
    if mode:
        options += " --mode %s" % mode
    try:
        virsh.attach_disk(vm_name, disk_iso, target_dev, options)
    except:
        os.remove(disk_iso)
        raise exceptions.TestFail("Failed to attach")
开发者ID:chloerh,项目名称:tp-libvirt,代码行数:17,代码来源:virsh_update_device_matrix.py

示例9: create_cdrom

def create_cdrom(vm_name, orig_iso, target_dev):
    """
    :param vm_name : vm_name
    :param source_iso : disk's source backing file.
    """
    try:
        _file = open(orig_iso, 'wb')
        _file.seek((1024 * 1024) - 1)
        _file.write(str(0))
        _file.close()
    except IOError:
        raise error.TestFail("Create orig_iso failed!")
    try:
        virsh.attach_disk(vm_name, orig_iso, target_dev,
                          "--type cdrom --sourcetype=file --config")
    except:
        os.remote(orig_iso)
        raise error.TestFail("Failed to attach")
开发者ID:libvirt-qe,项目名称:tp-libvirt,代码行数:18,代码来源:virsh_update_device.py

示例10: create_disk

def create_disk(test, vm_name, orig_iso, disk_type, target_dev, mode=""):
    """
    :param vm_name : vm_name
    :param source_iso : disk's source backing file
    :param disk_type: disk's device type: cdrom or floppy
    :param target_dev: disk's target device name
    :param mode: readonly or shareable
    """
    try:
        with open(orig_iso, 'wb') as _file:
            _file.seek((1024 * 1024) - 1)
            _file.write(str(0).encode())
    except IOError:
        test.fail("Create orig_iso failed!")
    options = "--type %s --sourcetype=file --config" % disk_type
    if mode:
        options += " --mode %s" % mode
    try:
        virsh.attach_disk(vm_name, orig_iso, target_dev, options)
    except Exception:
        os.remove(orig_iso)
        test.fail("Failed to attach")
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:22,代码来源:virsh_update_device.py

示例11: attach_additional_disk

def attach_additional_disk(vm, disksize, targetdev):
    """
    Create a disk with disksize, then attach it to given vm.

    @param vm: Libvirt VM object.
    @param disksize: size of attached disk
    @param targetdev: target of disk device
    """
    logging.info("Attaching disk...")
    disk_path = os.path.join(data_dir.get_tmp_dir(), targetdev)
    cmd = "qemu-img create %s %s" % (disk_path, disksize)
    status, output = commands.getstatusoutput(cmd)
    if status:
        return (False, output)

    # To confirm attached device do not exist.
    virsh.detach_disk(vm.name, targetdev, extra="--config")

    attach_result = virsh.attach_disk(vm.name, disk_path, targetdev, extra="--config", debug=True)
    if attach_result.exit_status:
        return (False, attach_result)
    return (True, disk_path)
开发者ID:tjamrisk,项目名称:virt-test,代码行数:22,代码来源:guestfs_block_operations.py

示例12: run


#.........这里部分代码省略.........

    # Back up xml file.Xen host has no guest xml file to define a guset.
    backup_xml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)

    # Confirm how to reference a VM.
    if vm_ref == "vm_name":
        vm_ref = vm_name
    elif vm_ref == "id":
        vm_ref = vm_id
    elif vm_ref == "hex_vm_id":
        vm_ref = hex(int(vm_id))
    elif vm_ref == "uuid":
        vm_ref = vm_uuid
    elif vm_ref.find("invalid") != -1:
        vm_ref = params.get(vm_ref)

    volume = None
    pvtest = None
    status3 = None

    try:
        save_file = "/var/lib/libvirt/qemu/save/%s.save" % vm_name
        if option.count("managedsave") and vm.is_alive():
            virsh.managedsave(vm_name)

        if not vm.is_lxc():
            snp_list = virsh.snapshot_list(vm_name)
            if option.count("snapshot"):
                snp_file_list = []
                if not len(snp_list):
                    virsh.snapshot_create(vm_name)
                    logging.debug("Create a snapshot for test!")
                else:
                    # Backup snapshots for domain
                    for snp_item in snp_list:
                        tmp_file = os.path.join(test.tmpdir, snp_item + ".xml")
                        virsh.snapshot_dumpxml(vm_name, snp_item, to_file=tmp_file)
                        snp_file_list.append(tmp_file)
            else:
                if len(snp_list):
                    raise error.TestNAError("This domain has snapshot(s), "
                                            "cannot be undefined!")
        if option.count("remove-all-storage"):
            pvtest = utlv.PoolVolumeTest(test, params)
            pvtest.pre_pool(pool_name, pool_type, pool_target, emulated_img,
                            emulated_size=emulated_size)
            new_pool = libvirt_storage.PoolVolume(pool_name)
            if not new_pool.create_volume(vol_name, volume_size):
                raise error.TestFail("Creation of volume %s failed." % vol_name)
            volumes = new_pool.list_volumes()
            volume = volumes[vol_name]
            virsh.attach_disk(vm_name, volume, disk_target, "--config")

        # Turn libvirtd into certain state.
        if libvirtd_state == "off":
            utils_libvirtd.libvirtd_stop()

        # Test virsh undefine command.
        output = ""
        if vm_ref != "remote":
            vm_ref = "%s %s" % (vm_ref, extra)
            cmdresult = virsh.undefine(vm_ref, option,
                                       unprivileged_user=unprivileged_user,
                                       uri=uri,
                                       ignore_status=True, debug=True)
            status = cmdresult.exit_status
            output = cmdresult.stdout.strip()
            if status:
                logging.debug("Error status, command output: %s",
                              cmdresult.stderr.strip())
            if undefine_twice:
                status2 = virsh.undefine(vm_ref,
                                         ignore_status=True).exit_status
        else:
            if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"):
                raise error.TestNAError("remote_ip and/or local_ip parameters"
                                        " not changed from default values")
            try:
                uri = libvirt_vm.complete_uri(local_ip)
                session = remote.remote_login("ssh", remote_ip, "22",
                                              remote_user, remote_pwd,
                                              remote_prompt)
                cmd_undefine = "virsh -c %s undefine %s" % (uri, vm_name)
                status, output = session.cmd_status_output(cmd_undefine)
                logging.info("Undefine output: %s", output)
            except (error.CmdError, remote.LoginError, aexpect.ShellError), de:
                logging.error("Detail: %s", de)
                status = 1

        # Recover libvirtd state.
        if libvirtd_state == "off":
            utils_libvirtd.libvirtd_start()

        # Shutdown VM.
        if virsh.domain_exists(vm.name):
            try:
                if vm.is_alive():
                    vm.destroy(gracefully=False)
            except error.CmdError, detail:
                logging.error("Detail: %s", detail)
开发者ID:Antique,项目名称:tp-libvirt,代码行数:101,代码来源:virsh_undefine.py

示例13: run

def run(test, params, env):
    """
    Test virsh snapshot command when disk in all kinds of type.

    (1). Init the variables from params.
    (2). Create a image by specifice format.
    (3). Attach disk to vm.
    (4). Snapshot create.
    (5). Snapshot revert.
    (6). cleanup.
    """
    # Init variables.
    vm_name = params.get("main_vm", "virt-tests-vm1")
    vm = env.get_vm(vm_name)
    image_format = params.get("snapshot_image_format", "qcow2")
    status_error = ("yes" == params.get("status_error", "no"))
    snapshot_from_xml = ("yes" == params.get("snapshot_from_xml", "no"))
    snapshot_current = ("yes" == params.get("snapshot_current", "no"))
    snapshot_revert_paused = ("yes" == params.get("snapshot_revert_paused",
                                                  "no"))

    # Do xml backup for final recovery
    vmxml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)

    # Some variable for xmlfile of snapshot.
    snapshot_memory = params.get("snapshot_memory", "internal")
    snapshot_disk = params.get("snapshot_disk", "internal")

    # Get a tmp_dir.
    tmp_dir = data_dir.get_tmp_dir()
    # Create a image.
    params['image_name'] = "snapshot_test"
    params['image_format'] = image_format
    params['image_size'] = "1M"
    image = qemu_storage.QemuImg(params, tmp_dir, "snapshot_test")
    img_path, _ = image.create(params)
    # Do the attach action.
    result = virsh.attach_disk(vm_name, source=img_path, target="vdf",
                               extra="--persistent --subdriver %s" % image_format)
    if result.exit_status:
        raise error.TestNAError("Failed to attach disk %s to VM."
                                "Detail: %s." % (img_path, result.stderr))

    # Init snapshot_name
    snapshot_name = None
    snapshot_external_disk = []
    try:
        # Create snapshot.
        if snapshot_from_xml:
            snapshot_name = "snapshot_test"
            lines = ["<domainsnapshot>\n",
                     "<name>%s</name>\n" % snapshot_name,
                     "<description>Snapshot Test</description>\n"]
            if snapshot_memory == "external":
                memory_external = os.path.join(tmp_dir, "snapshot_memory")
                snapshot_external_disk.append(memory_external)
                lines.append("<memory snapshot=\'%s\' file='%s'/>\n" %
                             (snapshot_memory, memory_external))
            else:
                lines.append("<memory snapshot='%s'/>\n" % snapshot_memory)

            # Add all disks into xml file.
            disks = vm.get_disk_devices().values()
            lines.append("<disks>\n")
            for disk in disks:
                lines.append("<disk name='%s' snapshot='%s'>\n" %
                             (disk['source'], snapshot_disk))
                if snapshot_disk == "external":
                    disk_external = os.path.join(tmp_dir,
                                                 "%s.snap" % os.path.basename(disk['source']))
                    snapshot_external_disk.append(disk_external)
                    lines.append("<source file='%s'/>\n" % disk_external)
                lines.append("</disk>\n")
            lines.append("</disks>\n")
            lines.append("</domainsnapshot>")

            snapshot_xml_path = "%s/snapshot_xml" % tmp_dir
            snapshot_xml_file = open(snapshot_xml_path, "w")
            snapshot_xml_file.writelines(lines)
            snapshot_xml_file.close()
            snapshot_result = virsh.snapshot_create(
                vm_name, ("--xmlfile %s" % snapshot_xml_path))
            if snapshot_result.exit_status:
                if status_error:
                    return
                else:
                    raise error.TestFail("Failed to create snapshot. Error:%s."
                                         % snapshot_result.stderr.strip())
        else:
            options = ""
            snapshot_result = virsh.snapshot_create(vm_name, options)
            if snapshot_result.exit_status:
                if status_error:
                    return
                else:
                    raise error.TestFail("Failed to create snapshot. Error:%s."
                                         % snapshot_result.stderr.strip())
            snapshot_name = re.search(
                "\d+", snapshot_result.stdout.strip()).group(0)
            if snapshot_current:
#.........这里部分代码省略.........
开发者ID:Guannan-Ren,项目名称:tp-libvirt,代码行数:101,代码来源:virsh_snapshot_disk.py

示例14: run

def run(test, params, env):
    """
    Test command: virsh qemu-agent-command.
    """
    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    status_cmd = params.get("status_cmd", "")
    freeze_cmd = params.get("freeze_cmd", "")
    thaw_cmd = params.get("thaw_cmd", "")
    xml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
    try:
        def get_dirty(session, frozen=False):
            """
            Get dirty data of guest
            """
            try:
                data_cmd = "cat /proc/meminfo | grep Dirty"
                if not frozen:
                    result = utils_misc.wait_for(lambda:
                                                 int(session.
                                                     cmd_output(data_cmd).
                                                     strip().split()[1]) != 0,
                                                 60)
                    if result:
                        return int(session.cmd_output(data_cmd).strip().
                                   split()[1])
                    else:
                        return 0
                    dirty_info = session.cmd_output(data_cmd).strip()
                    return int(dirty_info.split()[1])
                else:
                    result = utils_misc.wait_for(lambda:
                                                 int(session.
                                                     cmd_output(data_cmd).
                                                     strip().split()[1]) == 0,
                                                 60)
                    if result:
                        return 0
                    else:
                        return int(session.cmd_output(data_cmd).strip().
                                   split()[1])
            except (IndexError, ValueError) as details:
                test.fail("Get dirty info failed: %s" % details)

        device_source_path = os.path.join(data_dir.get_tmp_dir(), "disk.img")
        device_source = libvirt.create_local_disk("file", path=device_source_path,
                                                  disk_format="qcow2")
        vm.prepare_guest_agent()

        # Do operation before freeze guest filesystem
        session = vm.wait_for_login()
        tmp_file = "/mnt/test.file"
        try:
            # Create extra image and attach to guest, then mount
            old_parts = libvirt.get_parts_list(session)
            ret = virsh.attach_disk(vm_name, device_source, "vdd")
            if ret.exit_status:
                test.fail("Attaching device failed before testing agent:%s" % ret.stdout.strip())
            time.sleep(1)
            new_parts = libvirt.get_parts_list(session)
            added_part = list(set(new_parts).difference(set(old_parts)))
            session.cmd("mkfs.ext3 -F /dev/{0} && mount /dev/{0} /mnt".format(added_part[0]))

            # Generate dirty memory
            session.cmd("rm -f %s" % tmp_file)
            session.cmd_output("cp /dev/zero %s 2>/dev/null &" % tmp_file)
            # Get original dirty data
            org_dirty_info = get_dirty(session)
            fz_cmd_result = virsh.qemu_agent_command(vm_name, freeze_cmd,
                                                     ignore_status=True,
                                                     debug=True)
            libvirt.check_exit_status(fz_cmd_result)

            # Get frozen dirty data
            fz_dirty_info = get_dirty(session, True)
            st_cmd_result = virsh.qemu_agent_command(vm_name, status_cmd,
                                                     ignore_status=True,
                                                     debug=True)
            libvirt.check_exit_status(st_cmd_result)
            if not st_cmd_result.stdout.strip().count("frozen"):
                test.fail("Guest filesystem status is not frozen: %s"
                          % st_cmd_result.stdout.strip())

            tw_cmd_result = virsh.qemu_agent_command(vm_name, thaw_cmd,
                                                     ignore_status=True,
                                                     debug=True)
            libvirt.check_exit_status(tw_cmd_result)

            # Get thawed dirty data
            tw_dirty_info = get_dirty(session)
            st_cmd_result = virsh.qemu_agent_command(vm_name, status_cmd,
                                                     ignore_status=True,
                                                     debug=True)
            libvirt.check_exit_status(st_cmd_result)
            if not st_cmd_result.stdout.strip().count("thawed"):
                test.fail("Guest filesystem status is not thawed: %s"
                          % st_cmd_result.stdout.strip())
            logging.info("Original dirty data: %s" % org_dirty_info)
            logging.info("Frozen dirty data: %s" % fz_dirty_info)
            logging.info("Thawed dirty data: %s" % tw_dirty_info)
#.........这里部分代码省略.........
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:101,代码来源:virsh_qemu_agent_command_fs.py

示例15: run

def run(test, params, env):
    """
    Test command: virsh domblklist.
    1.Prepare test environment.
    2.Run domblklist and check
    3.Do attach disk and rerun domblklist with check
    4.Clean test environment.
    """

    def domblklist_test():
        """
        Run domblklist and check result, raise error if check fail.
        """
        output_disk_info = {}
        result = virsh.domblklist(vm_ref, options,
                                  ignore_status=True, debug=True)
        status = result.exit_status
        output = result.stdout.strip()

        # Check status_error
        if status_error == "yes":
            if status == 0:
                raise error.TestFail("Run successfully with wrong command!")
        elif status_error == "no":
            if status == 1:
                raise error.TestFail("Run failed with right command")
            # Check disk information.
            disk_info = get_disk_info(vm_name, options)
            logging.debug("The disk info dict from xml is: %s" % disk_info)

            output_list = output.split('\n')
            for i in range(2, len(output_list)):
                output_disk_info[i-2] = output_list[i].split()
            logging.debug("The disk info dict from command output is: %s"
                          % output_disk_info)

            if "--details" in options:
                if disk_info != output_disk_info:
                    raise error.TestFail("The output did not match with disk"
                                         " info from xml")
            else:
                for i in range(len(disk_info.keys())):
                    disk_info[i] = disk_info[i][2:]
                if disk_info != output_disk_info:
                    raise error.TestFail("The output did not match with disk"
                                         " info from xml")

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

    # Get all parameters from configuration.
    vm_ref = params.get("domblklist_vm_ref")
    options = params.get("domblklist_options", "")
    status_error = params.get("status_error", "no")
    front_dev = params.get("domblkinfo_front_dev", "vdd")
    test_attach_disk = os.path.join(test.virtdir, "tmp.img")
    extra = ""

    domid = vm.get_id()
    domuuid = vm.get_uuid()
    vm_state = vm.state()

    if vm_ref == "id":
        vm_ref = domid
    elif vm_ref == "hex_id":
        vm_ref = hex(int(domid))
    elif vm_ref.find("invalid") != -1:
        vm_ref = params.get(vm_ref)
    elif vm_ref == "name":
        vm_ref = vm_name
    elif vm_ref == "uuid":
        vm_ref = domuuid

    # run domblklist and check
    domblklist_test()

    if status_error == "no":
        try:
            # attach disk and check
            source_file = open(test_attach_disk, 'wb')
            source_file.seek((512 * 1024 * 1024) - 1)
            source_file.write(str(0))
            source_file.close()
            # since bug 1049529, --config will work with detach when
            # domain is running, so change it back using --config here
            if "--inactive" in options or vm_state == "shut off":
                extra = "--config"
            virsh.attach_disk(vm_name, test_attach_disk, front_dev, extra,
                              debug=True)
            domblklist_test()
        finally:
            virsh.detach_disk(vm_name, front_dev, extra, debug=True)
            if os.path.exists(test_attach_disk):
                os.remove(test_attach_disk)
开发者ID:Guannan-Ren,项目名称:tp-libvirt,代码行数:94,代码来源:virsh_domblklist.py


注:本文中的virttest.virsh.attach_disk函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。