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


Python virsh.domstate函数代码示例

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


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


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