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

Python virsh.undefine函数代码示例

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

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



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

示例1: vm_undefine_check

    def vm_undefine_check(vm_name):
        """
        Check if vm can be undefined with manage-save option
        """
        #backup xml file
        xml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
        if not os.path.exists(managed_save_file):
            raise error.TestFail("Can't find managed save image")
        #undefine domain with no options.
        if not virsh.undefine(vm_name, options=None,
                              ignore_status=True).exit_status:
            raise error.TestFail("Guest shouldn't be undefined"
                                 "while domain managed save image exists")
        #undefine domain with managed-save option.
        if virsh.undefine(vm_name, options="--managed-save",
                          ignore_status=True).exit_status:
            raise error.TestFail("Guest can't be undefine with "
                                 "managed-save option")

        if os.path.exists(managed_save_file):
            raise error.TestFail("Managed save image exists"
                                 " after undefining vm")
        #restore and start the vm.
        xml_backup.define()
        vm.start()
开发者ID:CongLi,项目名称:tp-libvirt,代码行数:25,代码来源:virsh_managedsave.py


示例2: cleanup_vm

def cleanup_vm(vm_name=None, disk=None):
    """
    Cleanup the vm with its disk deleted.
    """
    try:
        if vm_name is not None:
            virsh.undefine(vm_name)
    except error.CmdError, detail:
        logging.error("Undefine %s failed:%s", vm_name, detail)
开发者ID:Keepod,项目名称:virt-test,代码行数:9,代码来源:libguestfs.py


示例3: cleanup_vm

def cleanup_vm(vm_name=None):
    """
    Cleanup the vm.
    """
    try:
        if vm_name is not None:
            virsh.undefine(vm_name)
    except error.CmdError:
        pass
开发者ID:Chenditang,项目名称:tp-libvirt,代码行数:9,代码来源:vfio.py


示例4: reset_env

def reset_env(vm_name, xml_file):
    """
    Reset env

    :param vm_name: the vm name
    :xml_file: domain xml file
    """
    virsh.destroy(vm_name)
    virsh.undefine(vm_name)
    virsh.define(xml_file)
    if os.path.exists(xml_file):
        os.remove(xml_file)
开发者ID:CongLi,项目名称:tp-libvirt,代码行数:12,代码来源:virsh_qemu_agent_command.py


示例5: clean_clone_vm

 def clean_clone_vm():
     """
     Clean up cloned domain.
     """
     try:
         if virsh.domain_exists(vm_clone_name):
             if virsh.is_alive(vm_clone_name):
                 virsh.destroy(vm_clone_name, ignore_status=False)
             virsh.undefine(vm_clone_name, ignore_status=False)
         if os.path.exists(clone_image):
             os.remove(clone_image)
     except error.CmdError, detail:
         raise error.TestFail("Clean clone guest failed!:%s" % detail)
开发者ID:Guannan-Ren,项目名称:tp-libvirt,代码行数:13,代码来源:virt_sysprep.py


示例6: cleanup_vm

def cleanup_vm(vm_name=None, disk_removed=None):
    """
    Cleanup the vm with its disk deleted.
    """
    try:
        if vm_name is not None:
            virsh.undefine(vm_name)
    except process.CmdError:
        pass
    try:
        if disk_removed is not None:
            os.remove(disk_removed)
    except IOError:
        pass
开发者ID:CongLi,项目名称:tp-libvirt,代码行数:14,代码来源:multifunction.py


示例7: test_add_domain

def test_add_domain(vm, params):
    """
    Test command add_domain:
    """
    add_ref = params.get("gf_add_ref", "disk")
    readonly = "yes" == params.get("gf_add_readonly")

    gf = utils_test.libguestfs.GuestfishTools(params)

    image_path = params.get("image_path")
    pv_name = params.get("pv_name")
    test_domain_name = "libguestfs_test_domain"
    test_dir = params.get("img_dir", data_dir.get_tmp_dir())
    test_xml = test_dir + '/test_domain.xml'

    xml_content = "<domain type='kvm'>\n\
      <memory>500000</memory>\n\
      <name>%s</name>\n\
      <vcpu>1</vcpu>\n\
      <os>\n\
        <type>hvm</type>\n\
        <boot dev='hd'/>\n\
      </os>\n\
      <devices>\n\
        <disk type='file' device='disk'>\n\
          <source file='%s'/>\n\
          <target dev='hda' bus='ide'/>\n\
        </disk>\n\
      </devices>\n\
    </domain>\n\
    " % (test_domain_name, image_path)
    f = open(test_xml, "w")
    f.write(xml_content)
    f.close()

    virsh.define(test_xml)
    gf.add_domain(test_domain_name)
    gf.run()
    gf_result = gf.list_devices()

    if '/dev/sd' not in gf_result.stdout:
        gf.close_session()
        logging.error(gf_result)
        virsh.undefine(test_domain_name)
        os.system('rm -f %s' % test_xml)
        raise error.TestFail("test_add_domain failed")
    gf.close_session()
    virsh.undefine(test_domain_name)
    os.system('rm -f %s' % test_xml)
开发者ID:zcyes,项目名称:tp-libvirt,代码行数:49,代码来源:guestfish_utils.py


示例8: run

def run(test, params, env):
    """
    Test undefine after set preferred numa tuning
    """
    bug_url = params.get("bug_url", "")
    vm_name = params.get("main_vm")
    backup_xml = libvirt_xml.VMXML.new_from_dumpxml(vm_name)

    # Prepare numatune memory parameter dict
    mem_tuple = ('memory_mode', 'memory_placement', 'memory_nodeset')
    numa_memory = {}
    for mem_param in mem_tuple:
        value = params.get(mem_param)
        if value:
            numa_memory[mem_param.split('_')[1]] = value

    libvirtd = utils_libvirtd.Libvirtd()
    libvirtd.start()

    try:
        vmxml = libvirt_xml.VMXML.new_from_dumpxml(vm_name)
        vmxml.numa_memory = numa_memory
        logging.debug("vm xml is %s", vmxml)
        vmxml.sync()
        result = virsh.undefine(vm_name, debug=True, ignore_status=True)
        if result.exit_status:
            raise error.TestFail("Undefine vm failed, check %s" % bug_url)
    finally:
        libvirtd.restart()
        backup_xml.sync()
开发者ID:CongLi,项目名称:tp-libvirt,代码行数:30,代码来源:numa_preferred_undefine.py


示例9: remove

 def remove(self, name):
     dom = name
     if dom['state'] != 'shut off':
         res = virsh.destroy(dom['name'])
         if res.exit_status:
             raise Exception(str(res))
     if dom['persistent'] == 'yes':
         # Make sure the domain is remove anyway
         res = virsh.undefine(
             dom['name'], options='--snapshots-metadata --managed-save')
         if res.exit_status:
             raise Exception(str(res))
开发者ID:cheneydc,项目名称:virt-test-ci,代码行数:12,代码来源:ci.py


示例10: prepare_env

    def prepare_env(self):
        """
        Prepare the environment before all tests.
        """
        print 'Running bootstrap'
        self.bootstrap()

        print 'Removing VM',  # TODO: use virt-test api remove VM
        sys.stdout.flush()
        status, res, err_msg = self.run_test(
            'remove_guest.without_disk', need_check=False)
        if not 'PASS' in status:
            virsh.undefine('virt-tests-vm1', '--snapshots-metadata')
            print '   WARNING: Failed to remove guest'

        print 'Installing VM',
        sys.stdout.flush()
        status, res, err_msg = self.run_test(
            'unattended_install.import.import.default_install.aio_native',
            restore_image=True, need_check=False)
        if not 'PASS' in status:
            raise Exception('   ERROR: Failed to install guest \n %s' %
                            res.stderr)
        virsh.destroy('virt-tests-vm1')
开发者ID:cheneydc,项目名称:virt-test-ci,代码行数:24,代码来源:ci.py


示例11:

            xml_exist = True

        # Check if save file exists if use --managed-save
        save_exist = False
        if os.path.exists(save_file):
            save_exist = True

        # Check if save file exists if use --managed-save
        volume_exist = False
        if volume and os.path.exists(volume):
            volume_exist = True

        # Test define with acl control and recover domain.
        if params.get('setup_libvirt_polkit') == 'yes':
            if virsh.domain_exists(vm.name):
                virsh.undefine(vm_ref, ignore_status=True)
            cmd = "chmod 666 %s" % backup_xml.xml
            utils.run(cmd, ignore_status=False)
            s_define = virsh.define(backup_xml.xml,
                                    unprivileged_user=unprivileged_user,
                                    uri=uri, ignore_status=True, debug=True)
            status3 = s_define.exit_status

    finally:
        # Recover main VM.
        backup_xml.sync()

        # Clean up pool
        if pvtest:
            pvtest.cleanup_pool(pool_name, pool_type,
                                pool_target, emulated_img)
开发者ID:Antique,项目名称:tp-libvirt,代码行数:31,代码来源:virsh_undefine.py


示例12: run

def run(test, params, env):
    """
    Test virsh undefine command.

    Undefine an inactive domain, or convert persistent to transient.
    1.Prepare test environment.
    2.Backup the VM's information to a xml file.
    3.When the libvirtd == "off", stop the libvirtd service.
    4.Perform virsh undefine operation.
    5.Recover test environment.(libvirts service,VM)
    6.Confirm the test result.
    """

    vm_ref = params.get("undefine_vm_ref", "vm_name")
    extra = params.get("undefine_extra", "")
    option = params.get("undefine_option", "")
    libvirtd_state = params.get("libvirtd", "on")
    status_error = ("yes" == params.get("status_error", "no"))
    undefine_twice = ("yes" == params.get("undefine_twice", 'no'))
    local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM")
    remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM")
    remote_user = params.get("remote_user", "user")
    remote_pwd = params.get("remote_pwd", "password")
    remote_prompt = params.get("remote_prompt", "#")

    vm_name = params.get("main_vm", "virt-tests-vm1")
    vm = env.get_vm(vm_name)
    vm_id = vm.get_id()
    vm_uuid = vm.get_uuid()

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

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

    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!")

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

    # Test virsh undefine command.
    if vm_ref != "remote":
        vm_ref = "%s %s" % (vm_ref, extra)
        cmdresult = virsh.undefine(vm_ref, option,
                                   ignore_status=True, debug=True)
        status = cmdresult.exit_status
        if status:
            logging.debug("Error status, command output: %s", cmdresult.stdout)
        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), detail:
            logging.error("Detail: %s", detail)
            status = 1
开发者ID:vanbogithub,项目名称:tp-libvirt,代码行数:95,代码来源:virsh_undefine.py


示例13: run


#.........这里部分代码省略.........
                            (i, i, install_root), shell=True)

            # Config basic network
            net_file = install_root + '/etc/sysconfig/network'
            with open(net_file, 'w') as f:
                f.write('NETWORKING=yes\nHOSTNAME=%s\n' % vm_name)
            net_script = install_root + '/etc/sysconfig/network-scripts/ifcfg-eth0'
            with open(net_script, 'w') as f:
                f.write('DEVICE=eth0\nBOOTPROTO=dhcp\nONBOOT=yes\n')

            # Set root password and enable sshd
            session = aexpect.ShellSession("chroot %s" % install_root)
            session.sendline('echo %s|passwd root --stdin' % passwd)
            session.sendline('chkconfig sshd on')
            session.close()

        # Create
        result = virsh.create(vmxml.xml, **virsh_args)
        utlv.check_exit_status(result)
        check_state('running')

        # Destroy
        result = virsh.destroy(vm_name, **virsh_args)
        utlv.check_exit_status(result)
        if not virsh.domain_exists(vm_name, **virsh_args):
            logging.info("Destroy transient LXC domain successfully")
        else:
            raise TestFail("Transient LXC domain still exist after destroy")

        # Define
        result = virsh.define(vmxml.xml, **virsh_args)
        utlv.check_exit_status(result)
        check_state('shut off')

        # List
        result = virsh.dom_list('--inactive', **virsh_args)
        utlv.check_exit_status(result)
        if re.findall("(%s)\s+shut off" % vm_name, result.stdout):
            logging.info("Find %s in virsh list output", vm_name)
        else:
            raise TestFail("Not find %s in virsh list output")

        # Dumpxml
        result = virsh.dumpxml(vm_name, uri=uri, debug=False)
        utlv.check_exit_status(result)

        # Edit
        edit_vcpu = '2'
        logging.info("Change vcpu of LXC container to %s", edit_vcpu)
        edit_cmd = [r":%s /[0-9]*<\/vcpu>/" + edit_vcpu + r"<\/vcpu>"]
        if not utlv.exec_virsh_edit(vm_name, edit_cmd, connect_uri=uri):
            raise TestFail("Run edit command fail")
        else:
            result = virsh.dumpxml(vm_name, **virsh_args)
            new_vcpu = re.search(r'(\d*)</vcpu>', result.stdout).group(1)
            if new_vcpu == edit_vcpu:
                logging.info("vcpu number is expected after do edit")
            else:
                raise TestFail("vcpu number is unexpected after do edit")

        # Start
        result = virsh.start(vm_name, **virsh_args)
        utlv.check_exit_status(result)
        check_state('running')

        # Suspend
        result = virsh.suspend(vm_name, **virsh_args)
        utlv.check_exit_status(result)
        check_state('paused')

        # Resume
        result = virsh.resume(vm_name, **virsh_args)
        utlv.check_exit_status(result)
        check_state('running')

        # Reboot(not supported on RHEL6)
        result = virsh.reboot(vm_name, **virsh_args)
        supported_err = 'not supported by the connection driver: virDomainReboot'
        if supported_err in result.stderr.strip():
            logging.info("Reboot is not supported")
        else:
            utlv.check_exit_status(result)

        # Destroy
        result = virsh.destroy(vm_name, **virsh_args)
        utlv.check_exit_status(result)
        check_state('shut off')

        # Undefine
        result = virsh.undefine(vm_name, **virsh_args)
        utlv.check_exit_status(result)
        if not virsh.domain_exists(vm_name, **virsh_args):
            logging.info("Undefine LXC domain successfully")
        else:
            raise TestFail("LXC domain still exist after undefine")

    finally:
        virsh.remove_domain(vm_name, **virsh_args)
        if full_os and os.path.exists(install_root):
            shutil.rmtree(install_root)
开发者ID:CongLi,项目名称:tp-libvirt,代码行数:101,代码来源:lxc_life_cycle.py


示例14: run_virsh_edit


#.........这里部分代码省略.........
    vcpucount_result = virsh.vcpucount(vm_name, options="--config")
    if vcpucount_result.exit_status:
        raise error.TestError("Failed to get vcpucount. Detail:\n%s"
                              % vcpucount_result)
    original_vcpu = vcpucount_result.stdout.strip()
    expected_vcpu = str(int(original_vcpu)+1)

    libvirtd = params.get("libvirtd", "on")
    vm_ref = params.get("edit_vm_ref")
    status_error = params.get("status_error")

    def modify_vcpu(source, edit_cmd):
        """
        Modify vm's cpu infomation.

        @param: source : virsh edit's option.
        @param: dic_mode : a edit commad line .
        @return: True if edit successed,False if edit failed.
        """
        session = aexpect.ShellSession("sudo -s")
        try:
            session.sendline("virsh edit %s" % source)
            session.sendline(edit_cmd)
            session.send('\x1b')
            session.send('ZZ')
            # use sleep(1) to make sure the modify has been completed.
            time.sleep(1)
            session.close()
            return True
        except:
            return False

    def edit_vcpu(source, guest_name):
        """
        Modify vm's cpu infomation by virsh edit command.

        @param: source : virsh edit's option.
        @param: guest_name : vm's name.
        @return: True if edit successed,False if edit failed.
        """
        dic_mode = {"edit": ":%s /[0-9]*<\/vcpu>/"+expected_vcpu+"<\/vcpu>",
                    "recover": ":%s /[0-9]*<\/vcpu>/"+original_vcpu+"<\/vcpu>"}
        status = modify_vcpu(source, dic_mode["edit"])
        if not status:
            return status
        if params.get("paused_after_start_vm") == "yes":
            virsh.resume(guest_name, ignore_status=True)
            virsh.destroy(guest_name)
        elif params.get("start_vm") == "yes":
            virsh.destroy(guest_name)
        vcpus = vm.dominfo()["CPU(s)"]
        #Recover cpuinfo
        status = modify_vcpu(source, dic_mode["recover"])
        if status and vcpus != expected_vcpu:
            return False
        return status

    #run test case
    xml_file = os.path.join(test.tmpdir, 'tmp.xml')
    virsh.dumpxml(vm_name, extra="", to_file=xml_file)

    if libvirtd == "off":
        utils_libvirtd.libvirtd_stop()

    try:
        if vm_ref == "id":
            status = edit_vcpu(domid, vm_name)
        elif vm_ref == "uuid":
            status = edit_vcpu(domuuid, vm_name)
        elif vm_ref == "name" and status_error == "no":
            status = edit_vcpu(vm_name, vm_name)
        else:
            status = False
            if vm_ref.find("invalid") != -1:
                vm_ref = params.get(vm_ref)
            elif vm_ref == "name":
                vm_ref = "%s %s" % (vm_name, params.get("edit_extra_param"))
            edit_status = virsh.edit(vm_ref).exit_status
            if edit_status == 0:
                status = True
    except:
        status = False

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

    #Recover VM
    if vm.is_alive():
        vm.destroy()
    virsh.undefine(vm_name)
    virsh.define(xml_file)

    #check status_error
    if status_error == "yes":
        if status:
            raise error.TestFail("Run successfully with wrong command!")
    elif status_error == "no":
        if not status:
            raise error.TestFail("Run failed with right command")
开发者ID:bingbu,项目名称:virt-test,代码行数:101,代码来源:virsh_edit.py


示例15: run


#.........这里部分代码省略.........
        if if_device == "no_exist_net":
            device = "vnet-1"
        elif if_device == "no_exist_mac":
            # Generate random mac address for negative test
            device = utils_net.VirtIface.complete_mac_address("01:02")
        elif if_device == " ":
            device = "''"

        # Setlink opertation
        result = domif_setlink(vm_name[1], device, if_operation, options)
        status = result.exit_status
        logging.info("Setlink done")

        # Getlink opertation
        get_result = domif_getlink(vm_name[1], device, options)
        getlink_output = get_result.stdout.strip()

        # Check the getlink command output
        if status_error == "no":
            if not re.search(if_operation, getlink_output):
                test.fail("Getlink result should "
                          "equal with setlink operation")

        logging.info("Getlink done")
        # If --config or --persistent is given should restart the vm then test link status
        if any(options == option for option in ["--config", "--persistent"]) and vm.is_alive():
            vm.destroy()
            vm.start()
            logging.info("Restart VM")

        elif start_vm == "no":
            vm.start()

        error_msg = None
        if status_error == "no":
            # Serial login the vm to check link status
            # Start vm check the link statue
            session = vm.wait_for_serial_login(username=username,
                                               password=password)
            guest_if_name = utils_net.get_linux_ifname(session, mac_address)

            # Check link state in guest
            if check_link_state:
                if (if_operation == "up" and
                        not guest_if_state(guest_if_name, session)):
                    error_msg = "Link state should be up in guest"
                if (if_operation == "down" and
                        guest_if_state(guest_if_name, session)):
                    error_msg = "Link state should be down in guest"

            # Test of setting link state by update_device command
            if check_link_by_update_device:
                if not check_update_device(vm, guest_if_name, session):
                    error_msg = "Check update_device failed"

            # Set the link up make host connect with vm
            domif_setlink(vm_name[0], device, "up", "")
            if not utils_misc.wait_for(
                    lambda: guest_if_state(guest_if_name, session), 5):
                error_msg = "Link state isn't up in guest"

            # Ignore status of this one
            cmd = 'ip link set down %s' % guest_if_name
            session.cmd_status_output(cmd, timeout=10)
            pattern = "%s:.*state DOWN.*" % guest_if_name
            pattern_cmd = 'ip addr show dev %s' % guest_if_name
            guest_cmd_check(pattern_cmd, session, pattern)

            cmd = 'ip link set up %s' % guest_if_name
            session.cmd_status_output(cmd, timeout=10)
            pattern = "%s:.*state UP.*" % guest_if_name
            if not guest_cmd_check(pattern_cmd, session, pattern):
                error_msg = ("Could not bring up interface %s inside guest"
                             % guest_if_name)
        else:  # negative test
            # stop guest, so state is always consistent on next start
            vm.destroy()

        if error_msg:
            test.fail(error_msg)

        # Check status_error
        if status_error == "yes":
            if status:
                logging.info("Expected error (negative testing). Output: %s",
                             result.stderr.strip())

            else:
                test.fail("Unexpected return code %d "
                          "(negative testing)" % status)
        elif status_error != "no":
            test.error("Invalid value for status_error '%s' "
                       "(must be 'yes' or 'no')" % status_error)
    finally:
        # Recover VM.
        if vm.is_alive():
            vm.destroy(gracefully=False)
        virsh.undefine(vm_name[0])
        virsh.define(vm_xml_file)
        os.remove(vm_xml_file)
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:101,代码来源:virsh_domif_setlink_getlink.py


示例16: shutdown

    vm.destroy(gracefully=False)

    # Check disk count after VM shutdown (with --config).
    check_count_after_shutdown = True
    disk_count_after_shutdown = vm_xml.VMXML.get_disk_count(vm_name)
    if test_cmd == "attach-disk":
        if disk_count_after_shutdown == disk_count_before_cmd:
            check_count_after_shutdown = False
    elif test_cmd == "detach-disk":
        if disk_count_after_shutdown < disk_count_before_cmd:
            check_count_after_shutdown = False

    # Recover VM.
    if vm.is_alive():
        vm.destroy(gracefully=False)
    virsh.undefine(vm_name)
    virsh.define(vm_xml_file)
    if os.path.exists(device_source):
        os.remove(device_source)

    # Check results.
    if status_error == 'yes':
        if status == 0:
            raise error.TestFail("virsh %s exit with unexpected value."
                                 % test_cmd)
    else:
        if status != 0:
            raise error.TestFail("virsh %s failed." % test_cmd)
        if test_cmd == "attach-disk":
            if not check_count_after_cmd:
                raise error.TestFail("Cannot see deivce in xml file"
开发者ID:FengYang,项目名称:virt-test,代码行数:31,代码来源:virsh_attach_detach_disk.py


示例17: run_virsh_undefine

def run_virsh_undefine(test, params, env):
    """
    Test virsh undefine command.

    Undefine an inactive domain, or convert persistent to transient.
    1.Prepare test environment.
    2.Backup the VM's information to a xml file.
    3.When the libvirtd == "off", stop the libvirtd service.
    4.Perform virsh undefine operation.
    5.Recover test environment.(libvirts service,VM)
    6.Confirm the test result.
    """

    vm_ref = params.get("undefine_vm_ref", "vm_name")
    extra = params.get("undefine_extra", "")
    libvirtd_state = params.get("libvirtd", "on")
    status_error = params.get("status_error")
    undefine_twice = params.get("undefine_twice", 'no')
    local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM")
    remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM")
    xml_file = os.path.join(test.tmpdir, 'tmp.xml')
    remote_user = params.get("remote_user", "user")
    remote_password = params.get("remote_password", "password")
    remote_prompt = params.get("remote_prompt", "#")

    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    vm_id = vm.get_id()
    vm_uuid = vm.get_uuid()

    # Back up xml file.Xen host has no guest xml file to define a guset.
    virsh.dumpxml(vm_name, extra="", to_file=xml_file)

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

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

    # Test virsh undefine command.
    status = 0
    try:
        uri = libvirt_vm.complete_uri(local_ip)
    except error.CmdError:
        status = 1
        uri = None
    if vm_ref != "remote":
        vm_ref = "%s %s" % (vm_ref, extra)
        cmdresult = virsh.undefine(vm_ref, uri=uri,
                                   ignore_status=True, debug=True)
        status = cmdresult.exit_status
        if status:
            logging.debug("Error status, command output: %s", cmdresult.stdout)
        if undefine_twice == "yes":
            status2 = virsh.undefine(vm_ref, uri=uri,
                                     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")
        session = remote.remote_login("ssh", remote_ip, "22", remote_user,
                                      remote_password, 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)

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

    # Shutdown VM.
    if virsh.domain_exists(vm.name, uri=uri):
        try:
            if vm.is_alive():
                vm.destroy()
        except error.CmdError, detail:
            logging.error("Detail: %s", detail)
开发者ID:FT4VT,项目名称:FT4VM-L1_test,代码行数:87,代码来源:virsh_undefine.py


示例18: guest_cmd_check

            guest_cmd_check(cmd, session, pattern)

            cmd = "ifup %s" % guest_if_name
            pattern = "Determining IP information for %s" % guest_if_name
            pattern += "|Connection successfully activated"
            if not guest_cmd_check(cmd, session, pattern):
                error_msg = "Could not bring up interface %s inside guest" % guest_if_name
        else:  # negative test
            # stop guest, so state is always consistent on next start
            vm.destroy()

        if error_msg:
            raise error.TestFail(error_msg)

        # Check status_error
        if status_error == "yes":
            if status:
                logging.info("Expected error (negative testing). Output: %s", result.stderr.strip())

            else:
                raise error.TestFail("Unexpected return code %d " "(negative testing)" % status)
        elif status_error != "no":
            raise error.TestError("Invalid value for status_error '%s' " "(must be 'yes' or 'no')" % status_error)
    finally:
        # Recover VM.
        if vm.is_alive():
            vm.destroy(gracefully=False)
        virsh.undefine(vm_name[0])
        virsh.define(vm_xml_file)
        os.remove(vm_xml_file)
开发者ID:chloerh,项目名称:tp-libvirt,代码行数:30,代码来源:virsh_domif_setlink_getlink.py


示例19: run_virsh_domif_setlink_getlink


#.........这里部分代码省略.........
    vm_name = params.get("main_vm", "virt-tests-vm1")
    vm = env.get_vm(vm_name)
    options = params.get("if_options", "--config")
    start_vm = params.get("start_vm", "no")
    if_device = params.get("if_device", "net")
    if_name = params.get("if_name", "vnet0")
    if_operation = params.get("if_operation", "up")
    if_name_re = params.get("if_ifname_re", r"\s*\d+:\s+([[a-zA-Z]+\d+):")
    status_error = params.get("status_error", "no")
    mac_address = vm.get_virsh_mac_address(0)
    device = "vnet0"

    # Back up xml file.
    vm_xml_file = os.path.join(test.tmpdir, "vm.xml")
    virsh.dumpxml(vm_name, extra="--inactive", to_file=vm_xml_file)

    # Vm status
    if start_vm == "yes" and vm.is_dead():
        vm.start()

    elif start_vm == "no" and vm.is_alive():
        vm.destroy()

    # Test device net or mac address
    if if_device == "net" and vm.is_alive():
        device = if_name
        # Get all vm's interface device
        device = vm_xml.VMXML.get_net_dev(vm_name)[0]

    elif if_device == "mac":
        device = mac_address

    # Setlink opertation
    result = domif_setlink(vm_name, device, if_operation, options)
    status = result.exit_status
    logging.info("Setlink done")

    # Getlink opertation
    get_result = domif_getlink(vm_name, device, options)
    getlink_output = get_result.stdout.strip()

    # Check the getlink command output
    if not re.search(if_operation, getlink_output) and status_error == "no":
        raise error.TestFail("Getlink result should " "equal with setlink operation ", getlink_output)

    logging.info("Getlink done")
    # If --config is given should restart the vm then test link status
    if options == "--config" and vm.is_alive():
        vm.destroy()
        vm.start()
        logging.info("Restart VM")

    elif start_vm == "no":
        vm.start()

    error_msg = None
    if status_error == "no":
        # Serial login the vm to check link status
        # Start vm check the link statue
        session = vm.wait_for_serial_login()
        cmd = "ip add |grep -i '%s' -B1|grep -i 'state %s' " % (mac_address, if_operation)
        cmd_status, output = session.cmd_status_output(cmd)
        logging.info("====%s==%s===", cmd_status, output)
        # Set the link up make host connect with vm
        domif_setlink(vm_name, device, "up", "")
        # Bring up referenced guest nic
        guest_if_name = re.search(if_name_re, output).group(1)
        # Ignore status of this one
        cmd_status = session.cmd_status("ifdown %s" % guest_if_name)
        cmd_status = session.cmd_status("ifup %s" % guest_if_name)
        if cmd_status != 0:
            error_msg = "Could not bring up interface %s inside guest" % guest_if_name
    else:  # negative test
        # stop guest, so state is always consistent on next start
        vm.destroy()

    # Recover VM.
    if vm.is_alive():
        vm.destroy(gracefully=False)
    virsh.undefine(vm_name)
    virsh.define(vm_xml_file)
    os.remove(vm_xml_file)

    if error_msg:
        raise error.TestFail(error_msg)

    # Check status_error
    if status_error == "yes":
        if status:
            logging.info("Expected error (negative testing). Output: %s", result.stderr.strip())

        else:
            raise error.TestFail("Unexpected return code %d " "(negative testing)" % status)
    elif status_error == "no":
        status = cmd_status
        if status:
            raise error.TestFail("Unexpected error (positive testing). " "Output: %s" % result.stderr.strip())

    else:
        raise error.TestError("Invalid value for status_error '%s' " "(must be 'yes' or 'no')" % status_error)
开发者ID:tjamrisk,项目名称:virt-test,代码行数:101,代码来源:virsh_domif_setlink_getlink.py


示例20: run


#.........这里部分代码省略.........
                os.environ[virtio_win_env] = dest_dir
            if checkpoint.endswith('iso_mount'):
                logging.info('Mount iso to /opt')
                process.run('mount %s /opt' % iso_path)
                os.environ[virtio_win_env] = '/opt'
            if checkpoint.endswith('iso_file'):
                logging.info('Set env %s=%s' % (virtio_win_env, iso_path))
                os.environ[virtio_win_env] = iso_path
        if checkpoint == 'cdrom':
            xml = vm_xml.VMXML.new_from_inactive_dumpxml(
                    vm_name, virsh_instance=virsh_instance)
            logging.debug(xml.xmltreefile)
            disks = xml.get_disk_all()
            logging.debug('Disks: %r', disks)
            for disk in list(disks.values()):
                # Check if vm has cdrom attached
                if disk.get('device') == 'cdrom' and disk.find('source') is None:
                    test.error('No CDROM image attached')
        if checkpoint == 'vdsm':
            extra_pkg = params.get('extra_pkg')
            logging.info('Instal 

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python virtualchain.get_config_filename函数代码示例发布时间:2022-05-26
下一篇:
Python virsh.start函数代码示例发布时间: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