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

Python virsh.domstate函数代码示例

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

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



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

示例1: 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


示例2: test_suspend

 def test_suspend():
     # Suspend
     result = virsh.suspend(vm_name, ignore_status=True, debug=True)
     libvirt.check_exit_status(result)
     cmd = "virsh domstate %s" % vm_name
     if "paused" not in virsh.domstate(vm_name, **dargs).stdout:
         test.fail("suspend vm failed")
     # Resume
     result = virsh.resume(vm_name, ignore_status=True, debug=True)
     libvirt.check_exit_status(result)
     if "running" not in virsh.domstate(vm_name, **dargs).stdout:
         test.fail("resume vm failed")
     if check_attach_pci():
         logging.debug("adapter found after suspend/resume")
     else:
         test.fail("passthroughed adapter not found after suspend/resume")
开发者ID:balamuruhans,项目名称:tp-libvirt,代码行数:16,代码来源:libvirt_pci_passthrough_hotplug.py


示例3: for_each_vm

    def for_each_vm(vms, virsh_func, state=None):
        """
        Execute the virsh_func with each vm in vms.

        :Param vms: List of vm.
        :Param virsh_func: Function in virsh module.
        :Param state: State to verify the result of virsh_func.
                      None means do not check the state.
        """
        vm_names = []
        for vm in vms:
            vm_names.append(vm.name)
        for vm_name in vm_names:
            cmd_result = virsh_func(vm_name)
            if cmd_result.exit_status:
                raise error.TestFail(cmd_result)
            if state is None:
                continue
            actual_state = virsh.domstate(vm_name).stdout.strip()
            if not (actual_state == state):
                raise error.TestFail("Command %s succeed, but the state is %s,"
                                     "but not %s." %
                                     (virsh_func.__name__, actual_state, state))
        logging.debug("Operation %s on %s succeed.",
                      virsh_func.__name__, vm_names)
开发者ID:Antique,项目名称:virt-test,代码行数:25,代码来源:libvirt_bench_domstate_switch_in_loop.py


示例4: check_state

 def check_state(expected_state):
     result = virsh.domstate(vm_name, uri=uri)
     utlv.check_exit_status(result)
     vm_state = result.stdout.strip()
     if vm_state == expected_state:
         logging.info("Get expected state: %s", vm_state)
     else:
         raise TestFail("Get unexpected state: %s", vm_state)
开发者ID:CongLi,项目名称:tp-libvirt,代码行数:8,代码来源:lxc_life_cycle.py


示例5: check_on_shutdown_vm_status

 def check_on_shutdown_vm_status():
     for dom in vms:
         result = virsh.domstate(dom.name, "--reason")
         try:
             dom.wait_for_shutdown()
         except Exception as e:
             test.fail('As on_boot is set to "ignore", but guest %s is '
                       'not shutdown. reason: %s ' % (dom.name, e))
开发者ID:balamuruhans,项目名称:tp-libvirt,代码行数:8,代码来源:libvirt_guests.py


示例6: vm_state_check

    def vm_state_check():
        cmd_result = virsh.dumpxml(vm_name, debug=True)
        libvirt.check_exit_status(cmd_result)

        # The xml should contain the match_string
        xml = cmd_result.stdout.strip()
        match_string = "<boot dev='cdrom'/>"
        if not re.search(match_string, xml):
            raise exceptions.TestFail("After domain restore, "
                                      "the xml is not expected")

        domstate = virsh.domstate(vm_name, debug=True).stdout.strip()
        if restore_state != domstate:
            raise exceptions.TestFail("The domain state is not expected")
开发者ID:chloerh,项目名称:tp-libvirt,代码行数:14,代码来源:virsh_save_image_define.py


示例7: vm_state_check

    def vm_state_check():
        cmd_result = virsh.dumpxml(vm_name, debug=True)
        if cmd_result.exit_status:
            test.fail("Failed to dump xml of domain %s" % vm_name)

        # The xml should contain the match_string
        xml = cmd_result.stdout.strip()
        match_string = "<boot dev='cdrom'/>"
        if not re.search(match_string, xml):
            test.fail("After domain restore the xml is not expected")

        domstate = virsh.domstate(vm_name, debug=True).stdout.strip()
        if restore_state != domstate:
            test.fail("The domain state is not expected")
开发者ID:lento-sun,项目名称:tp-libvirt,代码行数:14,代码来源:virsh_save_image_edit.py


示例8: check_crash_state

def check_crash_state(cmd_output, crash_action, vm_name, dump_file=""):
    """
    Check the domain state about crash actions.
    """
    expect_output = ""
    crash_state = False
    global find_dump_file

    if crash_action in ["destroy", "coredump-destroy"]:
        expect_output = "shut off (crashed)"
    elif crash_action in ["restart", "coredump-restart"]:
        expect_output = "running (crashed)"
    elif crash_action in ["preserve", "rename-restart"]:
        expect_output = "crashed (panicked)"
    logging.info("Expected state: %s", expect_output)

    def _wait_for_state():
        cmd_output = virsh.domstate(vm_name, '--reason').stdout.strip()
        return cmd_output.strip() == expect_output

    # There is a middle state 'crashed (panicked)' for these two actions
    if crash_action in ['coredump-destroy', 'coredump-restart']:
        middle_state = 'crashed (panicked)'
        text = 'VM in middle state: %s' % middle_state
        if cmd_output.strip() == middle_state:
            utils_misc.wait_for(_wait_for_state, 60, text=text)
            cmd_output = virsh.domstate(vm_name, '--reason').stdout.strip()

    logging.debug("Actual state: %s", cmd_output.strip())
    if cmd_output.strip() == expect_output:
        crash_state = True
    if dump_file:
        result = process.run("ls %s" % dump_file,
                             ignore_status=True, shell=True)
        if result.exit_status == 0:
            logging.debug("Find the auto dump core file:\n%s", result.stdout_text)
            find_dump_file = True
        else:
            logging.error("Not find coredump file: %s", dump_file)
    return crash_state
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:40,代码来源:virsh_domstate.py


示例9: run

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

    1.Prepare test environment.
    2.When the libvirtd == "off", stop the libvirtd service.
    3.Perform virsh domstate operation.
    4.Recover test environment.
    5.Confirm the test result.
    """
    vm_name = params.get("main_vm", "virt-tests-vm1")
    vm = env.get_vm(vm_name)

    libvirtd = params.get("libvirtd", "on")
    vm_ref = params.get("domstate_vm_ref")
    status_error = params.get("status_error", "no") == "yes"
    extra = params.get("domstate_extra", "")
    vm_action = params.get("domstate_vm_action", "")

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

    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

    try:
        if vm_action == "suspend":
            virsh.suspend(vm_name, ignore_status=False)
        elif vm_action == "resume":
            virsh.suspend(vm_name, ignore_status=False)
            virsh.resume(vm_name, ignore_status=False)
        elif vm_action == "destroy":
            virsh.destroy(vm_name, ignore_status=False)
        elif vm_action == "start":
            virsh.destroy(vm_name, ignore_status=False)
            virsh.start(vm_name, ignore_status=False)
    except error.CmdError:
        raise error.TestError("Guest prepare action error!")

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

    if vm_ref == "remote":
        remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM")
        local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM")
        remote_pwd = params.get("remote_pwd", None)
        if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"):
            raise error.TestNAError("Test 'remote' parameters not setup")
        status = 0
        try:
            remote_uri = libvirt_vm.complete_uri(local_ip)
            session = remote.remote_login("ssh", remote_ip, "22", "root", remote_pwd, "#")
            session.cmd_output("LANG=C")
            command = "virsh -c %s domstate %s" % (remote_uri, vm_name)
            status, output = session.cmd_status_output(command, internal_timeout=5)
            session.close()
        except error.CmdError:
            status = 1
    else:
        result = virsh.domstate(vm_ref, extra, ignore_status=True)
        status = result.exit_status
        output = result.stdout.strip()

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

    # check status_error
    if status_error:
        if not status:
            raise error.TestFail("Run successfully with wrong command!")
    else:
        if status or not output:
            raise error.TestFail("Run failed with right command")
        if extra.count("reason"):
            if vm_action == "suspend":
                # If not, will cost long time to destroy vm
                virsh.destroy(vm_name)
                if not output.count("user"):
                    raise ActionError(vm_action)
            elif vm_action == "resume":
                if not output.count("unpaused"):
                    raise ActionError(vm_action)
            elif vm_action == "destroy":
                if not output.count("destroyed"):
                    raise ActionError(vm_action)
            elif vm_action == "start":
                if not output.count("booted"):
                    raise ActionError(vm_action)
        if vm_ref == "remote":
            if not (re.search("running", output) or re.search("blocked", output) or re.search("idle", output)):
                raise error.TestFail("Run failed with right command")
开发者ID:jferlan,项目名称:tp-libvirt,代码行数:100,代码来源:virsh_domstate.py


示例10: check_vm_state

        # Check vm state on destination.
        logging.debug("Checking %s state on target %s.", vm.name,
                      vm.connect_uri)
        if (options.count("dname") or
                extra.count("dname") and status_error != 'yes'):
            vm.name = extra.split()[1].strip()
        check_dest_state = True
        check_dest_state = check_vm_state(vm, dest_state)
        logging.info("Supposed state: %s" % dest_state)
        logging.info("Actual state: %s" % vm.state())

        # Check vm state on source.
        if extra.count("--timeout-suspend"):
            logging.debug("Checking '%s' state on source '%s'", vm.name,
                          src_uri)
            vm_state = virsh.domstate(vm.name, uri=src_uri).stdout.strip()
            if vm_state != "shut off":
                raise exceptions.TestFail("Local vm state should be 'shut off'"
                                          ", but found '%s'" % vm_state)

        # Recover VM state.
        logging.debug("Recovering %s state." % vm.name)
        if src_state == "paused":
            vm.resume()
        elif src_state == "shut off":
            vm.start()

        # Checking for --persistent.
        check_dest_persistent = True
        if options.count("persistent") or extra.count("persistent"):
            logging.debug("Checking for --persistent option.")
开发者ID:dzhengfy,项目名称:tp-libvirt,代码行数:31,代码来源:virsh_migrate.py


示例11: handle_error

        except error.CmdError:
            handle_error("Failed getting snapshots info", vm_name)
        except error.TestFail, e:
            handle_error(str(e), vm_name)
        logging.info("Snapshot %s verified", sni["Name"])

    logging.info("Test snapshot switching")
    for sni in snapshot_info:
        try:
            # Assure VM is shut off before revert.
            virsh.destroy(vm_name)
            result = virsh.snapshot_revert(vm_name, sni["Name"])
            if result.exit_status:
                raise error.TestFail("Snapshot revert failed.\n"
                                     "Error: %s." % result.stderr)
            state = normalize_state(virsh.domstate(vm_name).stdout.strip())
            if state != sni["State"]:
                raise error.TestFail("Incorrect state after revert - %s"
                                     % (sni["Name"]))
            if state == normalize_state('shutoff'):
                vm.start()
            elif state == normalize_state('paused'):
                vm.resume()

            session = vm.wait_for_login()
            test_file(session, sni["to_create"], 0)
            test_file(session, sni["to_delete"], 2)
        except error.CmdError:
            handle_error("Failed to revert snapshot", vm_name)
        except (error.TestFail, virt_vm.VMDeadError), e:
            handle_error(str(e), vm_name)
开发者ID:Acidburn0zzz,项目名称:tp-libvirt,代码行数:31,代码来源:virsh_snapshot.py


示例12: check_info

                       "Incorrect children count")
            check_info(infos["Descendants"], sni["Descendants"],
                       "Incorrect descendants count")

        except error.CmdError:
            handle_error("Failed getting snapshots info", vm_name)
        except error.TestFail, e:
            handle_error(str(e),vm_name)
        logging.info("Snapshot %s verified", sni["Name"])


    logging.info("Test snapshot switching")
    for sni in snapshot_info:
        try:
            virsh.snapshot_revert(vm_name,sni["Name"])
            state = normalize_state(virsh.domstate(vm_name))
            if state != sni["State"]:
                raise error.TestFail("Incorrect state after revert - %s"
                                     % (sni["Name"]))
            if state == normalize_state('shutoff'):
                vm.start()
            elif state == normalize_state('paused'):
                vm.resume()

            session = vm.wait_for_login()
            test_file(session, sni["to_create"], 0)
            test_file(session, sni["to_delete"], 2)
        except error.CmdError:
            handle_error("Failed to revert snapshot", vm_name)
        except error.TestFail, e:
            handle_error(str(e), vm_name)
开发者ID:HeidCloud,项目名称:virt-test,代码行数:31,代码来源:virsh_snapshot.py


示例13: confirm_guest_status

    def confirm_guest_status():
        """
        Confirm the guest status after watchdog triggered
        """
        def _booting_completed():
            session = vm.wait_for_login()
            status, second_boot_time = session.cmd_status_output("uptime --since")
            logging.debug("The second boot time is %s", second_boot_time)
            session.close()
            return second_boot_time > first_boot_time

        def _inject_nmi():
            session = vm.wait_for_login()
            status, output = session.cmd_status_output("dmesg | grep -i nmi")
            session.close()
            if status == 0:
                logging.debug(output)
                return True
            return False

        def _inject_nmi_event():
            virsh_session.send_ctrl("^C")
            output = virsh_session.get_stripped_output()
            if "inject-nmi" not in output:
                return False
            return True

        def _check_dump_file(dump_path, domain_id):
            dump_file = glob.glob('%s%s-*' % (dump_path, domain_id))
            if len(dump_file):
                logging.debug("Find the auto core dump file:\n%s", dump_file[0])
                os.remove(dump_file[0])
                return True
            return False

        if action in ["poweroff", "shutdown"]:
            if not utils_misc.wait_for(lambda: vm.state() == "shut off", 180, 10):
                test.fail("Guest not shutdown after watchdog triggered")
        elif action == "reset":
            if not utils_misc.wait_for(_booting_completed, 600, 10):
                test.fail("Guest not reboot after watchdog triggered")
        elif action == "pause":
            if utils_misc.wait_for(lambda: vm.state() == "paused", 180, 10):
                cmd_output = virsh.domstate(vm_name, '--reason').stdout.strip()
                logging.debug("Check guest status: %s\n", cmd_output)
                if cmd_output != "paused (watchdog)":
                    test.fail("The domstate is not correct after dump by watchdog")
            else:
                test.fail("Guest not pause after watchdog triggered")
        elif action == "none" and utils_misc.wait_for(lambda: vm.state() == "shut off", 180, 10):
            test.fail("Guest shutdown unexpectedly")
        elif action == "inject-nmi":
            if not utils_misc.wait_for(_inject_nmi, 180, 10):
                test.fail("Guest not receive inject-nmi after watchdog triggered\n")
            elif not utils_misc.wait_for(_inject_nmi_event, 180, 10):
                test.fail("No inject-nmi watchdog event caught")
            virsh_session.close()
        elif action == "dump":
            domain_id = vm.get_id()
            dump_path = "/var/lib/libvirt/qemu/dump/"
            if not utils_misc.wait_for(lambda: _check_dump_file(dump_path, domain_id), 180, 10):
                test.fail("No auto core dump file found after watchdog triggered")
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:62,代码来源:watchdog.py


示例14: run_virsh_domstate

def run_virsh_domstate(test, params, env):
    """
    Test command: virsh domstate.

    1.Prepare test environment.
    2.When the libvirtd == "off", stop the libvirtd service.
    3.Perform virsh domstate operation.
    4.Recover test environment.
    5.Confirm the test result.
    """
    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)

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

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

    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 = "%s %s" % (vm_name, params.get("domstate_extra"))
    elif  vm_ref == "uuid":
        vm_ref = domuuid

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

    if vm_ref == "remote":
        remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM")
        local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM")
        remote_pwd = params.get("remote_pwd", None)
        if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"):
            raise error.TestNAError("Test 'remote' parameters not setup")
        status = 0
        try:
            remote_uri = libvirt_vm.complete_uri(local_ip)
            session = remote.remote_login("ssh", remote_ip, "22", "root",
                                          remote_pwd, "#")
            session.cmd_output('LANG=C')
            command = "virsh -c %s domstate %s" % (remote_uri, vm_name)
            status, output = session.cmd_status_output(command,
                                                       internal_timeout=5)
            session.close()
        except error.CmdError:
            status = 1
    else:
        result = virsh.domstate(vm_ref, ignore_status=True)
        status = result.exit_status
        output = result.stdout

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

    #check status_error
    if status_error == "yes":
        if status == 0:
            raise error.TestFail("Run successfully with wrong command!")
    elif status_error == "no":
        if status != 0 or output == "":
            raise error.TestFail("Run failed with right command")
        if vm_ref == "remote":
            if not (re.match("running", output) or re.match("blocked", output)
                 or re.match("idle", output)):
                raise error.TestFail("Run failed with right command")
开发者ID:FengYang,项目名称:virt-test,代码行数:72,代码来源:virsh_domstate.py


示例15: chk_libvirtd_log

                    if (re.search(log_pattern, cmd_result.stdout) or
                            chk_libvirtd_log(libvirtd_log_path,
                                             log_pattern, "debug")):
                        logging.debug("Found success a timed out block copy")
                else:
                    raise error.TestFail("Expect fail, but run "
                                         "successfully.")
    finally:
        # Restore libvirtd conf and restart libvirtd
        libvirtd_conf.restore()
        libvirtd_utl.restart()
        if libvirtd_log_path and os.path.exists(libvirtd_log_path):
            os.unlink(libvirtd_log_path)

        if vm.is_alive():
            vm.destroy(gracefully=False)
        utils_misc.wait_for(
            lambda: virsh.domstate(vm_name, ignore_status=True).exit_status, 2)
        original_xml.sync("--snapshots-metadata")

        if replace_vm_disk and disk_source_protocol == "netfs":
            restore_selinux = params.get('selinux_status_bak')
            utl.setup_or_cleanup_nfs(is_setup=False,
                                     restore_selinux=restore_selinux)
        if os.path.exists(dest_path):
            os.remove(dest_path)
        if os.path.exists(snap_path):
            os.remove(snap_path)
        if os.path.exists(save_path):
            os.remove(save_path)
开发者ID:Chenditang,项目名称:tp-libvirt,代码行数:30,代码来源:virsh_blockcopy.py


示例16:

            if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"):
                raise error.TestNAError("Test 'remote' parameters not setup")
            status = 0
            try:
                remote_uri = libvirt_vm.complete_uri(local_ip)
                session = remote.remote_login("ssh", remote_ip, "22", "root",
                                              remote_pwd, "#")
                session.cmd_output('LANG=C')
                command = "virsh -c %s domstate %s" % (remote_uri, vm_name)
                status, output = session.cmd_status_output(command,
                                                           internal_timeout=5)
                session.close()
            except error.CmdError:
                status = 1
        else:
            result = virsh.domstate(vm_ref, extra, ignore_status=True,
                                    debug=True)
            status = result.exit_status
            output = result.stdout.strip()

        # check status_error
        if status_error:
            if not status:
                raise error.TestFail("Run successfully with wrong command!")
        else:
            if status or not output:
                raise error.TestFail("Run failed with right command")
            if extra.count("reason"):
                if vm_action == "suspend":
                    # If not, will cost long time to destroy vm
                    virsh.destroy(vm_name)
                    if not output.count("user"):
开发者ID:Acidburn0zzz,项目名称:tp-libvirt,代码行数:32,代码来源:virsh_domstate.py


示例17: run

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

    Run a reboot command in the target domain.
    1.Prepare test environment.
    2.When the libvirtd == "off", stop the libvirtd service.
    3.Perform virsh reboot operation.
    4.Recover test environment.(libvirts service)
    5.Confirm the test result.
    """

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

    # run test case
    libvirtd = params.get("libvirtd", "on")
    vm_ref = params.get("reboot_vm_ref")
    status_error = ("yes" == params.get("status_error"))
    extra = params.get("reboot_extra", "")
    remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM")
    local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM")
    remote_pwd = params.get("remote_pwd", "password")
    agent = ("yes" == params.get("reboot_agent", "no"))
    mode = params.get("reboot_mode", "")
    pre_domian_status = params.get("reboot_pre_domian_status", "running")
    reboot_readonly = "yes" == params.get("reboot_readonly", "no")
    xml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
    try:
        # Add or remove qemu-agent from guest before test
        try:
            vm.prepare_guest_agent(channel=agent, start=agent)
        except virt_vm.VMError as e:
            logging.debug(e)
            # qemu-guest-agent is not available on REHL5
            test.cancel("qemu-guest-agent package is not available")

        if pre_domian_status == "shutoff":
            virsh.destroy(vm_name)
        if libvirtd == "off":
            utils_libvirtd.libvirtd_stop()

        domid = vm.get_id()
        domuuid = vm.get_uuid()
        if vm_ref == "id":
            vm_ref = domid
        elif vm_ref == "name":
            vm_ref = vm_name
        elif vm_ref == "uuid":
            vm_ref = domuuid
        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 == "remote_name":
            if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"):
                test.cancel("remote_ip and/or local_ip parameters"
                            " not changed from default values")
            complete_uri = libvirt_vm.complete_uri(local_ip)
            try:
                session = remote.remote_login("ssh", remote_ip, "22", "root",
                                              remote_pwd, "#")
                session.cmd_output('LANG=C')
                command = "virsh -c %s reboot %s %s" % (complete_uri, vm_name,
                                                        mode)
                status, output = session.cmd_status_output(command,
                                                           internal_timeout=5)
                session.close()
                if not status:
                    # the operation before the end of reboot
                    # may result in data corruption
                    vm.wait_for_login().close()
            except (remote.LoginError, process.CmdError, aexpect.ShellError) as e:
                logging.error("Exception: %s", str(e))
                status = -1
        if vm_ref != "remote_name":
            vm_ref = "%s" % vm_ref
            if extra:
                vm_ref += " %s" % extra
            cmdresult = virsh.reboot(vm_ref, mode,
                                     ignore_status=True, debug=True)
            status = cmdresult.exit_status
            if status:
                logging.debug("Error status, cmd error: %s", cmdresult.stderr)
                if not virsh.has_command_help_match('reboot', '\s+--mode\s+'):
                    # old libvirt doesn't support reboot
                    status = -2
            time.sleep(5)
            # avoid the check if it is negative test
            if not status_error:
                cmdoutput = virsh.domstate(vm_ref, '--reason',
                                           ignore_status=True, debug=True)
                domstate_status = cmdoutput.exit_status
                output = "running" in cmdoutput.stdout
                if domstate_status or (not output):
                    test.fail("Cmd error: %s Error status: %s" %
                              (cmdoutput.stderr, cmdoutput.stdout))
            elif pre_domian_status != 'shutoff':
                vm.wait_for_login().close()
        output = virsh.dom_list(ignore_status=True).stdout.strip()
#.........这里部分代码省略.........
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:101,代码来源:virsh_reboot.py


示例18: run


#.........这里部分代码省略.........
                'devices').find('graphics').get('type')

        backup_xml = None
        # Only kvm guest's xml needs to be backup currently
        if checkpoint in backup_list and hypervisor == 'kvm':
            backup_xml = ori_vm_xml
        if checkpoint == 'multi_disks':
            new_xml = vm_xml.VMXML.new_from_inactive_dumpxml(
                vm_name, virsh_instance=v2v_virsh)
            disk_count = 0
            for disk in list(new_xml.get_disk_all().values()):
                if disk.get('device') == 'disk':
                    disk_count += 1
            if disk_count <= 1:
                test.error('Not enough disk devices')
            params['ori_disks'] = disk_count
        if checkpoint == 'sata_disk':
            change_disk_bus('sata')
        if checkpoint.startswith('floppy'):
            img_path = data_dir.get_tmp_dir() + '/floppy.img'
            utlv.create_local_disk('floppy', img_path)
            attach_removable_media('floppy', img_path, 'fda')
            if checkpoint == 'floppy_devmap':
                insert_floppy_devicemap()
        if checkpoint.startswith('fstab'):
            if checkpoint == 'fstab_cdrom':
                img_path = data_dir.get_tmp_dir() + '/cdrom.iso'
                utlv.create_local_disk('iso', img_path)
                attach_removable_media('cdrom', img_path, 'hdc')
            specify_fstab_entry(checkpoint[6:])
        if checkpoint == 'running':
            virsh.start(vm_name)
            logging.info('VM state: %s' %
                         virsh.domstate(vm_name).stdout.strip())
        if checkpoint == 'paused':
            virsh.start(vm_name, '--paused')
            logging.info('VM state: %s' %
                         virsh.domstate(vm_name).stdout.strip())
        if checkpoint == 'serial_terminal':
            grub_serial_terminal()
            check_boot()
        if checkpoint == 'no_space':
            @vm_shell
            def take_space(**kwargs):
                create_large_file(kwargs['session'], 20)
            take_space()
        if checkpoint.startswith('host_no_space'):
            session = aexpect.ShellSession('sh')
            create_large_file(session, 1000)
            if checkpoint == 'host_no_space_setcache':
                logging.info('Set LIBGUESTFS_CACHEDIR=/home')
                os.environ['LIBGUESTFS_CACHEDIR'] = '/home'
        if checkpoint == 'corrupt_rpmdb':
            corrupt_rpmdb()
        if checkpoint.startswith('network'):
            change_network_model(checkpoint[8:])
        if checkpoint == 'multi_netcards':
            params['mac_address'] = []
            vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(
                vm_name, virsh_instance=v2v_virsh)
            network_list = vmxml.get_iface_all()
            for mac in network_list:
                if network_list[mac].get('type') in ['bridge', 'network']:
                    params['mac_address'].append(mac)
            if len(params['mac_address']) < 2:
                test.error('Not enough network interface')
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:67,代码来源:specific_kvm.py


示例19: chk_libvirtd_log

                    if re.search(log_pattern, cmd_result.stdout) or chk_libvirtd_log(
                        libvirtd_log_path, log_pattern, "debug"
                    ):
                        logging.debug("Found success a timed out block copy")
                else:
                    raise error.TestFail("Expect fail, but run " "successfully. %s" % bug_url)
    finally:
        # Restore libvirtd conf and restart libvirtd
        libvirtd_conf.restore()
        libvirtd_utl.restart()
        if libvirtd_log_path and os.path.exists(libvirtd_log_path):
            os.unlink(libvirtd_log_path)

        if vm.is_alive():
            vm.destroy(gracefully=False)
        utils_misc.wait_for(lambda: virsh.domstate(vm_name, ignore_status=True).exit_status, 2)
        if active_snap or with_shallow:
            option = "--snapshots-metadata"
        else:
            option = None
        original_xml.sync(option)

        for disk in snapshot_external_disks:
            if os.path.exists(disk):
                os.remove(disk)

        if replace_vm_disk:
            if disk_source_protocol == "netfs":
                restore_selinux = params.get("selinux_status_bak")
                utl.setup_or_cleanup_nfs(is_setup=False, restore_selinux=restore_selinux)
            elif disk_source_protocol == "iscsi":
开发者ID:uni-peter-zheng,项目名称:tp-libvirt,代码行数:31,代码来源:virsh_blockcopy.py


示例20: _wait_for_state

 def _wait_for_state():
     cmd_output = virsh.domstate(vm_name, '--reason').stdout.strip()
     return cmd_output.strip() == expect_output
开发者ID:pezhang,项目名称:tp-libvirt,代码行数:3,代码来源:virsh_domstate.py



注:本文中的virttest.virsh.domstate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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