def run(test, params, env): """ Test command: virsh domuuid. """ vm_name = params.get("main_vm", "vm1") vm = env.get_vm(vm_name) vm.verify_alive() # Get parameters vm_ref = params.get("domuuid_vm_ref", "domname") vm_state = params.get("domuuid_vm_state", "running") addition_arg = params.get("domuuid_addition_arg") libvirtd = params.get("libvirtd", "on") status_error = params.get("status_error", "no") domid = vm.get_id() vmxml = libvirt_xml.VMXML.new_from_dumpxml(vm_name) xml_domuuid = vmxml.uuid logging.debug("UUID in XML is:\n%s", xml_domuuid) if vm_state == "shutoff": vm.destroy() # Prepare options if vm_ref == "domid": vm_ref = domid elif vm_ref == "hex_id": vm_ref = hex(int(domid)) elif vm_ref == "domname": vm_ref = vm_name # Add additional argument if vm_ref and addition_arg: vm_ref = "%s %s" % (vm_ref, addition_arg) # Prepare libvirtd state if libvirtd == "off": utils_libvirtd.libvirtd_stop() result = virsh.domuuid(vm_ref) logging.debug(result) 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 == "yes": if status == 0: test.fail("Run successfully with wrong command!") elif status_error == "no": if not check_domuuid_compliant_with_rfc4122(output): test.fail("UUID is not compliant with RFC4122 format") if status != 0: test.fail("Run failed with right command.") elif xml_domuuid != output: test.fail("UUID from virsh command is not expected.")
def run_virsh_reboot(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 = 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") domid = vm.get_id() domuuid = vm.get_uuid() if libvirtd == "off": utils_libvirtd.libvirtd_stop() 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"): raise error.TestNAError("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" % (complete_uri, vm_name) status, output = session.cmd_status_output(command, internal_timeout=5) session.close() # FIXME: Catch specific exception except Exception, detail: logging.error("Exception: %s", str(detail)) status = -1
def run(test, params, env): """ Test the command virsh hostname (1) Call virsh hostname (2) Call virsh hostname with an unexpected option (3) Call virsh hostname with libvirtd service stop """ hostname_result = utils.run("hostname", ignore_status=True) hostname = hostname_result.stdout.strip() # Prepare libvirtd service check_libvirtd = params.has_key("libvirtd") if check_libvirtd: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_hostname_options") try: hostname_test = virsh.hostname(option, ignore_status=False, debug=True) status = 0 # good except error.CmdError: status = 1 # bad hostname_test = None # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: raise error.TestFail("Command 'virsh hostname %s' succeeded " "(incorrect command)" % option) elif status_error == "no": if cmp(hostname, hostname_test) != 0: raise error.TestFail( "Virsh cmd gives hostname %s != %s." % (hostname_test, hostname)) if status != 0: raise error.TestFail("Command 'virsh hostname %s' failed " "(correct command)" % option)
def run(test, params, env): """ Test the command virsh version (1) Call virsh version (2) Call virsh version with an unexpected option (3) Call virsh version with libvirtd service stop """ connect_uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri", "default")) # Prepare libvirtd service check_libvirtd = params.has_key("libvirtd") if check_libvirtd: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_version_options") try: output = virsh.version(option, uri=connect_uri, ignore_status=False, debug=True) status = 0 # good except error.CmdError: status = 1 # bad # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: raise error.TestFail("Command 'virsh version %s' succeeded " "(incorrect command)" % option) elif status_error == "no": if status != 0: raise error.TestFail("Command 'virsh version %s' failed " "(correct command)" % option)
def run(test, params, env): """ Test the command virsh version (1) Call virsh version (2) Call virsh version with an unexpected option (3) Call virsh version with libvirtd service stop """ connect_uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri", "default")) libvirtd = params.get("libvirtd", "on") option = params.get("virsh_version_options") status_error = (params.get("status_error") == "yes") # Prepare libvirtd service if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case result = virsh.version(option, uri=connect_uri, debug=True) # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error if status_error: if not result.exit_status: test.fail("Command 'virsh version %s' succeeded " "(incorrect command)" % option) else: if result.exit_status: test.fail("Command 'virsh version %s' failed " "(correct command)" % option) if option.count("daemon") and not result.stdout.count("daemon"): test.fail("No daemon information outputed!")
def run(test, params, env): """ Test command: virsh save. The command can save the RAM state of a running domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Run virsh save command with assigned options. 4.Recover test environment.(If the libvirtd service is stopped ,start the libvirtd service.) 5.Confirm the test result. """ savefile = params.get("save_file", "save.file") if savefile: savefile = os.path.join(data_dir.get_tmp_dir(), savefile) libvirtd = params.get("libvirtd", "on") extra_param = params.get("save_extra_param") vm_ref = params.get("save_vm_ref") progress = ("yes" == params.get("save_progress", "no")) options = params.get("save_option", "") status_error = ("yes" == params.get("save_status_error", "yes")) vm_name = params.get("main_vm", "avocado-vt-vm1") vm = env.get_vm(vm_name) uri = params.get("virsh_uri") readonly = ("yes" == params.get("save_readonly", "no")) expect_msg = params.get("save_err_msg", "") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' if not libvirt_version.version_compare(1, 1, 1): if params.get('setup_libvirt_polkit') == 'yes': test.cancel("API acl test not supported in current" " libvirt version.") domid = vm.get_id() domuuid = vm.get_uuid() # set the option if vm_ref == "id": vm_ref = domid elif vm_ref == "hex_id": vm_ref = hex(int(domid)) elif vm_ref == "uuid": vm_ref = domuuid elif vm_ref.count("invalid"): vm_ref = params.get(vm_ref) elif vm_ref.count("name"): vm_ref = vm_name vm_ref += (" %s" % extra_param) if libvirtd == "off": utils_libvirtd.libvirtd_stop() if progress: options += " --verbose" result = virsh.save(vm_ref, savefile, options, ignore_status=True, unprivileged_user=unprivileged_user, uri=uri, debug=True, readonly=readonly) status = result.exit_status err_msg = result.stderr.strip() # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() if savefile: virsh.restore(savefile, debug=True) # check status_error try: if status_error: if not status: if libvirtd == "off" and libvirt_version.version_compare( 5, 6, 0): logging.info( "From libvirt version 5.6.0 libvirtd is restarted " "and command should succeed") else: test.fail("virsh run succeeded with an " "incorrect command") if readonly: if not re.search(expect_msg, err_msg): test.fail("Fail to get expect err msg: %s" % expect_msg) else: if status: test.fail("virsh run failed with a " "correct command") if progress and not err_msg.count("Save:"): test.fail("No progress information outputed!") if options.count("running"): if vm.is_dead() or vm.is_paused(): test.fail("Guest state should be" " running after restore" " due to the option --running") elif options.count("paused"): if not vm.is_paused(): test.fail("Guest state should be" " paused after restore" " due to the option --paused") else: if vm.is_dead(): test.fail("Guest state should be" " alive after restore" " since no option was specified") finally: if vm.is_paused(): virsh.resume(vm_name)
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") 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, e: logging.debug(e) # qemu-guest-agent is not available on REHL5 raise error.TestNAError("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"): raise error.TestNAError("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() except (remote.LoginError, process.CmdError, aexpect.ShellError), e: logging.error("Exception: %s", str(e)) status = -1
def run_virsh_dominfo(test, params, env): """ Test command: virsh dominfo. The command returns basic information about the domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh dominfo operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm", "vm1") vm = env.get_vm(vm_name) if vm.is_alive() and params.get("start_vm") == "no": vm.destroy() domid = vm.get_id() domuuid = vm.get_uuid() vm_ref = params.get("dominfo_vm_ref") extra = params.get("dominfo_extra", "") status_error = params.get("status_error", "no") libvirtd = params.get("libvirtd", "on") def remote_test(params, vm_name): """ Test remote case. """ remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", "") status = 0 output = "" err = "" try: 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.") 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 dominfo %s" % (uri, vm_name) status, output = session.cmd_status_output(command, internal_timeout=5) if status != 0: err = output session.close() except error.CmdError: status = 1 output = "" err = "remote test failed" return status, output, err #run test case 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, extra) elif vm_ref == "uuid": vm_ref = domuuid if libvirtd == "off": utils_libvirtd.libvirtd_stop() if vm_ref != "remote": result = virsh.dominfo(vm_ref, ignore_status=True) status = result.exit_status output = result.stdout.strip() err = result.stderr.strip() else: status, output, err = remote_test(params, vm_name) #recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() #check status_error if status_error == "yes": if status == 0 or err == "": 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")
raise error.TestError("Creating %s failed." % dest_xmlfile) # Turn VM into certain state. logging.debug("Turning %s into certain state." % vm.name) if src_state == "paused": if vm.is_alive(): vm.pause() elif src_state == "shut off": if vm.is_alive(): if not vm.shutdown(): vm.destroy() # Turn libvirtd into certain state. logging.debug("Turning libvirtd into certain status.") if libvirtd_state == "off": utils_libvirtd.libvirtd_stop() # Test uni-direction migration. logging.debug("Doing migration test.") if vm_ref != vm_name: vm.name = vm_ref # For vm name error testing. ret_migrate = do_migration(delay, vm, dest_uri, options, extra) if vm_ref != vm_name: vm.name = vm_name # Recover libvirtd state. logging.debug("Recovering libvirtd status.") if libvirtd_state == "off": utils_libvirtd.libvirtd_start() # Check vm state on destination.
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", "#") pool_type = params.get("pool_type") pool_name = params.get("pool_name", "test") pool_target = params.get("pool_target") volume_size = params.get("volume_size", "1G") vol_name = params.get("vol_name", "test_vol") emulated_img = params.get("emulated_img", "emulated_img") emulated_size = "%sG" % (int(volume_size[:-1]) + 1) disk_target = params.get("disk_target", "vdb") wipe_data = "yes" == params.get("wipe_data", "no") if wipe_data: option += " --wipe-storage" 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() # polkit acl related params uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' if not libvirt_version.version_compare(1, 1, 1): if params.get('setup_libvirt_polkit') == 'yes': raise error.TestNAError("API acl test not supported in current" " libvirt version.") # Back up xml file.Xen host has no guest xml file to define a guset. backup_xml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) # Confirm how to reference a VM. if vm_ref == "vm_name": vm_ref = vm_name elif vm_ref == "id": vm_ref = vm_id elif vm_ref == "hex_vm_id": vm_ref = hex(int(vm_id)) elif vm_ref == "uuid": vm_ref = vm_uuid elif vm_ref.find("invalid") != -1: vm_ref = params.get(vm_ref) volume = None pvtest = None status3 = None try: save_file = "/var/lib/libvirt/qemu/save/%s.save" % vm_name if option.count("managedsave") and vm.is_alive(): virsh.managedsave(vm_name) if not vm.is_lxc(): snp_list = virsh.snapshot_list(vm_name) if option.count("snapshot"): snp_file_list = [] if not len(snp_list): virsh.snapshot_create(vm_name) logging.debug("Create a snapshot for test!") else: # Backup snapshots for domain for snp_item in snp_list: tmp_file = os.path.join(test.tmpdir, snp_item + ".xml") virsh.snapshot_dumpxml(vm_name, snp_item, to_file=tmp_file) snp_file_list.append(tmp_file) else: if len(snp_list): raise error.TestNAError("This domain has snapshot(s), " "cannot be undefined!") if option.count("remove-all-storage"): pvtest = utlv.PoolVolumeTest(test, params) pvtest.pre_pool(pool_name, pool_type, pool_target, emulated_img, emulated_size=emulated_size) new_pool = libvirt_storage.PoolVolume(pool_name) if not new_pool.create_volume(vol_name, volume_size): raise error.TestFail("Creation of volume %s failed." % vol_name) volumes = new_pool.list_volumes() volume = volumes[vol_name] virsh.attach_disk(vm_name, volume, disk_target, "--config") # Turn libvirtd into certain state. if libvirtd_state == "off": utils_libvirtd.libvirtd_stop() # Test virsh undefine command. output = "" if vm_ref != "remote": vm_ref = "%s %s" % (vm_ref, extra) cmdresult = virsh.undefine(vm_ref, option, unprivileged_user=unprivileged_user, uri=uri, ignore_status=True, debug=True) status = cmdresult.exit_status output = cmdresult.stdout.strip() if status: logging.debug("Error status, command output: %s", cmdresult.stderr.strip()) if undefine_twice: status2 = virsh.undefine(vm_ref, ignore_status=True).exit_status else: if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"): raise error.TestNAError("remote_ip and/or local_ip parameters" " not changed from default values") try: uri = libvirt_vm.complete_uri(local_ip) session = remote.remote_login("ssh", remote_ip, "22", remote_user, remote_pwd, remote_prompt) cmd_undefine = "virsh -c %s undefine %s" % (uri, vm_name) status, output = session.cmd_status_output(cmd_undefine) logging.info("Undefine output: %s", output) except (error.CmdError, remote.LoginError, aexpect.ShellError), de: logging.error("Detail: %s", de) status = 1 # Recover libvirtd state. if libvirtd_state == "off": utils_libvirtd.libvirtd_start() # Shutdown VM. if virsh.domain_exists(vm.name): try: if vm.is_alive(): vm.destroy(gracefully=False) except error.CmdError, detail: logging.error("Detail: %s", detail)
def run(test, params, env): """ Test the command virsh capabilities (1) Call virsh capabilities (2) Call virsh capabilities with an unexpected option (3) Call virsh capabilities with libvirtd service stop """ def compare_capabilities_xml(source): cap_xml = capability_xml.CapabilityXML() cap_xml.xml = source # Check that host has a non-empty UUID tag. xml_uuid = cap_xml.uuid logging.debug("Host UUID (capabilities_xml): %s" % xml_uuid) if xml_uuid == "": raise error.TestFail("The host uuid in capabilities_xml is none!") # Check the host arch. xml_arch = cap_xml.arch logging.debug("Host arch (capabilities_xml): %s", xml_arch) exp_arch = utils.run("arch", ignore_status=True).stdout.strip() if cmp(xml_arch, exp_arch) != 0: raise error.TestFail("The host arch in capabilities_xml is expected" " to be %s, but get %s" % (exp_arch, xml_arch)) # Check the host cpu count. xml_cpu_count = cap_xml.cpu_count logging.debug("Host cpus count (capabilities_xml): %s", xml_cpu_count) cmd = "grep processor /proc/cpuinfo | wc -l" exp_cpu_count = int(utils.run(cmd, ignore_status=True).stdout.strip()) if xml_cpu_count != exp_cpu_count: raise error.TestFail("Host cpus count is expected to be %s, but get " "%s" % (exp_cpu_count, xml_cpu_count)) # Check the arch of guest supported. guest_capa = cap_xml.get_guest_capabilities() logging.debug(guest_capa) try: img = utils_misc.find_command("qemu-kvm") except ValueError: raise error.TestNAError("Cannot find qemu-kvm") if re.search("ppc", utils.run("arch").stdout): cmd = img + " --cpu ? | grep ppc" else: cmd = img + " --cpu ? | grep qemu" cmd_result = utils.run(cmd, ignore_status=True) for guest in cap_xml.xmltreefile.findall('guest'): guest_wordsize = guest.find('arch').find('wordsize').text logging.debug("Arch of guest supported (capabilities_xml):%s", guest_wordsize) if not re.search(guest_wordsize, cmd_result.stdout.strip()): raise error.TestFail("The capabilities_xml gives an extra arch " "of guest to support!") # Check the type of hypervisor. first_guest = cap_xml.xmltreefile.findall('guest')[0] first_domain = first_guest.find('arch').findall('domain')[0] guest_domain_type = first_domain.get('type') logging.debug("Hypervisor (capabilities_xml):%s", guest_domain_type) cmd_result = utils.run("virsh uri", ignore_status=True) if not re.search(guest_domain_type, cmd_result.stdout.strip()): raise error.TestFail("The capabilities_xml gives an different " "hypervisor") # check power management support. try: pm_cmd = os_dep.command('pm-is-supported') pm_cap_map = {'suspend': 'suspend_mem', 'hibernate': 'suspend_disk', 'suspend-hybrid': 'suspend_hybrid', } exp_pms = [] for opt in pm_cap_map: cmd = '%s --%s' % (pm_cmd, opt) res = utils.run(cmd, ignore_status=True) if res.exit_status == 0: exp_pms.append(pm_cap_map[opt]) pms = cap_xml.power_management_list if set(exp_pms) != set(pms): raise error.TestFail("Expected supported PMs are %s, got %s " "instead." % (exp_pms, pms)) except ValueError: logging.debug('Power management checking is skipped, since command ' 'pm-is-supported is not found.') connect_uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri", "default")) # Prepare libvirtd service if "libvirtd" in params: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_cap_options") try: output = virsh.capabilities(option, uri=connect_uri, ignore_status=False, debug=True) status = 0 # good except error.CmdError: status = 1 # bad output = '' # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off": raise error.TestFail("Command 'virsh capabilities' succeeded " "with libvirtd service stopped, incorrect") else: raise error.TestFail("Command 'virsh capabilities %s' succeeded " "(incorrect command)" % option) elif status_error == "no": compare_capabilities_xml(output) if status != 0: raise error.TestFail("Command 'virsh capabilities %s' failed " "(correct command)" % option)
def run(test, params, env): """ Test the command virsh nodecpustats (1) Call the virsh nodecpustats command for all cpu host cpus separately (2) Get the output (3) Check the against /proc/stat output(o) for respective cpu user: o[0] + o[1] system: o[2] + o[5] + o[6] idle: o[3] iowait: o[4] (4) Call the virsh nodecpustats command with an unexpected option (5) Call the virsh nodecpustats command with libvirtd service stop """ def get_expected_stat(cpu=None): """ Parse cpu stats from /proc/stat :param cpu: cpu index, None for total cpu stat :return: dict of cpu stats """ stats = {} cpu_stat = [] with open("/proc/stat", "r") as fl: for line in fl.readlines(): if line.startswith("cpu"): cpu_stat.append(line.strip().split(" ")[1:]) # Delete additional space in the total cpu stats line del cpu_stat[0][0] if cpu is None: idx = 0 else: idx = int(cpu) + 1 stats['user'] = int(cpu_stat[idx][0]) + int(cpu_stat[idx][1]) stats['system'] = int(cpu_stat[idx][2]) + int(cpu_stat[idx][5]) + int( cpu_stat[idx][6]) stats['idle'] = int(cpu_stat[idx][3]) stats['iowait'] = int(cpu_stat[idx][4]) stats['total'] = stats['user'] + stats['system'] + stats[ 'idle'] + stats['iowait'] return stats def virsh_check_nodecpustats_percpu(actual_stats, cpu): """ Check the actual nodecpustats output value total time <= total stat from proc :param actual_stats: Actual cpu stats :param cpu: cpu index :return: True if matches, else failout """ # Normalise to seconds from nano seconds total = float( (actual_stats['system'] + actual_stats['user'] + actual_stats['idle'] + actual_stats['iowait']) / (10**9)) expected = get_expected_stat(cpu) if not total <= expected['total']: test.fail("Commands 'virsh nodecpustats' not succeeded" " as total time: %f is more" " than proc/stat: %f" % (total, expected['total'])) return True def virsh_check_nodecpustats(actual_stats): """ Check the actual nodecpustats output value total time <= total stat from proc :param actual_stats: Actual cpu stats :return: True if matches, else failout """ # Normalise to seconds from nano seconds and get for one cpu total = float( ((actual_stats['system'] + actual_stats['user'] + actual_stats['idle'] + actual_stats['iowait']) / (10**9))) expected = get_expected_stat() if not total <= expected['total']: test.fail("Commands 'virsh nodecpustats' not succeeded" " as total time: %f is more" " than proc/stat: %f" % (total, expected['total'])) return True def virsh_check_nodecpustats_percentage(actual_per): """ Check the actual nodecpustats percentage adds up to 100% :param actual_per: Actual cpu stats percentage :return: True if matches, else failout """ total = int( round(actual_per['user'] + actual_per['system'] + actual_per['idle'] + actual_per['iowait'])) if not total == 100: test.fail("Commands 'virsh nodecpustats' not succeeded" " as the total percentage value: %d" " is not equal 100" % total) def parse_output(output): """ To get the output parsed into a dictionary :param output: virsh command output :return: dict of user,system,idle,iowait times """ # From the beginning of a line, group 1 is one or more word-characters, # followed by zero or more whitespace characters and a ':', # then one or more whitespace characters, # followed by group 2, which is one or more digit characters, # e.g as below # user: 6163690000000 # regex_obj = re.compile(r"^(\w+)\s*:\s+(\d+)") actual = {} for line in output.stdout.split('\n'): match_obj = regex_obj.search(line) # Due to the extra space in the list if match_obj is not None: name = match_obj.group(1) value = match_obj.group(2) actual[name] = int(value) return actual def parse_percentage_output(output): """ To get the output parsed into a dictionary :param output: virsh command output :return: dict of user,system,idle,iowait times """ # From the beginning of a line, group 1 is one or more word-characters, # followed by zero or more whitespace characters and a ':', # then one or more whitespace characters, # followed by group 2, which is one or more digit characters, # e.g as below # user: 1.5% # regex_obj = re.compile(r"^(\w+)\s*:\s+(\d+.\d+)") actual_percentage = {} for line in output.stdout.split('\n'): match_obj = regex_obj.search(line) # Due to the extra space in the list if match_obj is not None: name = match_obj.group(1) value = match_obj.group(2) actual_percentage[name] = float(value) return actual_percentage # Initialize the variables itr = int(params.get("inner_test_iterations")) option = params.get("virsh_cpunodestats_options") invalid_cpunum = params.get("invalid_cpunum") status_error = params.get("status_error") libvirtd = params.get("libvirtd", "on") # Prepare libvirtd service if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Get the host cpu list host_cpus_list = cpuutil.cpu_online_list() # Run test case for 5 iterations default can be changed in subtests.cfg # file for i in range(itr): if status_error == "yes": if invalid_cpunum == "yes": option = "--cpu %s" % (len(host_cpus_list) + 1) output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: if libvirtd == "off": if libvirt_version.version_compare(5, 6, 0): logging.debug( "From libvirt version 5.6.0 libvirtd is restarted" " and command should succeed") else: utils_libvirtd.libvirtd_start() test.fail("Command 'virsh nodecpustats' " "succeeded with libvirtd service " "stopped, incorrect") else: test.fail("Command 'virsh nodecpustats %s' " "succeeded (incorrect command)" % option) if (invalid_cpunum == "yes" and libvirt_version.version_compare(6, 2, 0)): err_msg = "Invalid cpuNum in virHostCPUGetStatsLinux" libvirt.check_result(output, expected_fails=[err_msg]) elif status_error == "no": # Run the testcase for each cpu to get the cpu stats for idx, cpu in enumerate(host_cpus_list): option = "--cpu %s" % cpu output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: actual_value = parse_output(output) virsh_check_nodecpustats_percpu(actual_value, idx) else: test.fail("Command 'virsh nodecpustats %s'" "not succeeded" % option) # Run the test case for each cpu to get the cpu stats in percentage for cpu in host_cpus_list: option = "--cpu %s --percent" % cpu output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: actual_value = parse_percentage_output(output) virsh_check_nodecpustats_percentage(actual_value) else: test.fail("Command 'virsh nodecpustats %s'" " not succeeded" % option) option = '' # Run the test case for total cpus to get the cpus stats output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: actual_value = parse_output(output) virsh_check_nodecpustats(actual_value) else: test.fail("Command 'virsh nodecpustats %s'" " not succeeded" % option) # Run the test case for the total cpus to get the stats in # percentage option = "--percent" output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: actual_value = parse_percentage_output(output) virsh_check_nodecpustats_percentage(actual_value) else: test.fail("Command 'virsh nodecpustats %s'" " not succeeded" % option) # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start()
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") xml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) try: # Add or remove qemu-agent from guest before test if agent: vm_xml.VMXML.set_agent_channel(vm_name) else: vm_xml.VMXML.remove_agent_channel(vm_name) virsh.start(vm_name) guest_session = vm.wait_for_login() if agent: if guest_session.cmd_status("which qemu-ga"): raise error.TestNAError("Cannot execute this test for domain" " doesn't have qemu-ga command!") # check if the qemu-guest-agent is active or not firstly stat_ps = guest_session.cmd_status("ps aux |grep [q]emu-ga") if stat_ps != 0: s, o = guest_session.cmd_status_output("qemu-ga -d") if s != 0: raise error.TestError("'qemu-ga -d' failed.\noutput:%s" % o) stat_ps = guest_session.cmd_status("ps aux |grep [q]emu-ga") guest_session.close() if stat_ps: raise error.TestError("Fail to start qemu-guest-agent!") 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"): raise error.TestNAError("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() # FIXME: Catch specific exception except Exception, detail: logging.error("Exception: %s", str(detail)) status = -1 if vm_ref != "remote_name": vm_ref = "%s %s" % (vm_ref, 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 output = virsh.dom_list(ignore_status=True).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 re.search(vm_name, output)): if status == -2: raise error.TestNAError( "Reboot command doesn't work on older libvirt versions") raise error.TestFail("Run failed with right command")
def run(test, params, env): """ Test command: virsh dommemstat. The command gets memory statistics for a domain 1.Prepare test environment. 2.When the ibvirtd == "off", stop the libvirtd service. 3.Perform virsh dommemstat operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(params["main_vm"]) domid = vm.get_id() domuuid = vm.get_uuid() status_error = params.get("status_error", "no") vm_ref = params.get("dommemstat_vm_ref", "name") libvirtd = params.get("libvirtd", "on") extra = params.get("dommemstat_extra", "") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # run test case if vm_ref == "id": vm_ref = domid elif vm_ref == "hex_id": vm_ref = hex(int(domid)) elif vm_ref == "uuid": vm_ref = domuuid elif vm_ref.count("_invalid_"): # vm_ref names parameter to fetch vm_ref = params.get(vm_ref) elif vm_ref == "name": vm_ref = "%s" % vm_name if libvirtd == "off": utils_libvirtd.libvirtd_stop() try: if vm_ref != "remote": status = virsh.dommemstat(vm_ref, extra, ignore_status=True, debug=True).exit_status else: remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) remote_user = params.get("remote_user", "root") if remote_ip.count("EXAMPLE.COM"): test.cancel("remote ip parameters not set.") ssh_key.setup_ssh_key(remote_ip, remote_user, remote_pwd) remote_uri = "qemu+ssh://%s/system" % remote_ip virsh.start(vm_name, ignore_status=False, debug=True, uri=remote_uri) status = virsh.dommemstat(vm_name, ignore_status=True, debug=True, uri=remote_uri).exit_status finally: if vm_ref == "remote": virsh.destroy(vm_name, ignore_status=False, debug=True, uri=remote_uri) # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error == "yes": if status == 0: test.fail("Run successfully with wrong command!") elif status_error == "no": if status != 0: test.fail("Run failed with right command")
def run(test, params, env): """ Test the command virsh uri (1) Call virsh uri (2) Call virsh -c remote_uri uri (3) Call virsh uri with an unexpected option (4) Call virsh uri with libvirtd service stop """ connect_uri = libvirt_vm.normalize_connect_uri( params.get("connect_uri", "default")) option = params.get("virsh_uri_options") unprivileged_user = params.get('unprivileged_user') remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) remote_user = params.get("remote_user", "root") # Forming the uri using the api target_uri = params.get("target_uri") remote_ref = params.get("uri_remote_ref", "") if remote_ref: if target_uri.count('EXAMPLE.COM'): test.cancel('target_uri configuration set to sample value') logging.info("The target_uri: %s", target_uri) cmd = "virsh -c %s uri" % target_uri else: cmd = "virsh uri %s" % option # Prepare libvirtd service check_libvirtd = "libvirtd" in list(params.keys()) if check_libvirtd: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case logging.info("The command: %s", cmd) # setup autologin for ssh to remote machine to execute commands if remote_ref: ssh_key.setup_ssh_key(remote_ip, remote_user, remote_pwd) if unprivileged_user: if process.run("id %s" % unprivileged_user, ignore_status=True).exit_status != 0: process.run("useradd %s" % unprivileged_user) try: if remote_ref == "remote" or unprivileged_user: connect_uri = target_uri uri_test = virsh.canonical_uri(option, unprivileged_user=unprivileged_user, uri=connect_uri, ignore_status=False, debug=True) status = 0 # good except process.CmdError: status = 1 # bad uri_test = '' if unprivileged_user: process.run("userdel %s" % unprivileged_user) # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error", "no") if status_error == "yes": if status == 0: if libvirtd == "off" and libvirt_version.version_compare(5, 6, 0): logging.info( "From libvirt version 5.6.0 libvirtd is restarted " "and command should succeed.") else: test.fail("Command: %s succeeded " "(incorrect command)" % cmd) else: logging.info("command: %s is a expected error", cmd) elif status_error == "no": if target_uri != uri_test: test.fail("Virsh cmd uri %s != %s." % (uri_test, target_uri)) if status != 0: test.fail("Command: %s failed " "(correct command)" % cmd)
def run(test, params, env): """ Test the command virsh capabilities (1) Call virsh capabilities (2) Call virsh capabilities with an unexpected option (3) Call virsh capabilities with libvirtd service stop """ def compare_capabilities_xml(source): cap_xml = capability_xml.CapabilityXML() cap_xml.xml = source # Check that host has a non-empty UUID tag. xml_uuid = cap_xml.uuid logging.debug("Host UUID (capabilities_xml): %s", xml_uuid) if xml_uuid == "": raise error.TestFail("The host uuid in capabilities_xml is none!") # Check the host arch. xml_arch = cap_xml.arch logging.debug("Host arch (capabilities_xml): %s", xml_arch) exp_arch = process.run("arch", shell=True).stdout.strip() if cmp(xml_arch, exp_arch) != 0: raise error.TestFail("The host arch in capabilities_xml is " "expected to be %s, but get %s" % (exp_arch, xml_arch)) # Check the host cpu count. xml_cpu_count = cap_xml.cpu_count logging.debug("Host cpus count (capabilities_xml): %s", xml_cpu_count) cmd = "grep processor /proc/cpuinfo | wc -l" exp_cpu_count = int(process.run(cmd, shell=True).stdout.strip()) if xml_cpu_count != exp_cpu_count: raise error.TestFail("Host cpus count is expected to be %s, " "but get %s" % (exp_cpu_count, xml_cpu_count)) # Check the arch of guest supported. guest_capa = cap_xml.get_guest_capabilities() logging.debug(guest_capa) # libvirt track wordsize in hardcode struct virArchData wordsize = {} wordsize['64'] = [ 'alpha', 'aarch64', 'ia64', 'mips64', 'mips64el', 'parisc64', 'ppc64', 'ppc64le', 's390x', 'sh4eb', 'sparc64', 'x86_64' ] wordsize['32'] = [ 'armv6l', 'armv7l', 'armv7b', 'cris', 'i686', 'lm32', 'm68k', 'microblaze', 'microblazeel', 'mips', 'mipsel', 'openrisc', 'parisc', 'ppc', 'ppcle', 'ppcemb', 's390', 'sh4', 'sparc', 'unicore32', 'xtensa', 'xtensaeb' ] uri_type = process.run("virsh uri", shell=True).stdout.split(':')[0] domain_type = "domain_" + uri_type for arch_dict in guest_capa.values(): for arch, val_dict in arch_dict.items(): # Check wordsize if arch not in wordsize[val_dict['wordsize']]: raise error.TestFail("'%s' wordsize '%s' in " "capabilities_xml not expected" % (arch, val_dict['wordsize'])) # Check the type of hypervisor if domain_type not in val_dict.keys(): raise error.TestFail("domain type '%s' is not matched" " under arch '%s' in " "capabilities_xml" % (uri_type, arch)) # check power management support. try: pm_cmd = os_dep.command('pm-is-supported') pm_cap_map = { 'suspend': 'suspend_mem', 'hibernate': 'suspend_disk', 'suspend-hybrid': 'suspend_hybrid' } exp_pms = [] for opt in pm_cap_map: cmd = '%s --%s' % (pm_cmd, opt) res = process.run(cmd, ignore_status=True, shell=True) if res.exit_status == 0: exp_pms.append(pm_cap_map[opt]) pms = cap_xml.power_management_list if set(exp_pms) != set(pms): raise error.TestFail("Expected supported PMs are %s, got %s " "instead." % (exp_pms, pms)) except ValueError: logging.debug('Power management checking is skipped, since command' ' pm-is-supported is not found.') connect_uri = libvirt_vm.normalize_connect_uri( params.get("connect_uri", "default")) # Prepare libvirtd service if "libvirtd" in params: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_cap_options") try: output = virsh.capabilities(option, uri=connect_uri, ignore_status=False, debug=True) status = 0 # good except process.CmdError: status = 1 # bad output = '' # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off": raise error.TestFail("Command 'virsh capabilities' succeeded " "with libvirtd service stopped, " "incorrect") else: raise error.TestFail("Command 'virsh capabilities %s' " "succeeded (incorrect command)" % option) elif status_error == "no": compare_capabilities_xml(output) if status != 0: raise error.TestFail("Command 'virsh capabilities %s' failed " "(correct command)" % option)
def run(test, params, env): """ Test command: virsh dommemstat. The command gets memory statistics for a domain 1.Prepare test environment. 2.When the ibvirtd == "off", stop the libvirtd service. 3.Perform virsh dommemstat operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(params["main_vm"]) domid = vm.get_id() domuuid = vm.get_uuid() status_error = params.get("status_error", "no") vm_ref = params.get("dommemstat_vm_ref", "name") libvirtd = params.get("libvirtd", "on") extra = params.get("dommemstat_extra", "") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # run test case if vm_ref == "id": vm_ref = domid elif vm_ref == "hex_id": vm_ref = hex(int(domid)) elif vm_ref == "uuid": vm_ref = domuuid elif vm_ref.count("_invalid_"): # vm_ref names parameter to fetch vm_ref = params.get(vm_ref) elif vm_ref == "name": vm_ref = "%s" % vm_name if libvirtd == "off": utils_libvirtd.libvirtd_stop() if vm_ref != "remote": status = virsh.dommemstat(vm_ref, extra, ignore_status=True, debug=True).exit_status else: remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"): raise error.TestNAError("local/remote ip parameters not set.") 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 dommemstat %s %s" % (remote_uri, vm_name, extra) status = session.cmd_status(command, internal_timeout=5) session.close() except process.CmdError: status = 1 # recover libvirtd service start if libvirtd == "off": utils_libvirtd.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: raise error.TestFail("Run failed with right command")
def run_virsh_shutdown(test, params, env): """ Test command: virsh shutdown. The conmand can gracefully shutdown a domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh setvcpus operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) domid = vm.get_id() domuuid = vm.get_uuid() vm_ref = params.get("shutdown_vm_ref") libvirtd = params.get("libvirtd", "on") # run test case 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("shutdown_extra")) elif vm_ref == "uuid": vm_ref = domuuid if libvirtd == "off": utils_libvirtd.libvirtd_stop() if vm_ref != "remote": status = virsh.shutdown(vm_ref, ignore_status=True).exit_status else: remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"): raise error.TestNAError( "Remote test parameters unchanged from default") 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 shutdown %s" % (remote_uri, vm_name) status = session.cmd_status(command, internal_timeout=5) session.close() except error.CmdError: status = 1 # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: raise error.TestFail("Run successfully with wrong command!") elif status_error == "no": if status != 0: raise error.TestFail("Run failed with right command")
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)
def run(test, params, env): """ Test command: virsh save. The command can save the RAM state of a running domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Run virsh save command with assigned options. 4.Recover test environment.(If the libvirtd service is stopped ,start the libvirtd service.) 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(params["main_vm"]) vm.verify_alive() domid = vm.get_id().strip() domuuid = vm.get_uuid().strip() savefile = params.get("save_file", "save.file") # If savefile is not an abs path, join it to test.tmpdir if os.path.dirname(savefile) is "": savefile = os.path.join(test.tmpdir, savefile) pre_vm_state = params.get("save_pre_vm_state", "null") libvirtd = params.get("save_libvirtd") extra_param = params.get("save_extra_param") vm_ref = params.get("save_vm_ref") # prepare the environment if vm_ref == "name" and pre_vm_state == "paused": virsh.suspend(vm_name) elif vm_ref == "name" and pre_vm_state == "shut off": virsh.destroy(vm_name) # set the option if vm_ref == "id": vm_ref = domid elif vm_ref == "hex_id": vm_ref = hex(int(domid)) elif vm_ref == "uuid": vm_ref = domuuid elif vm_ref == "save_invalid_id" or vm_ref == "save_invalid_uuid": vm_ref = params.get(vm_ref) elif vm_ref.find("name") != -1 or vm_ref == "extra_param": savefile = "%s %s" % (savefile, extra_param) if vm_ref == "only_name": savefile = " " vm_ref = vm_name if libvirtd == "off": utils_libvirtd.libvirtd_stop() status = virsh.save(vm_ref, savefile, ignore_status=True).exit_status # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # cleanup if os.path.exists(savefile): virsh.restore(savefile) os.remove(savefile) # check status_error status_error = params.get("save_status_error") if status_error == "yes": if status == 0: raise error.TestFail("Run successfully with wrong command!") elif status_error == "no": if status != 0: raise error.TestFail("Run failed with right command")
raise error.TestError("Creating %s failed." % dest_xmlfile) # Turn VM into certain state. logging.debug("Turning %s into certain state." % vm.name) if src_state == "paused": if vm.is_alive(): vm.pause() elif src_state == "shut off": if vm.is_alive(): if not vm.shutdown(): vm.destroy() # Turn libvirtd into certain state. logging.debug("Turning libvirtd into certain status.") if libvirtd_state == "off": utils_libvirtd.libvirtd_stop() # Test uni-direction migration. logging.debug("Doing migration test.") if vm_ref != vm_name: vm.name = vm_ref # For vm name error testing. if unsafe_test: options = "--live" ret_migrate = do_migration(delay, vm, dest_uri, options, extra) # Check unsafe result and may do migration again in right mode check_unsafe_result = True if ret_migrate is False and unsafe_test: options = params.get("virsh_migrate_options") ret_migrate = do_migration(delay, vm, dest_uri, options, extra) elif ret_migrate and unsafe_test:
def run(test, params, env): """ Test command: virsh destroy. The command can destroy (stop) a domain. 1.Prepare test environment. 2.When the ibvirtd == "off", stop the libvirtd service. 3.Perform virsh destroy operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) domid = vm.get_id() domuuid = vm.get_uuid() vm_ref = params.get("destroy_vm_ref") status_error = params.get("status_error", "no") libvirtd = params.get("libvirtd", "on") remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") local_pwd = params.get("local_pwd", "LOCAL.EXAMPLE.COM") paused_after_start_vm = "yes" == params.get("paused_after_start_vm", "no") destroy_readonly = "yes" == params.get("destroy_readonly", "no") if vm_ref == "remote" and (remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM")): test.cancel("Remote test parameters unchanged from default") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' if not libvirt_version.version_compare(1, 1, 1): if params.get('setup_libvirt_polkit') == 'yes': test.cancel("API acl test not supported in current" " libvirt version.") 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("destroy_extra")) elif vm_ref == "uuid": vm_ref = domuuid if libvirtd == "off": utils_libvirtd.libvirtd_stop() if vm_ref != "remote": if paused_after_start_vm: virsh.suspend(vm_ref) if not vm.is_paused(): test.fail("VM suspend failed") status = virsh.destroy(vm_ref, ignore_status=True, unprivileged_user=unprivileged_user, uri=uri, debug=True).exit_status output = "" else: 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') # Setup up remote to remote login in local host ssh_key.setup_remote_ssh_key(remote_ip, "root", remote_pwd, local_ip, "root", local_pwd) command = "virsh -c %s destroy %s" % (remote_uri, vm_name) status, output = session.cmd_status_output(command, internal_timeout=5) session.close() except process.CmdError: status = 1 if libvirtd == "off": utils_libvirtd.libvirtd_start() # Test the read_only mode if destroy_readonly: result = virsh.destroy(vm_ref, ignore_status=True, debug=True, readonly=True) libvirt.check_exit_status(result, expect_error=True) # This is for status_error check status = result.exit_status # check status_error if status_error == "yes": if status == 0: test.fail("Run successfully with wrong command! " "Output:\n%s" % output) elif status_error == "no": if status != 0: test.fail("Run failed with right command! Output:\n%s" % output)
def run_virsh_setmem(test, params, env): """ Test command: virsh setmem. 1) Prepare vm environment. 2) Handle params 3) Prepare libvirtd status. 4) Run test command and wait for current memory's stable. 5) Recover environment. 4) Check result. TODO: support new libvirt with more options. """ def vm_proc_meminfo(session): proc_meminfo = session.cmd_output("cat /proc/meminfo") # verify format and units are expected return int(re.search(r"MemTotal:\s+(\d+)\s+kB", proc_meminfo).group(1)) def make_domref(domarg, vm_ref, domid, vm_name, domuuid): # Specify domain as argument or parameter if domarg == "yes": dom_darg_key = "domainarg" else: dom_darg_key = "domain" # How to reference domain if vm_ref == "domid": dom_darg_value = domid elif vm_ref == "domname": dom_darg_value = vm_name elif vm_ref == "domuuid": dom_darg_value = domuuid elif vm_ref == "none": dom_darg_value = None elif vm_ref == "emptystring": dom_darg_value = '""' else: # stick in value directly dom_darg_value = vm_ref return {dom_darg_key: dom_darg_value} def make_sizeref(sizearg, mem_ref, original_mem): if sizearg == "yes": size_darg_key = "sizearg" else: size_darg_key = "size" if mem_ref == "halfless": size_darg_value = "%d" % (original_mem / 2) elif mem_ref == "halfmore": size_darg_value = "%d" % int(original_mem * 1.5) # no fraction elif mem_ref == "same": size_darg_value = "%d" % original_mem elif mem_ref == "emptystring": size_darg_value = '""' elif mem_ref == "zero": size_darg_value = "0" elif mem_ref == "toosmall": size_darg_value = "1024" elif mem_ref == "toobig": size_darg_value = "1099511627776" # (KiB) One Petabyte elif mem_ref == "none": size_darg_value = None else: # stick in value directly size_darg_value = mem_ref return {size_darg_key: size_darg_value} def is_in_range(actual, expected, error_percent): deviation = 100 - (100 * (float(actual) / float(expected))) logging.debug("Deviation: %0.2f%%" % float(deviation)) return float(deviation) <= float(error_percent) def is_old_libvirt(): regex = r"\s+\[--size\]\s+" return bool(not virsh.has_command_help_match("setmem", regex)) def print_debug_stats( original_inside_mem, original_outside_mem, test_inside_mem, test_outside_mem, expected_mem, delta_percentage ): dbgmsg = ( "Original inside mem : %d KiB\n" "Expected inside mem : %d KiB\n" "Actual inside mem : %d KiB\n" "Inside mem deviation : %0.2f%%\n" "Original outside mem : %d KiB\n" "Expected outside mem : %d KiB\n" "Actual outside mem : %d KiB\n" "Outside mem deviation: %0.2f%%\n" "Acceptable deviation %0.2f%%" % ( original_inside_mem, expected_mem, test_inside_mem, 100 - (100 * (float(test_inside_mem) / float(expected_mem))), original_outside_mem, expected_mem, test_outside_mem, 100 - (100 * (float(test_outside_mem) / float(expected_mem))), float(delta_percentage), ) ) for dbgline in dbgmsg.splitlines(): logging.debug(dbgline) # MAIN TEST CODE ### # Process cartesian parameters vm_ref = params.get("setmem_vm_ref", "") mem_ref = params.get("setmem_mem_ref", "") flags = params.get("setmem_flags", "") status_error = params.get("status_error", "no") old_libvirt_fail = params.get("setmem_old_libvirt_fail", "no") quiesce_delay = int(params.get("setmem_quiesce_delay", "1")) domarg = params.get("setmem_domarg", "no") sizearg = params.get("setmem_sizearg", "no") libvirt = params.get("libvirt", "on") delta_percentage = float(params.get("setmem_delta_per", "10")) start_vm = params.get("start_vm", "yes") vm_name = params.get("main_vm") paused_after_start_vm = "yes" == params.get("paused_after_start_vm", "no") # Gather environment parameters vm = env.get_vm(params["main_vm"]) if start_vm == "yes": if paused_after_start_vm: vm.resume() session = vm.wait_for_login() original_inside_mem = vm_proc_meminfo(session) session.close() if paused_after_start_vm: vm.pause() else: session = None # Retrieve known mem value, convert into kilobytes original_inside_mem = int(params.get("mem", "1024")) * 1024 original_outside_mem = vm.get_used_mem() domid = vm.get_id() domuuid = vm.get_uuid() uri = vm.connect_uri old_libvirt = is_old_libvirt() if old_libvirt: logging.info("Running test on older libvirt") use_kilobytes = True else: logging.info("Running test on newer libvirt") use_kilobytes = False # Argument pattern is complex, build with dargs dargs = {"flagstr": flags, "use_kilobytes": use_kilobytes, "uri": uri, "ignore_status": True, "debug": True} dargs.update(make_domref(domarg, vm_ref, domid, vm_name, domuuid)) dargs.update(make_sizeref(sizearg, mem_ref, original_outside_mem)) # Prepare libvirtd status if libvirt == "off": utils_libvirtd.libvirtd_stop() else: # make sure it's running utils_libvirtd.libvirtd_restart() if status_error == "yes" or old_libvirt_fail == "yes": logging.info("Error Test: Expecting an error to occur!") result = virsh.setmem(**dargs) status = result.exit_status # Recover libvirtd status if libvirt == "off": utils_libvirtd.libvirtd_start() if status is 0: logging.info("Waiting %d seconds for VM memory to settle", quiesce_delay) # It takes time for kernel to settle on new memory # and current clean pages is not predictable. Therefor, # extremely difficult to determine quiescence, so # sleep one second per error percent is reasonable option. time.sleep(quiesce_delay) # Gather stats if not running error test if status_error == "no" and old_libvirt_fail == "no": if vm.state() == "shut off": vm.start() # Make sure it's never paused vm.resume() session = vm.wait_for_login() # Actual results test_inside_mem = vm_proc_meminfo(session) session.close() test_outside_mem = vm.get_used_mem() # Expected results for both inside and outside if sizearg == "yes": expected_mem = int(dargs["sizearg"]) else: expected_mem = int(dargs["size"]) print_debug_stats( original_inside_mem, original_outside_mem, test_inside_mem, test_outside_mem, expected_mem, delta_percentage ) if status is 0: # Restore original memory restore_status = virsh.setmem(domainarg=vm_name, sizearg=original_outside_mem, ignore_status=True).exit_status if restore_status is not 0: logging.warning("Failed to restore VM's original memory to %s KiB" % original_outside_mem) else: # virsh setmem failed, no need to restore pass # Don't care about memory comparison on error test if status_error == "no" and old_libvirt_fail == "no": outside_in_range = is_in_range(test_outside_mem, expected_mem, delta_percentage) inside_in_range = is_in_range(test_inside_mem, expected_mem, delta_percentage) if status is not 0 or not outside_in_range or not inside_in_range: msg = "test conditions not met: " if status is not 0: msg += "Non-zero virsh setmem exit code. " # maybe multiple if not outside_in_range: # errors msg += "Outside memory deviated. " if not inside_in_range: msg += "Inside memory deviated. " raise error.TestFail(msg) return # Normal test passed elif status_error == "no" and old_libvirt_fail == "yes": if status is 0: if old_libvirt: raise error.TestFail("Error test did not result in an error") else: if not old_libvirt: raise error.TestFail("Newer libvirt failed when it should not") else: # Verify an error test resulted in error if status is 0: raise error.TestFail("Error test did not result in an error")
def run_virsh_list(test, params, env): """ Test command: virsh list. 1) Filt parameters according libvirtd's version 2) Prepare domain's exist state:transient,managed-save. 3) Prepare libvirt's status. 4) Execute list command. 5) Result check. """ def list_local_domains_on_remote(options_ref, remote_ip, remote_passwd, local_ip): """ Create a virsh list command and execute it on remote host. It will list local domains on remote host. :param options_ref:options in virsh list command. :param remote_ip:remote host's ip. :param remote_passwd:remote host's password. :param local_ip:local ip, to create uri in virsh list. :return:return status and output of the virsh list command. """ complete_uri = libvirt_vm.complete_uri(local_ip) command_on_remote = "virsh -c %s list %s" % (complete_uri, options_ref) session = remote.remote_login("ssh", remote_ip, "22", "root", remote_passwd, "#") time.sleep(5) status, output = session.cmd_status_output(command_on_remote, internal_timeout=5) time.sleep(5) session.close() return int(status), output vm_name = params.get("main_vm") vm = env.get_vm(vm_name) options_ref = params.get("list_options_ref", "") list_ref = params.get("list_type_ref", "") vm_ref = params.get("vm_ref", "") # Some parameters are not supported on old libvirt, skip them. help_info = virsh.command("help list").stdout.strip() if vm_ref and not re.search(vm_ref, help_info): raise error.TestNAError("This version do not support vm type:%s" % vm_ref) if list_ref and not re.search(list_ref, help_info): raise error.TestNAError("This version do not support list type:%s" % list_ref) status_error = params.get("status_error", "no") addition_status_error = params.get("addition_status_error", "no") domuuid = vm.get_uuid().strip() # If a transient domain is destroyed, it will disappear. if vm_ref == "transient" and options_ref == "inactive": logging.info("Set addition_status_error to yes") logging.info( "because transient domain will disappear after destroyed.") addition_status_error = "yes" if vm_ref == "transient": tmp_xml = vm.backup_xml() vm.undefine() elif vm_ref == "managed-save": virsh.managedsave(vm_name, ignore_status=True, print_info=True) # Prepare libvirtd status libvirtd = params.get("libvirtd", "on") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # run test case if list_ref == "--uuid": result_expected = domuuid logging.info("%s's uuid is: %s", vm_name, domuuid) else: result_expected = vm_name logging.info("domain's name is: %s", vm_name) if options_ref == "vm_id": domid = vm.get_id().strip() logging.info("%s's running-id is: %s", vm_name, domid) options_ref = "%s %s" % (domid, list_ref) elif options_ref == "vm_uuid": logging.info("%s's uuid is: %s", vm_name, domuuid) options_ref = "%s %s" % (domuuid, list_ref) elif options_ref == "inactive": vm.destroy() options_ref = "--inactive %s" % list_ref elif options_ref == "vm_name": options_ref = "%s %s" % (vm_name, list_ref) elif options_ref == "all": options_ref = "--all %s" % list_ref elif options_ref == "": options_ref = "%s" % list_ref remote_ref = params.get("remote_ref", "local") if remote_ref == "remote": remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_passwd = params.get("remote_passwd", None) local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"): raise error.TestNAError( "Remote test parameters unchanged from default") logging.info("Execute virsh command on remote host %s.", remote_ip) status, output = list_local_domains_on_remote(options_ref, remote_ip, remote_passwd, local_ip) logging.info("Status:%s", status) logging.info("Output:\n%s", output) else: if vm_ref: options_ref = "%s --%s" % (options_ref, vm_ref) result = virsh.dom_list(options_ref, ignore_status=True, print_info=True) status = result.exit_status output = result.stdout.strip() # Recover libvirtd service status if libvirtd == "off": utils_libvirtd.libvirtd_start() # Recover of domain if vm_ref == "transient": vm.define(tmp_xml) elif vm_ref == "managed-save": # Recover saved guest. virsh.managedsave_remove(vm_name, ignore_status=True, print_info=True) # Check result status_error = (status_error == "no") and (addition_status_error == "no") if vm_ref == "managed-save": saved_output = re.search(vm_name + "\s+saved", output) if saved_output: output = saved_output.group(0) else: output = "" if not status_error: if status == 0 and re.search(result_expected, output): raise error.TestFail("Run successful with wrong command!") else: if status != 0: raise error.TestFail("Run failed with right command.") if not re.search(result_expected, output): raise error.TestFail("Run successful but result is not expected.")
def run(test, params, env): """ Test command: virsh list. 1) Filt parameters according libvirtd's version 2) Prepare domain's exist state:transient,managed-save. 3) Prepare libvirt's status. 4) Execute list command. 5) Result check. """ def list_local_domains_on_remote(options_ref, remote_ip, remote_passwd, local_ip): """ Create a virsh list command and execute it on remote host. It will list local domains on remote host. :param options_ref:options in virsh list command. :param remote_ip:remote host's ip. :param remote_passwd:remote host's password. :param local_ip:local ip, to create uri in virsh list. :return:return status and output of the virsh list command. """ complete_uri = libvirt_vm.complete_uri(local_ip) command_on_remote = "virsh -c %s list %s" % (complete_uri, options_ref) session = remote.remote_login( "ssh", remote_ip, "22", "root", remote_passwd, "#") time.sleep(5) status, output = session.cmd_status_output( command_on_remote, internal_timeout=5) time.sleep(5) session.close() return int(status), output vm_name = params.get("main_vm") vm = env.get_vm(vm_name) options_ref = params.get("list_options_ref", "") list_ref = params.get("list_type_ref", "") vm_ref = params.get("vm_ref", "") # Some parameters are not supported on old libvirt, skip them. help_info = virsh.command("help list").stdout.strip() if vm_ref and not re.search(vm_ref, help_info): raise error.TestNAError("This version do not support vm type:%s" % vm_ref) if list_ref and not re.search(list_ref, help_info): raise error.TestNAError("This version do not support list type:%s" % list_ref) status_error = params.get("status_error", "no") addition_status_error = params.get("addition_status_error", "no") domuuid = vm.get_uuid().strip() # If a transient domain is destroyed, it will disappear. if vm_ref == "transient" and options_ref == "inactive": logging.info("Set addition_status_error to yes") logging.info( "because transient domain will disappear after destroyed.") addition_status_error = "yes" if vm_ref == "transient": tmp_xml = vm.backup_xml() vm.undefine() elif vm_ref == "managed-save": virsh.managedsave(vm_name, ignore_status=True, print_info=True) # Prepare libvirtd status libvirtd = params.get("libvirtd", "on") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # run test case if list_ref == "--uuid": result_expected = domuuid logging.info("%s's uuid is: %s", vm_name, domuuid) else: result_expected = vm_name logging.info("domain's name is: %s", vm_name) if options_ref == "vm_id": domid = vm.get_id().strip() logging.info("%s's running-id is: %s", vm_name, domid) options_ref = "%s %s" % (domid, list_ref) elif options_ref == "vm_uuid": logging.info("%s's uuid is: %s", vm_name, domuuid) options_ref = "%s %s" % (domuuid, list_ref) elif options_ref == "inactive": vm.destroy() options_ref = "--inactive %s" % list_ref elif options_ref == "vm_name": options_ref = "%s %s" % (vm_name, list_ref) elif options_ref == "all": options_ref = "--all %s" % list_ref elif options_ref == "": options_ref = "%s" % list_ref remote_ref = params.get("remote_ref", "local") if remote_ref == "remote": remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"): raise error.TestNAError( "Remote test parameters unchanged from default") logging.info("Execute virsh command on remote host %s.", remote_ip) status, output = list_local_domains_on_remote( options_ref, remote_ip, remote_pwd, local_ip) logging.info("Status:%s", status) logging.info("Output:\n%s", output) else: if vm_ref: options_ref = "%s --%s" % (options_ref, vm_ref) result = virsh.dom_list( options_ref, ignore_status=True, print_info=True) status = result.exit_status output = result.stdout.strip() # Recover libvirtd service status if libvirtd == "off": utils_libvirtd.libvirtd_start() # Recover of domain if vm_ref == "transient": vm.define(tmp_xml) elif vm_ref == "managed-save": # Recover saved guest. virsh.managedsave_remove(vm_name, ignore_status=True, print_info=True) # Check result status_error = (status_error == "no") and (addition_status_error == "no") if vm_ref == "managed-save": saved_output = re.search(vm_name + "\s+saved", output) if saved_output: output = saved_output.group(0) else: output = "" if not status_error: if status == 0 and re.search(result_expected, output): raise error.TestFail("Run successful with wrong command!") else: if status != 0: raise error.TestFail("Run failed with right command.") if not re.search(result_expected, output): raise error.TestFail("Run successful but result is not expected.")
def run(test, params, env): """ Test command: virsh restore. Restore a domain from a saved state in a file 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Run virsh restore command with assigned option. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) session = vm.wait_for_login() os_type = params.get("os_type") status_error = ("yes" == params.get("status_error")) libvirtd = params.get("libvirtd", "on") extra_param = params.get("restore_extra_param") pre_status = params.get("restore_pre_status") vm_ref = params.get("restore_vm_ref") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' if not libvirt_version.version_compare(1, 1, 1): if params.get('setup_libvirt_polkit') == 'yes': test.cancel("API acl test not supported in current" " libvirt version.") # run test if vm_ref == "" or vm_ref == "xyz": status = virsh.restore(vm_ref, extra_param, debug=True, unprivileged_user=unprivileged_user, uri=uri, ignore_status=True).exit_status else: if os_type == "linux": cmd = "cat /proc/cpuinfo" try: status, output = session.cmd_status_output(cmd, timeout=10) finally: session.close() if not re.search("processor", output): test.fail("Unable to read /proc/cpuinfo") tmp_file = os.path.join(test.tmpdir, "save.file") virsh.save(vm_name, tmp_file) if vm_ref == "saved_file": vm_ref = tmp_file elif vm_ref == "empty_new_file": tmp_file = os.path.join(test.tmpdir, "new.file") with open(tmp_file, 'w') as tmp: pass vm_ref = tmp_file if vm.is_alive(): vm.destroy() if pre_status == "start": virsh.start(vm_name) if libvirtd == "off": utils_libvirtd.libvirtd_stop() status = virsh.restore(vm_ref, extra_param, debug=True, unprivileged_user=unprivileged_user, uri=uri, ignore_status=True).exit_status if not status_error: list_output = virsh.dom_list().stdout.strip() session.close() # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() try: if status_error: if not status: test.fail("Run successfully with wrong command!") else: if status: test.fail("Run failed with right command") if not re.search(vm_name, list_output): test.fail("Run failed with right command") if extra_param.count("paused"): if not vm.is_paused(): test.fail("Guest state should be" " paused after restore" " due to the option --paused") if extra_param.count("running"): if vm.is_dead() or vm.is_paused(): test.fail("Guest state should be" " running after restore" " due to the option --running") finally: if vm.is_paused(): virsh.resume(vm_name)
def run(test, params, env): """ Test the command virsh nodeinfo (1) Call virsh nodeinfo (2) Call virsh nodeinfo with an unexpected option (3) Call virsh nodeinfo with libvirtd service stop """ def _check_nodeinfo(nodeinfo_output, verify_str, column): cmd = "echo \"%s\" | grep \"%s\" | awk '{print $%s}'" % ( nodeinfo_output, verify_str, column) cmd_result = utils.run(cmd, ignore_status=True) stdout = cmd_result.stdout.strip() logging.debug("Info %s on nodeinfo output:%s" % (verify_str, stdout)) return stdout def output_check(nodeinfo_output): # Check CPU model cpu_model_nodeinfo = _check_nodeinfo(nodeinfo_output, "CPU model", 3) cpu_model_os = utils.get_current_kernel_arch() if not re.match(cpu_model_nodeinfo, cpu_model_os): raise error.TestFail( "Virsh nodeinfo output didn't match CPU model") # Check number of CPUs, nodeinfo CPUs represent online threads in the # system, check all online cpus in sysfs cpus_nodeinfo = _check_nodeinfo(nodeinfo_output, "CPU(s)", 2) cmd = "cat /sys/devices/system/cpu/cpu*/online | grep 1 | wc -l" cpus_online = utils.run(cmd, ignore_status=True).stdout.strip() cmd = "cat /sys/devices/system/cpu/cpu*/online | wc -l" cpus_total = utils.run(cmd, ignore_status=True).stdout.strip() if not os.path.exists('/sys/devices/system/cpu/cpu0/online'): cpus_online = str(int(cpus_online) + 1) cpus_total = str(int(cpus_total) + 1) logging.debug("host online cpus are %s", cpus_online) logging.debug("host total cpus are %s", cpus_total) if cpus_nodeinfo != cpus_online: if 'power' in cpu_util.get_cpu_arch(): if cpus_nodeinfo != cpus_total: raise error.TestFail("Virsh nodeinfo output of CPU(s) on" " ppc did not match all threads in " "the system") else: raise error.TestFail("Virsh nodeinfo output didn't match " "number of CPU(s)") # Check CPU frequency, frequency is under clock for ppc cpu_frequency_nodeinfo = _check_nodeinfo( nodeinfo_output, 'CPU frequency', 3) cmd = ("cat /proc/cpuinfo | grep -E 'cpu MHz|clock' | head -n1 | " "awk -F: '{print $2}' | awk -F. '{print $1}'") cmd_result = utils.run(cmd, ignore_status=True) cpu_frequency_os = cmd_result.stdout.strip() logging.debug("cpu_frequency_nodeinfo=%s cpu_frequency_os=%s", cpu_frequency_nodeinfo, cpu_frequency_os) # # Matching CPU Frequency is not an exact science in todays modern # processors and OS's. CPU's can have their execution speed varied # based on current workload in order to save energy and keep cool. # Thus since we're getting the values at disparate points in time, # we cannot necessarily do a pure comparison. # So, let's get the absolute value of the difference and ensure # that it's within 20 percent of each value to give us enough of # a "fudge" factor to declare "close enough". Don't return a failure # just print a debug message and move on. diffval = abs(int(cpu_frequency_nodeinfo) - int(cpu_frequency_os)) if float(diffval) / float(cpu_frequency_nodeinfo) > 0.20 or \ float(diffval) / float(cpu_frequency_os) > 0.20: logging.debug("Virsh nodeinfo output didn't match CPU " "frequency within 20 percent") # Get CPU topology from virsh capabilities xml cpu_topology = capability_xml.CapabilityXML()['cpu_topology'] logging.debug("Cpu topology in virsh capabilities output: %s", cpu_topology) # Check CPU socket(s) cpu_sockets_nodeinfo = int( _check_nodeinfo(nodeinfo_output, 'CPU socket(s)', 3)) # CPU socket(s) in virsh nodeinfo is Total sockets in each node, not # total sockets in the system, so get total sockets in one node and # check with it node_info = utils_misc.NumaInfo() node_online_list = node_info.get_online_nodes() cmd = "cat /sys/devices/system/node/node%s" % node_online_list[0] cmd += "/cpu*/topology/physical_package_id | uniq |wc -l" cmd_result = utils.run(cmd, ignore_status=True) total_sockets_in_node = int(cmd_result.stdout.strip()) if total_sockets_in_node != cpu_sockets_nodeinfo: raise error.TestFail("Virsh nodeinfo output didn't match CPU " "socket(s) of host OS") if cpu_sockets_nodeinfo != int(cpu_topology['sockets']): raise error.TestFail("Virsh nodeinfo output didn't match CPU " "socket(s) of virsh capabilities output") # Check Core(s) per socket cores_per_socket_nodeinfo = _check_nodeinfo( nodeinfo_output, 'Core(s) per socket', 4) cmd = "lscpu | grep 'Core(s) per socket' | head -n1 | awk '{print $4}'" cmd_result = utils.run(cmd, ignore_status=True) cores_per_socket_os = cmd_result.stdout.strip() if not re.match(cores_per_socket_nodeinfo, cores_per_socket_os): raise error.TestFail("Virsh nodeinfo output didn't match Core(s) " "per socket of host OS") if cores_per_socket_nodeinfo != cpu_topology['cores']: raise error.TestFail("Virsh nodeinfo output didn't match Core(s) " "per socket of virsh capabilities output") # Ckeck Thread(s) per core threads_per_core_nodeinfo = _check_nodeinfo(nodeinfo_output, 'Thread(s) per core', 4) if threads_per_core_nodeinfo != cpu_topology['threads']: raise error.TestFail("Virsh nodeinfo output didn't match Thread(s) " "per core of virsh capabilities output") # Check Memory size memory_size_nodeinfo = int( _check_nodeinfo(nodeinfo_output, 'Memory size', 3)) memory_size_os = 0 for i in node_online_list: node_memory = node_info.read_from_node_meminfo(i, 'MemTotal') memory_size_os += int(node_memory) logging.debug('The host total memory from nodes is %s', memory_size_os) if memory_size_nodeinfo != memory_size_os: raise error.TestFail("Virsh nodeinfo output didn't match " "Memory size") # Prepare libvirtd service check_libvirtd = params.has_key("libvirtd") if check_libvirtd: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_node_options") cmd_result = virsh.nodeinfo(ignore_status=True, extra=option) logging.info("Output:\n%s", cmd_result.stdout.strip()) logging.info("Status: %d", cmd_result.exit_status) logging.error("Error: %s", cmd_result.stderr.strip()) output = cmd_result.stdout.strip() status = cmd_result.exit_status # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off": raise error.TestFail("Command 'virsh nodeinfo' succeeded " "with libvirtd service stopped, incorrect") else: raise error.TestFail("Command 'virsh nodeinfo %s' succeeded" "(incorrect command)" % option) elif status_error == "no": output_check(output) if status != 0: raise error.TestFail("Command 'virsh nodeinfo %s' failed " "(correct command)" % option)
def run(test, params, env): """ Test the command virsh capabilities (1) Call virsh capabilities (2) Call virsh capabilities with an unexpected option (3) Call virsh capabilities with libvirtd service stop """ def compare_capabilities_xml(source): cap_xml = capability_xml.CapabilityXML() cap_xml.xml = source # Check that host has a non-empty UUID tag. xml_uuid = cap_xml.uuid logging.debug("Host UUID (capabilities_xml): %s" % xml_uuid) if xml_uuid == "": raise error.TestFail("The host uuid in capabilities_xml is none!") # Check the host arch. xml_arch = cap_xml.arch logging.debug("Host arch (capabilities_xml): %s", xml_arch) exp_arch = process.run("arch", shell=True).stdout.strip() if cmp(xml_arch, exp_arch) != 0: raise error.TestFail( "The host arch in capabilities_xml is expected" " to be %s, but get %s" % (exp_arch, xml_arch)) # Check the host cpu count. xml_cpu_count = cap_xml.cpu_count logging.debug("Host cpus count (capabilities_xml): %s", xml_cpu_count) cmd = "grep processor /proc/cpuinfo | wc -l" exp_cpu_count = int(process.run(cmd, shell=True).stdout.strip()) if xml_cpu_count != exp_cpu_count: raise error.TestFail( "Host cpus count is expected to be %s, but get " "%s" % (exp_cpu_count, xml_cpu_count)) # Check the arch of guest supported. guest_capa = cap_xml.get_guest_capabilities() logging.debug(guest_capa) try: img = utils_path.find_command("qemu-kvm") except utils_path.CmdNotFoundError: raise error.TestNAError("Cannot find qemu-kvm") if re.search("ppc", process.run("arch", shell=True).stdout): cmd = img + " --cpu ? | grep ppc" else: cmd = img + " --cpu ? | grep qemu" cmd_result = process.run(cmd, shell=True) for guest in cap_xml.xmltreefile.findall('guest'): guest_wordsize = guest.find('arch').find('wordsize').text logging.debug("Arch of guest supported (capabilities_xml):%s", guest_wordsize) if not re.search(guest_wordsize, cmd_result.stdout.strip()): raise error.TestFail( "The capabilities_xml gives an extra arch " "of guest to support!") # Check the type of hypervisor. first_guest = cap_xml.xmltreefile.findall('guest')[0] first_domain = first_guest.find('arch').findall('domain')[0] guest_domain_type = first_domain.get('type') logging.debug("Hypervisor (capabilities_xml):%s", guest_domain_type) cmd_result = process.run("virsh uri", shell=True) if not re.search(guest_domain_type, cmd_result.stdout.strip()): raise error.TestFail("The capabilities_xml gives an different " "hypervisor") # check power management support. try: pm_cmd = os_dep.command('pm-is-supported') pm_cap_map = { 'suspend': 'suspend_mem', 'hibernate': 'suspend_disk', 'suspend-hybrid': 'suspend_hybrid', } exp_pms = [] for opt in pm_cap_map: cmd = '%s --%s' % (pm_cmd, opt) res = process.run(cmd, ignore_status=True, shell=True) if res.exit_status == 0: exp_pms.append(pm_cap_map[opt]) pms = cap_xml.power_management_list if set(exp_pms) != set(pms): raise error.TestFail("Expected supported PMs are %s, got %s " "instead." % (exp_pms, pms)) except ValueError: logging.debug( 'Power management checking is skipped, since command ' 'pm-is-supported is not found.') connect_uri = libvirt_vm.normalize_connect_uri( params.get("connect_uri", "default")) # Prepare libvirtd service if "libvirtd" in params: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_cap_options") try: output = virsh.capabilities(option, uri=connect_uri, ignore_status=False, debug=True) status = 0 # good except process.CmdError: status = 1 # bad output = '' # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off": raise error.TestFail( "Command 'virsh capabilities' succeeded " "with libvirtd service stopped, incorrect") else: raise error.TestFail( "Command 'virsh capabilities %s' succeeded " "(incorrect command)" % option) elif status_error == "no": compare_capabilities_xml(output) if status != 0: raise error.TestFail("Command 'virsh capabilities %s' failed " "(correct command)" % option)
def run(test, params, env): """ Test command: virsh domifstat. The command can get network interface stats for a running domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh domifstat operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) def get_interface(guest_name): """ Get interface device of VM. :param guest_name: VM's name. :return: interface device of VM. """ interface = "" domxml = utils.system_output("virsh dumpxml %s" % guest_name) dom = parseString(domxml) root = dom.documentElement array = root.getElementsByTagName("interface") for element in array: if element.getAttribute("type") == "bridge" or \ element.getAttribute("type") == "network": interface = "vnet0" nodelist = element.childNodes for node in nodelist: if node.nodeName == "target": interface = node.getAttribute("dev") break return interface domid = vm.get_id() domuuid = vm.get_uuid() vm_ref = params.get("domifstat_vm_ref", vm_name) nic_ref = params.get("domifstat_nic_ref", "") libvirtd = params.get("libvirtd", "on") status_error = params.get("status_error", "no") 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 == "uuid": vm_ref = domuuid elif vm_ref == "name": vm_ref = vm_name interface = get_interface(vm_name) if nic_ref == "": interface = "" elif nic_ref == "error_interface": interface = params.get(nic_ref) interface = "%s %s" % (interface, params.get("domifstat_extra")) if libvirtd == "off": utils_libvirtd.libvirtd_stop() status = virsh.domifstat(vm_ref, interface, ignore_status=True).exit_status # recover libvirtd service start if libvirtd == "off": utils_libvirtd.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: raise error.TestFail("Run failed with right command")
def run_virt_edit(test, params, env): """ Test of virt-edit. 1) Get and init parameters for test. 2) Prepare environment. 3) Run virt-edit command and get result. 5) Recover environment. 6) Check result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) uri = libvirt_vm.normalize_connect_uri( params.get("connect_uri", "default")) start_vm = params.get("start_vm", "no") vm_ref = params.get("virt_edit_vm_ref", vm_name) file_ref = params.get("virt_edit_file_ref", "/etc/hosts") created_img = params.get("virt_edit_created_img", "/tmp/foo.img") foo_line = params.get("foo_line", "") options = params.get("virt_edit_options") options_suffix = params.get("virt_edit_options_suffix") status_error = params.get("status_error", "no") # virt-edit should not be used when vm is running. # (for normal test) if vm.is_alive() and start_vm == "no": vm.destroy(gracefully=True) dom_disk_dict = vm.get_disk_devices() # TODO dom_uuid = vm.get_uuid() if vm_ref == "domdisk": if len(dom_disk_dict) != 1: raise error.TestError("Only one disk device should exist on " "%s:\n%s." % (vm_name, dom_disk_dict)) disk_detail = dom_disk_dict.values()[0] vm_ref = disk_detail['source'] logging.info("disk to be edit:%s", vm_ref) elif vm_ref == "domname": vm_ref = vm_name elif vm_ref == "domuuid": vm_ref = dom_uuid elif vm_ref == "createdimg": vm_ref = created_img utils.run("dd if=/dev/zero of=%s bs=256M count=1" % created_img) # Decide whether pass a exprt for virt-edit command. if foo_line != "": expr = "s/$/%s/" % foo_line else: expr = "" # Stop libvirtd if test need. libvirtd = params.get("libvirtd", "on") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test virsh_dargs = {'ignore_status': True, 'debug': True, 'uri': uri} result = lgf.virt_edit_cmd(vm_ref, file_ref, options, options_suffix, expr, **virsh_dargs) status = result.exit_status # Recover libvirtd. if libvirtd == "off": utils_libvirtd.libvirtd_start() utils.run("rm -f %s" % created_img) status_error = (status_error == "yes") if status != 0: if not status_error: raise error.TestFail("Command executed failed.") else: if (expr != "" and (not login_to_check_foo_line(vm, file_ref, foo_line))): raise error.TestFail("Virt-edit to add %s in %s failed." "Test failed." % (foo_line, file_ref))
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. """ def boot_time(): session = vm.wait_for_login() boot_time = session.cmd_output("uptime --since") session.close() return boot_time 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") local_pwd = params.get("local_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") wait_time = int(params.get('wait_time', 5)) 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) # Setup ssh connection ssh_connection = utils_conn.SSHConnection(server_ip=local_ip, server_pwd=local_pwd, client_ip=remote_ip, client_pwd=remote_pwd) try: ssh_connection.conn_check() except utils_conn.ConnectionError: ssh_connection.conn_setup() ssh_connection.conn_check() 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": if not status_error: # Not need to check the boot up time if it is a negative test first_boot_time = boot_time() 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 # avoid the check if it is negative test if not status_error: cmdoutput = '' def _wait_for_reboot_up(): second_boot_time = boot_time() is_rebooted = second_boot_time > first_boot_time cmdoutput = virsh.domstate(vm_ref, '--reason', ignore_status=True, debug=True) domstate_status = cmdoutput.exit_status output = "running" in cmdoutput.stdout return not domstate_status and output and is_rebooted if not wait.wait_for( _wait_for_reboot_up, timeout=wait_time, step=1): 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() # Test the readonly mode if reboot_readonly: result = virsh.reboot(vm_ref, ignore_status=True, debug=True, readonly=True) libvirt.check_exit_status(result, expect_error=True) # This is for status_error check status = result.exit_status # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error: if not status: test.fail("Run successfully with wrong command!") else: if status or (not re.search(vm_name, output)): if status == -2: test.cancel("Reboot command doesn't work on older libvirt " "versions") test.fail("Run failed with right command") finally: xml_backup.sync() if 'ssh_connection' in locals(): ssh_connection.auto_recover = True
def run_virsh_capabilities(test, params, env): """ Test the command virsh capabilities (1) Call virsh capabilities (2) Call virsh capabilities with an unexpected option (3) Call virsh capabilities with libvirtd service stop """ def compare_capabilities_xml(source): dom = parseString(source) host = dom.getElementsByTagName('host')[0] # check that host has a non-empty UUID tag. uuid = host.getElementsByTagName('uuid')[0] host_uuid_output = uuid.firstChild.data logging.info("Host uuid (capabilities_xml):%s", host_uuid_output) if host_uuid_output == "": raise error.TestFail("The host uuid in capabilities_xml is none!") # check the host arch. arch = host.getElementsByTagName('arch')[0] host_arch_output = arch.firstChild.data logging.info("Host arch (capabilities_xml):%s", host_arch_output) cmd_result = utils.run("arch", ignore_status=True) if cmp(host_arch_output, cmd_result.stdout.strip()) != 0: raise error.TestFail("The host arch in capabilities_xml is wrong!") # check the host cpus num. cpus = dom.getElementsByTagName('cpus')[0] host_cpus_output = cpus.getAttribute('num') logging.info("Host cpus num (capabilities_xml):%s", host_cpus_output) cmd = "less /proc/cpuinfo | grep processor | wc -l" cmd_result = utils.run(cmd, ignore_status=True) if cmp(host_cpus_output, cmd_result.stdout.strip()) != 0: raise error.TestFail("Host cpus num (capabilities_xml) is " "wrong") # check the arch of guest supported. cmd = "/usr/libexec/qemu-kvm --cpu ? | grep qemu" cmd_result = utils.run(cmd, ignore_status=True) guest_wordsize_array = dom.getElementsByTagName('wordsize') length = len(guest_wordsize_array) for i in range(length): element = guest_wordsize_array[i] guest_wordsize = element.firstChild.data logging.info("Arch of guest supported (capabilities_xml):%s", guest_wordsize) if not re.search(guest_wordsize, cmd_result.stdout.strip()): raise error.TestFail("The capabilities_xml gives an extra arch " "of guest to support!") # check the type of hyperviosr. guest_domain_type = dom.getElementsByTagName('domain')[0] guest_domain_type_output = guest_domain_type.getAttribute('type') logging.info("Hypervisor (capabilities_xml):%s", guest_domain_type_output) cmd_result = utils.run("virsh uri", ignore_status=True) if not re.search(guest_domain_type_output, cmd_result.stdout.strip()): raise error.TestFail("The capabilities_xml gives an different " "hypervisor") connect_uri = libvirt_vm.normalize_connect_uri( params.get("connect_uri", "default") ) # Prepare libvirtd service if params.has_key("libvirtd"): libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_cap_options") try: output = virsh.capabilities(option, uri=connect_uri, ignore_status=False, debug=True) status = 0 # good except error.CmdError: status = 1 # bad output = '' # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off": raise error.TestFail("Command 'virsh capabilities' succeeded " "with libvirtd service stopped, incorrect") else: raise error.TestFail("Command 'virsh capabilities %s' succeeded " "(incorrect command)" % option) elif status_error == "no": compare_capabilities_xml(output) if status != 0: raise error.TestFail("Command 'virsh capabilities %s' failed " "(correct command)" % option)
def run_virsh_nodeinfo(test, params, env): """ Test the command virsh nodeinfo (1) Call virsh nodeinfo (2) Call virsh nodeinfo with an unexpected option (3) Call virsh nodeinfo with libvirtd service stop """ def _check_nodeinfo(nodeinfo_output, verify_str, column): cmd = "echo \"%s\" | grep \"%s\" | awk '{print $%s}'" % (nodeinfo_output, verify_str, column) cmd_result = utils.run(cmd, ignore_status=True) stdout = cmd_result.stdout.strip() logging.debug("Info %s on nodeinfo output:%s" % (verify_str, stdout)) return stdout def output_check(nodeinfo_output): # Check CPU model cpu_model_nodeinfo = _check_nodeinfo(nodeinfo_output, "CPU model", 3) cpu_model_os = utils.get_current_kernel_arch() if not re.match(cpu_model_nodeinfo, cpu_model_os): raise error.TestFail("Virsh nodeinfo output didn't match CPU model") # Check number of CPUs cpus_nodeinfo = _check_nodeinfo(nodeinfo_output, "CPU(s)", 2) cpus_os = utils.count_cpus() if int(cpus_nodeinfo) != cpus_os: raise error.TestFail("Virsh nodeinfo output didn't match number of " "CPU(s)") # Check CPU frequency cpu_frequency_nodeinfo = _check_nodeinfo(nodeinfo_output, 'CPU frequency', 3) cmd = ("cat /proc/cpuinfo | grep 'cpu MHz' | head -n1 | " "awk '{print $4}' | awk -F. '{print $1}'") cmd_result = utils.run(cmd, ignore_status=True) cpu_frequency_os = cmd_result.stdout.strip() print cpu_frequency_os if not re.match(cpu_frequency_nodeinfo, cpu_frequency_os): raise error.TestFail("Virsh nodeinfo output didn't match CPU " "frequency") # Check CPU socket(s) cpu_sockets_nodeinfo = int(_check_nodeinfo(nodeinfo_output, 'CPU socket(s)', 3)) cmd = "grep 'physical id' /proc/cpuinfo | uniq | sort | uniq |wc -l" cmd_result = utils.run(cmd, ignore_status=True) cpu_NUMA_nodeinfo = _check_nodeinfo(nodeinfo_output, 'NUMA cell(s)', 3) cpu_sockets_os = int(cmd_result.stdout.strip())/int(cpu_NUMA_nodeinfo) if cpu_sockets_os != cpu_sockets_nodeinfo: raise error.TestFail("Virsh nodeinfo output didn't match CPU " "socket(s)") # Check Core(s) per socket cores_per_socket_nodeinfo = _check_nodeinfo(nodeinfo_output, 'Core(s) per socket', 4) cmd = "grep 'cpu cores' /proc/cpuinfo | head -n1 | awk '{print $4}'" cmd_result = utils.run(cmd, ignore_status=True) cores_per_socket_os = cmd_result.stdout.strip() if not re.match(cores_per_socket_nodeinfo, cores_per_socket_os): raise error.TestFail("Virsh nodeinfo output didn't match Core(s) " "per socket") # Check Memory size memory_size_nodeinfo = int(_check_nodeinfo(nodeinfo_output, 'Memory size', 3)) memory_size_os = utils_memory.memtotal() if memory_size_nodeinfo != memory_size_os: raise error.TestFail("Virsh nodeinfo output didn't match " "Memory size") # Prepare libvirtd service check_libvirtd = params.has_key("libvirtd") if check_libvirtd: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_node_options") cmd_result = virsh.nodeinfo(ignore_status=True, extra=option) logging.info("Output:\n%s", cmd_result.stdout.strip()) logging.info("Status: %d", cmd_result.exit_status) logging.error("Error: %s", cmd_result.stderr.strip()) output = cmd_result.stdout.strip() status = cmd_result.exit_status # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off": raise error.TestFail("Command 'virsh nodeinfo' succeeded " "with libvirtd service stopped, incorrect") else: raise error.TestFail("Command 'virsh nodeinfo %s' succeeded" "(incorrect command)" % option) elif status_error == "no": output_check(output) if status != 0: raise error.TestFail("Command 'virsh nodeinfo %s' failed " "(correct command)" % option)
def run(test, params, env): """ Test command: virsh setmem. 1) Prepare vm environment. 2) Handle params 3) Prepare libvirtd status. 4) Run test command and wait for current memory's stable. 5) Recover environment. 4) Check result. TODO: support new libvirt with more options. """ def vm_proc_meminfo(session): proc_meminfo = session.cmd_output("cat /proc/meminfo") # verify format and units are expected return int(re.search(r'MemTotal:\s+(\d+)\s+kB', proc_meminfo).group(1)) def make_domref(domarg, vm_ref, domid, vm_name, domuuid): # Specify domain as argument or parameter if domarg == "yes": dom_darg_key = "domainarg" else: dom_darg_key = "domain" # How to reference domain if vm_ref == "domid": dom_darg_value = domid elif vm_ref == "domname": dom_darg_value = vm_name elif vm_ref == "domuuid": dom_darg_value = domuuid elif vm_ref == "none": dom_darg_value = None elif vm_ref == "emptystring": dom_darg_value = '""' else: # stick in value directly dom_darg_value = vm_ref return {dom_darg_key: dom_darg_value} def make_sizeref(sizearg, mem_ref, original_mem): if sizearg == "yes": size_darg_key = "sizearg" else: size_darg_key = "size" if mem_ref == "halfless": size_darg_value = "%d" % (original_mem / 2) elif mem_ref == "halfmore": size_darg_value = "%d" % int(original_mem * 1.5) # no fraction elif mem_ref == "same": size_darg_value = "%d" % original_mem elif mem_ref == "emptystring": size_darg_value = '""' elif mem_ref == "zero": size_darg_value = "0" elif mem_ref == "toosmall": size_darg_value = "1024" elif mem_ref == "toobig": size_darg_value = "1099511627776" # (KiB) One Petabyte elif mem_ref == "none": size_darg_value = None else: # stick in value directly size_darg_value = mem_ref return {size_darg_key: size_darg_value} def is_in_range(actual, expected, error_percent): deviation = 100 - (100 * (float(actual) / float(expected))) logging.debug("Deviation: %0.2f%%" % float(deviation)) return float(deviation) <= float(error_percent) def is_old_libvirt(): regex = r'\s+\[--size\]\s+' return bool(not virsh.has_command_help_match('setmem', regex)) def print_debug_stats(original_inside_mem, original_outside_mem, test_inside_mem, test_outside_mem, expected_mem, delta_percentage): dbgmsg = ("Original inside mem : %d KiB\n" "Expected inside mem : %d KiB\n" "Actual inside mem : %d KiB\n" "Inside mem deviation : %0.2f%%\n" "Original outside mem : %d KiB\n" "Expected outside mem : %d KiB\n" "Actual outside mem : %d KiB\n" "Outside mem deviation: %0.2f%%\n" "Acceptable deviation %0.2f%%" % (original_inside_mem, expected_mem, test_inside_mem, 100 - (100 * (float(test_inside_mem) / float(expected_mem))), original_outside_mem, expected_mem, test_outside_mem, 100 - (100 * (float(test_outside_mem) / float(expected_mem))), float(delta_percentage))) for dbgline in dbgmsg.splitlines(): logging.debug(dbgline) # MAIN TEST CODE ### # Process cartesian parameters vm_ref = params.get("setmem_vm_ref", "") mem_ref = params.get("setmem_mem_ref", "") flags = params.get("setmem_flags", "") status_error = params.get("status_error", "no") old_libvirt_fail = params.get("setmem_old_libvirt_fail", "no") quiesce_delay = int(params.get("setmem_quiesce_delay", "1")) domarg = params.get("setmem_domarg", "no") sizearg = params.get("setmem_sizearg", "no") libvirt = params.get("libvirt", "on") delta_percentage = float(params.get("setmem_delta_per", "10")) start_vm = params.get("start_vm", "yes") vm_name = params.get("main_vm") paused_after_start_vm = "yes" == params.get("paused_after_start_vm", "no") # Gather environment parameters vm = env.get_vm(params["main_vm"]) if start_vm == "yes": if paused_after_start_vm: vm.resume() session = vm.wait_for_login() original_inside_mem = vm_proc_meminfo(session) session.close() if paused_after_start_vm: vm.pause() else: session = None # Retrieve known mem value, convert into kilobytes original_inside_mem = int(params.get("mem", "1024")) * 1024 original_outside_mem = vm.get_used_mem() domid = vm.get_id() domuuid = vm.get_uuid() uri = vm.connect_uri old_libvirt = is_old_libvirt() if old_libvirt: logging.info("Running test on older libvirt") use_kilobytes = True else: logging.info("Running test on newer libvirt") use_kilobytes = False # Argument pattern is complex, build with dargs dargs = { 'flagstr': flags, 'use_kilobytes': use_kilobytes, 'uri': uri, 'ignore_status': True, "debug": True } dargs.update(make_domref(domarg, vm_ref, domid, vm_name, domuuid)) dargs.update(make_sizeref(sizearg, mem_ref, original_outside_mem)) # Prepare libvirtd status if libvirt == "off": utils_libvirtd.libvirtd_stop() else: if not utils_libvirtd.libvirtd_is_running() and \ not utils_libvirtd.libvirtd_start(): raise error.TestFail("Cannot start libvirtd") if status_error == "yes" or old_libvirt_fail == "yes": logging.info("Error Test: Expecting an error to occur!") result = virsh.setmem(**dargs) status = result.exit_status # Recover libvirtd status if libvirt == "off": utils_libvirtd.libvirtd_start() if status is 0: logging.info("Waiting %d seconds for VM memory to settle", quiesce_delay) # It takes time for kernel to settle on new memory # and current clean pages is not predictable. Therefor, # extremely difficult to determine quiescence, so # sleep one second per error percent is reasonable option. time.sleep(quiesce_delay) # Gather stats if not running error test if status_error == "no" and old_libvirt_fail == "no": if vm.state() == "shut off": vm.start() # Make sure it's never paused vm.resume() session = vm.wait_for_login() # Actual results test_inside_mem = vm_proc_meminfo(session) session.close() test_outside_mem = vm.get_used_mem() # Expected results for both inside and outside if sizearg == "yes": expected_mem = int(dargs["sizearg"]) else: expected_mem = int(dargs["size"]) print_debug_stats(original_inside_mem, original_outside_mem, test_inside_mem, test_outside_mem, expected_mem, delta_percentage) if status is 0: # Restore original memory restore_status = virsh.setmem(domainarg=vm_name, sizearg=original_outside_mem, ignore_status=True).exit_status if restore_status is not 0: logging.warning( "Failed to restore VM's original memory to %s KiB" % original_outside_mem) else: # virsh setmem failed, no need to restore pass # Don't care about memory comparison on error test if status_error == "no" and old_libvirt_fail == "no": outside_in_range = is_in_range(test_outside_mem, expected_mem, delta_percentage) inside_in_range = is_in_range(test_inside_mem, expected_mem, delta_percentage) if status is not 0 or not outside_in_range or not inside_in_range: msg = "test conditions not met: " if status is not 0: msg += "Non-zero virsh setmem exit code. " # maybe multiple if not outside_in_range: # errors msg += "Outside memory deviated. " if not inside_in_range: msg += "Inside memory deviated. " raise error.TestFail(msg) return # Normal test passed elif status_error == "no" and old_libvirt_fail == "yes": if status is 0: if old_libvirt: raise error.TestFail("Error test did not result in an error") else: if not old_libvirt: raise error.TestFail("Newer libvirt failed when it should not") else: # Verify an error test resulted in error if status is 0: raise error.TestFail("Error test did not result in an error")
def run_virsh_domblkstat(test, params, env): """ Test command: virsh domblkstat. The command get device block stats for a running domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh domblkstat operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) domid = vm.get_id() domuuid = vm.get_uuid() blklist = libvirt_xml.VMXML.get_disk_blk(vm_name) if blklist == None: raise error.TestFail("Cannot find disk in %s" % vm_name) #Select a block device from disks blk = blklist[0] libvirtd = params.get("libvirtd", "on") vm_ref = params.get("domblkstat_vm_ref") options = params.get("domblkstat_option", "") status_error = params.get("status_error", "no") if params.get("domblkinfo_dev") == "no": blk = "" if vm_ref == "id": vm_ref = domid 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 == "name": vm_ref = "%s %s" % (vm_name, params.get("domblkstat_extra")) option_list = options.split(" ") for option in option_list: if virsh.has_command_help_match("domblkstat", option) == None: status_error = "yes" break if libvirtd == "off": utils_libvirtd.libvirtd_stop() result = virsh.domblkstat(vm_ref, blk, options, ignore_status=True) status = result.exit_status output = result.stdout.strip() err = result.stderr.strip() #recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() #check status_error if status_error == "yes": if status == 0 or err == "": 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")
def run(test, params, env): """ Test command: virsh vcpuinfo. The command can get domain vcpu information 1.Prepare test environment. 2.When the ibvirtd == "off", stop the libvirtd service. 3.Perform virsh vcpuinfo operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) status_error = params.get("status_error", "no") libvirtd = params.get("libvirtd", "on") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # run test case vm_ref = params.get("vcpuinfo_vm_ref") domid = vm.get_id() domuuid = vm.get_uuid() def remote_case(params, vm_name): """ Test remote case. """ remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") local_pwd = params.get("local_pwd", None) # Used for connecting from remote to local connect_uri = params.get("remote_connect_uri", "qemu+ssh://LOCAL.EXAMPLE.COM/system") # Verify connect_uri/remote_ip/local_ip is useful for this test. if ("EXAMPLE" in remote_ip or "EXAMPLE" in connect_uri or "EXAMPLE" in local_ip): test.cancel("Please set remote_ip or connect_uri or local_ip.") status = 0 output = "" err = "" try: ssh_key.setup_remote_ssh_key(remote_ip, "root", remote_pwd, local_ip, "root", local_pwd) vcback = virsh.VirshConnectBack(remote_ip=remote_ip, remote_pwd=remote_pwd, uri=connect_uri, debug=True, ignore_status=True) cmdresult = vcback.vcpuinfo(vm_name) status = cmdresult.exit_status output = cmdresult.stdout.strip() vcback.close_session() if status != 0: err = output except process.CmdError: status = 1 output = "" err = "remote test failed" # Maintain result format conformance with local test return status, output, err 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 == "uuid": vm_ref = domuuid elif vm_ref == "name": vm_ref = "%s %s" % (vm_name, params.get("vcpuinfo_extra")) if vm_ref == "remote": # Keep status_error check conditions (below) simple status, output, err = remote_case(params, vm_name) else: result = virsh.vcpuinfo(vm_ref) status = result.exit_status output = result.stdout.strip() err = result.stderr.strip() # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error == "yes": if not status: if libvirtd == "off" and libvirt_version.version_compare(5, 6, 0): logging.debug( "From libvirt version 5.6.0 libvirtd is restarted " "and command should succeed") else: logging.debug(result) test.fail("Run successfully with wrong command!") # Check the error message in negative case. if not err and not libvirt_version.version_compare(5, 6, 0): logging.debug(result) logging.debug( "Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=889276 " "is helpful for tracing this bug.") test.fail("No error message for a command error!") elif status_error == "no": if status: logging.debug(result) test.fail("Run failed with right command")
def run(test, params, env): """ Test command: virsh restore. Restore a domain from a saved state in a file 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Run virsh restore command with assigned option. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) session = vm.wait_for_login() os_type = params.get("os_type") status_error = ("yes" == params.get("status_error")) libvirtd = params.get("libvirtd", "on") extra_param = params.get("restore_extra_param") pre_status = params.get("restore_pre_status") vm_ref = params.get("restore_vm_ref") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' if not libvirt_version.version_compare(1, 1, 1): if params.get('setup_libvirt_polkit') == 'yes': raise error.TestNAError("API acl test not supported in current" " libvirt version.") # run test if vm_ref == "" or vm_ref == "xyz": status = virsh.restore(vm_ref, extra_param, debug=True, unprivileged_user=unprivileged_user, uri=uri, ignore_status=True).exit_status else: if os_type == "linux": cmd = "cat /proc/cpuinfo" try: status, output = session.cmd_status_output(cmd, timeout=10) finally: session.close() if not re.search("processor", output): raise error.TestFail("Unable to read /proc/cpuinfo") tmp_file = os.path.join(test.tmpdir, "save.file") virsh.save(vm_name, tmp_file) if vm_ref == "saved_file": vm_ref = tmp_file elif vm_ref == "empty_new_file": tmp_file = os.path.join(test.tmpdir, "new.file") open(tmp_file, 'w').close() vm_ref = tmp_file if vm.is_alive(): vm.destroy() if pre_status == "start": virsh.start(vm_name) if libvirtd == "off": utils_libvirtd.libvirtd_stop() status = virsh.restore(vm_ref, extra_param, debug=True, unprivileged_user=unprivileged_user, uri=uri, ignore_status=True).exit_status if not status_error: list_output = virsh.dom_list().stdout.strip() session.close() # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() try: if status_error: if not status: raise error.TestFail("Run successfully with wrong command!") else: if status: raise error.TestFail("Run failed with right command") if not re.search(vm_name, list_output): raise error.TestFail("Run failed with right command") if extra_param.count("paused"): if not vm.is_paused(): raise error.TestFail("Guest state should be" " paused after restore" " due to the option --paused") if extra_param.count("running"): if vm.is_dead() or vm.is_paused(): raise error.TestFail("Guest state should be" " running after restore" " due to the option --running") finally: if vm.is_paused(): virsh.resume(vm_name)
def run(test, params, env): """ Test command: virsh domxml-to-native. Convert domain XML config to a native guest configuration format. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh domxml-from-native operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(params["main_vm"]) vm.verify_alive() def buildcmd(arglist): """ Return a list of arguments of qemu command. Return a list based on the input string where each list element is put together with care to pair up options with their argument rather than being on separate lines. Thus rather than having "-option" "argument" in separate list elements, they will be in one element "-option argument". Take care to note the argument to an option may not be required. This will make it easier to determine what is causing the failure when printing error messages. """ # First separate everything by the first space into a list elems = arglist.split('\x20') # Peruse the list to build up a formatted output retlist retlist = [] i = 0 skip = False for e in elems: # If 'skip' is True, then we've appended an option and argument if skip: skip = False i = i + 1 continue # Need a peek at the next element enext = elems[i + 1] # If current and next element starts with "-", then the # is not an argument to the current, thus we just append. # Same for anything we find that doesn't start with a "-" if (e[0] == '-' and enext[0] == '-') or e[0] != '-': retlist.append(e) else: # Append this and the next and set our skip flag retlist.append(e + " " + enext) skip = True i = i + 1 # Now build a list where the return retlist def filtlist(arglist): """ Return a filtered list of arguments. Walk through the supplied list to filter out things that will be known to be different depending on the running environment. """ retlist = [] for arg in arglist: if re.search("mode=readline", arg): continue elif re.search("mac=", arg): continue elif re.search("127.0.0.1:", arg): continue elif re.search("tap", arg): continue # Upstream libvirt commit id 'e8400564': # XMLToNative: Don't show -S elif re.search("-S", arg): continue elif re.search("socket,id=", arg): continue elif re.search("secret,id=", arg): continue elif re.search("-cpu", arg): continue retlist.append(arg) return retlist def compare(conv_arg): """ Compare converted information with vm's information. :param conv_arg : Converted information. :return: True if converted information has no different from vm's information. """ pid = vm.get_pid() cmdline_tmp = to_text( process.system_output("cat -v /proc/%d/cmdline" % pid, shell=True)) # Output has a trailing '^@' which gets converted into an empty # element when spliting by '\x20', so strip it on the end. cmdline = re.sub(r'\^@', ' ', cmdline_tmp).strip(' ') # Fedora 19 replaces the /usr/bin/qemu-kvm with the string # "/usr/bin/qemu-system-x86_64 -machine accel=kvm", so let's # do the same if we find "/usr/bin/qemu-kvm" in the incoming # argument list and we find "qemu-system-x86_64 -machine accel=kvm" # in the running guest's cmdline # ubuntu use /usr/bin/kvm as qemu binary qemu_bin = ["/usr/bin/qemu-kvm", "/usr/bin/kvm"] arch_bin = [ "/usr/bin/qemu-system-x86_64 -machine accel=kvm", "/usr/bin/qemu-system-ppc64 -machine accel=kvm", "qemu-system-ppc64 -enable-kvm" ] qemu_kvm_bin = "" for each_bin in qemu_bin: if conv_arg.find(each_bin) != -1: qemu_kvm_bin = each_bin if qemu_kvm_bin: for arch in arch_bin: if cmdline.find(arch) != -1: cmdline = re.sub(arch, qemu_kvm_bin, cmdline) else: logging.warning("qemu-kvm binary is not identified: '%s'", qemu_kvm_bin) # Now prepend the various environment variables that will be in # the conv_arg, but not in the actual command tmp = re.search('LC_ALL.[^\s]\s', conv_arg).group(0) +\ re.search('PATH.[^\s]+\s', conv_arg).group(0) +\ re.search('QEMU_AUDIO_DRV.[^\s]+\s', conv_arg).group(0) qemu_arg = tmp + cmdline conv_arg_lines = buildcmd(conv_arg) qemu_arg_lines = buildcmd(qemu_arg) diff1 = filtlist( tuple(x for x in conv_arg_lines if x not in set(qemu_arg_lines))) if diff1: logging.debug("Found the following in conv_arg not in qemu_arg:") for elem in diff1: logging.debug("\t%s", elem) diff2 = filtlist( tuple(x for x in qemu_arg_lines if x not in set(conv_arg_lines))) if diff2: logging.debug("Found the following in qemu_arg not in conv_arg:") for elem in diff2: logging.debug("\t%s", elem) if diff1 or diff2: return False return True # prepare vm_name = params.get("main_vm") vm = env.get_vm(vm_name) if not vm.is_dead(): vm.destroy() vm.start() if not vm.is_alive(): test.fail("VM start failed") domid = vm.get_id() domuuid = vm.get_uuid() dtn_format = params.get("dtn_format") file_xml = params.get("dtn_file_xml", "") extra_param = params.get("dtn_extra_param") extra = params.get("dtn_extra", "") libvirtd = params.get("libvirtd") status_error = params.get("status_error", "no") vm_id = params.get("dtn_vm_id", "") readonly = ("yes" == params.get("readonly", "no")) # For positive_test if status_error == "no": if vm_id == "id": vm_id = domid elif vm_id == "uuid": vm_id = domuuid elif vm_id == "name": vm_id = "%s %s" % (vm_name, extra) if file_xml == "": extra_param = extra_param + vm_id virsh.dumpxml(vm_name, extra="", to_file=file_xml) if libvirtd == "off": utils_libvirtd.libvirtd_stop() # run test case ret = virsh.domxml_to_native(dtn_format, file_xml, extra_param, readonly=readonly, ignore_status=True, debug=True) status = ret.exit_status conv_arg = ret.stdout.strip() # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # clean up if os.path.exists(file_xml): os.remove(file_xml) # check status_error if status_error == "yes": if status == 0: test.fail("Run successfully with wrong command!") elif status_error == "no": if status != 0: test.fail("Run failed with right command") if compare(conv_arg) is not True: test.fail("Test failed!")
def run_virsh_vcpuinfo(test, params, env): """ Test command: virsh vcpuinfo. The command can get domain vcpu information 1.Prepare test environment. 2.When the ibvirtd == "off", stop the libvirtd service. 3.Perform virsh vcpuinfo operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) status_error = params.get("status_error", "no") libvirtd = params.get("libvirtd", "on") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # run test case vm_ref = params.get("vcpuinfo_vm_ref") domid = vm.get_id() domuuid = vm.get_uuid() def remote_case(params, vm_name): """ Test remote case. """ remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) # Used for connecting from remote to local connect_uri = params.get("remote_connect_uri", "qemu+ssh://LOCAL.EXAMPLE.COM/system") # Verify connect_uri is useful for this test. if not virsh.VirshConnectBack.kosher_args(remote_ip, connect_uri): raise error.TestNAError("The connect_uri parameter '%s' does " "not point at fully-qualified host " "from perspective of remote support " "system at '%s'." % (connect_uri, remote_ip)) status = 0 output = "" err = "" try: vcback = virsh.VirshConnectBack(remote_ip=remote_ip, remote_pwd=remote_pwd, uri=connect_uri, debug=True, ignore_status=True) cmdresult = vcback.vcpuinfo(vm_name) status = cmdresult.exit_status output = cmdresult.stdout vcback.close_session() if status != 0: err = output except error.CmdError: status = 1 output = "" err = "remote test failed" # Maintain result format conformance with local test return status, output, err 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 == "uuid": vm_ref = domuuid elif vm_ref == "name": vm_ref = "%s %s" % (vm_name, params.get("vcpuinfo_extra")) if vm_ref == "remote": # Keep status_error check conditions (below) simple status, output, err = remote_case(params, vm_name) else: result = virsh.vcpuinfo(vm_ref) status = result.exit_status output = result.stdout.strip() err = result.stderr.strip() # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error == "yes": if not status: logging.debug(result) raise error.TestFail("Run successfully with wrong command!") # Check the error message in negative case. if not err: logging.debug(result) logging.debug("Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=889276 " "is helpful for tracing this bug.") raise error.TestFail("No error message for a command error!") elif status_error == "no": if status: logging.debug(result) raise error.TestFail("Run failed with right command")
def run(test, params, env): """ Test command: virsh domname <id/uuid>. 1) Prepare libvirtd status and test environment. 2) Try to get domname through valid and invalid command. 3) Recover libvirtd service and test environment. 4) Check result. """ vm_name = params.get("main_vm") vm = env.get_vm(params["main_vm"]) domid = vm.get_id() domuuid = vm.get_uuid() connect_uri = vm.connect_uri # run test case options_ref = params.get("domname_options_ref", "id") addition_status_error = params.get("addition_status_error", "no") status_error = params.get("status_error", "no") options = params.get("domname_options", "%s") options_suffix = params.get("domname_options_suffix", "") if options_ref == "id": options_ref = domid if options_ref == "-": options = "%s" else: options_ref = int(domid) elif options_ref == "uuid": options_ref = domuuid # UUID can get domain name in any state. logging.warning("Reset addition_status_error to NO for uuid test!") addition_status_error = "no" elif options_ref == "name": options_ref = vm_name if options: options = (options % options_ref) if options_suffix: options = options + " " + options_suffix # Prepare libvirtd status libvirtd = params.get("libvirtd", "on") if libvirtd == "off": utils_libvirtd.libvirtd_stop() result = virsh.domname(options, ignore_status=True, debug=True, uri=connect_uri) # Recover libvirtd service to start if libvirtd == "off": utils_libvirtd.libvirtd_start() addition_status_error = "yes" # check status_error status_error = (status_error == "no") and (addition_status_error == "no") if status_error: if result.exit_status != 0 or result.stdout.strip() != vm_name: raise error.TestFail("Run failed because unexpected result.") else: if result.exit_status == 0 and result.stdout.strip() != vm_name: raise error.TestFail("Run passed but result is unexpected.")
def run_virsh_edit(test, params, env): """ Test command: virsh edit. The command can edit XML configuration for a domain 1.Prepare test environment,destroy or suspend a VM. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh edit operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) domid = vm.get_id() domuuid = vm.get_uuid() 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")
def run(test, params, env): """ Test command: virsh domifstat. The command can get network interface stats for a running domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh domifstat operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) def get_interface(guest_name): """ Get interface device of VM. :param guest_name: VM's name. :return: interface device of VM. """ interface = "" domxml = to_text(process.system_output("virsh dumpxml %s" % guest_name, shell=True)) dom = parseString(domxml) root = dom.documentElement array = root.getElementsByTagName("interface") for element in array: if element.getAttribute("type") == "bridge" or \ element.getAttribute("type") == "network": interface = "vnet0" nodelist = element.childNodes for node in nodelist: if node.nodeName == "target": interface = node.getAttribute("dev") break return interface domid = vm.get_id() domuuid = vm.get_uuid() vm_ref = params.get("domifstat_vm_ref", vm_name) nic_ref = params.get("domifstat_nic_ref", "") libvirtd = params.get("libvirtd", "on") status_error = params.get("status_error", "no") 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 == "uuid": vm_ref = domuuid elif vm_ref == "name": vm_ref = vm_name interface = get_interface(vm_name) if nic_ref == "": interface = "" elif nic_ref == "error_interface": interface = params.get(nic_ref) interface = "%s %s" % (interface, params.get("domifstat_extra")) if libvirtd == "off": utils_libvirtd.libvirtd_stop() status = virsh.domifstat(vm_ref, interface, ignore_status=True).exit_status # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error == "yes": if status == 0: test.fail("Run successfully with wrong command!") elif status_error == "no": if status != 0: test.fail("Run failed with right command")
def run(test, params, env): """ Test command: virsh shutdown. The conmand can gracefully shutdown a domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh setvcpus operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) vm_ref = params.get("shutdown_vm_ref") status_error = ("yes" == params.get("status_error")) agent = ("yes" == params.get("shutdown_agent", "no")) mode = params.get("shutdown_mode", "") pre_domian_status = params.get("reboot_pre_domian_status", "running") libvirtd = params.get("libvirtd", "on") xml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) timeout = eval(params.get("shutdown_timeout", "60")) readonly = "yes" == params.get("shutdown_readonly", "no") expect_msg = params.get("shutdown_err_msg") # Libvirt acl test related params uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' if not libvirt_version.version_compare(1, 1, 1): if params.get('setup_libvirt_polkit') == 'yes': test.cancel("API acl test not supported in" " current libvirt version.") try: # Add or remove qemu-agent from guest before test vm.prepare_guest_agent(channel=agent, start=agent) if pre_domian_status == "shutoff": virsh.destroy(vm_name) domid = vm.get_id() domuuid = vm.get_uuid() # run test case 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("shutdown_extra")) elif vm_ref == "uuid": vm_ref = domuuid if libvirtd == "off": utils_libvirtd.libvirtd_stop() if vm_ref != "remote": result = virsh.shutdown(vm_ref, mode, unprivileged_user=unprivileged_user, uri=uri, debug=True, ignore_status=True, readonly=readonly) status = result.exit_status else: remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) remote_user = params.get("remote_user", "root") local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") local_pwd = params.get("local_pwd", "password") local_user = params.get("username", "root") if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"): test.cancel("Remote test parameters" " unchanged from default") status = 0 try: remote_uri = libvirt_vm.complete_uri(local_ip) # set up auto ssh login from remote machine to # execute commands config_opt = ["StrictHostKeyChecking=no"] ssh_key.setup_remote_ssh_key(remote_ip, remote_user, remote_pwd, hostname2=local_ip, user2=local_user, password2=local_pwd, config_options=config_opt) session = remote.remote_login("ssh", remote_ip, "22", "root", remote_pwd, "#") session.cmd_output('LANG=C') command = ("virsh -c %s shutdown %s %s" % (remote_uri, vm_name, mode)) status = session.cmd_status(command, internal_timeout=5) session.close() except process.CmdError: status = 1 # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error: if not status: test.fail("Run successfully with wrong command!") if expect_msg: libvirt.check_result(result, expect_msg.split(';')) else: if status: test.fail("Run failed with right command") if not vm.wait_for_shutdown(timeout): test.fail("Failed to shutdown in timeout %s" % timeout) finally: if utils_misc.wait_for(utils_libvirtd.libvirtd_is_running, 60): xml_backup.sync()
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") 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 else: vm.wait_for_login().close() output = virsh.dom_list(ignore_status=True).stdout.strip() # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error: if not status: test.fail("Run successfully with wrong command!") else: if status or (not re.search(vm_name, output)): if status == -2: test.cancel("Reboot command doesn't work on older libvirt " "versions") test.fail("Run failed with right command") finally: xml_backup.sync()
def run(test, params, env): """ Test the command virsh capabilities (1) Call virsh capabilities (2) Call virsh capabilities with an unexpected option (3) Call virsh capabilities with libvirtd service stop """ def compare_capabilities_xml(source): dom = parseString(source) host = dom.getElementsByTagName('host')[0] # check that host has a non-empty UUID tag. uuid = host.getElementsByTagName('uuid')[0] host_uuid_output = uuid.firstChild.data logging.info("Host uuid (capabilities_xml):%s", host_uuid_output) if host_uuid_output == "": raise error.TestFail("The host uuid in capabilities_xml is none!") # check the host arch. arch = host.getElementsByTagName('arch')[0] host_arch_output = arch.firstChild.data logging.info("Host arch (capabilities_xml):%s", host_arch_output) cmd_result = utils.run("arch", ignore_status=True) if cmp(host_arch_output, cmd_result.stdout.strip()) != 0: raise error.TestFail("The host arch in capabilities_xml is wrong!") # check the host cpus num. cpus = dom.getElementsByTagName('cpus') host_cpus = 0 for cpu in cpus: host_cpus += int(cpu.getAttribute('num')) logging.info("Host cpus num (capabilities_xml):%s", host_cpus) cmd = "less /proc/cpuinfo | grep processor | wc -l" cmd_result = utils.run(cmd, ignore_status=True) if cmp(host_cpus, int(cmd_result.stdout.strip())) != 0: raise error.TestFail("Host cpus num (capabilities_xml) is " "wrong") # check the arch of guest supported. try: img = utils_misc.find_command("qemu-kvm") except ValueError: raise error.TestNAError("Cannot find qemu-kvm") cmd = img + " --cpu ? | grep qemu" cmd_result = utils.run(cmd, ignore_status=True) guest_wordsize_array = dom.getElementsByTagName('wordsize') length = len(guest_wordsize_array) for i in range(length): element = guest_wordsize_array[i] guest_wordsize = element.firstChild.data logging.info("Arch of guest supported (capabilities_xml):%s", guest_wordsize) if not re.search(guest_wordsize, cmd_result.stdout.strip()): raise error.TestFail("The capabilities_xml gives an extra arch " "of guest to support!") # check the type of hyperviosr. guest_domain_type = dom.getElementsByTagName('domain')[0] guest_domain_type_output = guest_domain_type.getAttribute('type') logging.info("Hypervisor (capabilities_xml):%s", guest_domain_type_output) cmd_result = utils.run("virsh uri", ignore_status=True) if not re.search(guest_domain_type_output, cmd_result.stdout.strip()): raise error.TestFail("The capabilities_xml gives an different " "hypervisor") connect_uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri", "default")) # Prepare libvirtd service if params.has_key("libvirtd"): libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_cap_options") try: output = virsh.capabilities(option, uri=connect_uri, ignore_status=False, debug=True) status = 0 # good except error.CmdError: status = 1 # bad output = '' # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off": raise error.TestFail("Command 'virsh capabilities' succeeded " "with libvirtd service stopped, incorrect") else: raise error.TestFail("Command 'virsh capabilities %s' succeeded " "(incorrect command)" % option) elif status_error == "no": compare_capabilities_xml(output) if status != 0: raise error.TestFail("Command 'virsh capabilities %s' failed " "(correct command)" % option)
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") xml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) try: # Add or remove qemu-agent from guest before test if agent: vm_xml.VMXML.set_agent_channel(vm_name) else: vm_xml.VMXML.remove_agent_channel(vm_name) virsh.start(vm_name) guest_session = vm.wait_for_login() if agent: guest_session.cmd("qemu-ga -d") stat_ps = guest_session.cmd_status("ps aux |grep [q]emu-ga") guest_session.close() if stat_ps: raise error.TestError("Fail to start qemu-guest-agent!") 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"): raise error.TestNAError("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() # FIXME: Catch specific exception except Exception, detail: logging.error("Exception: %s", str(detail)) status = -1 if vm_ref != "remote_name": vm_ref = "%s %s" % (vm_ref, 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 output = virsh.dom_list(ignore_status=True).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 re.search(vm_name, output)): if status == -2: raise error.TestNAError( "Reboot command doesn't work on older libvirt versions" ) raise error.TestFail("Run failed with right command")
def run_virsh_change_media(test, params, env): """ Test command: virsh change-media. The command changes the media used by CD or floppy drives. Test steps: 1. Prepare test environment. 2. Perform virsh change-media operation. 3. Recover test environment. 4. Confirm the test result. """ @error.context_aware def env_pre(old_iso, new_iso): """ Prepare ISO image for test @param: old_iso: sourse file for insert @param: new_iso: sourse file for update """ error.context("Preparing ISO images") utils.run("dd if=/dev/urandom of=%s/old bs=10M count=1" % cdrom_dir) utils.run("dd if=/dev/urandom of=%s/new bs=10M count=1" % cdrom_dir) utils.run("mkisofs -o %s %s/old" % (old_iso, cdrom_dir)) utils.run("mkisofs -o %s %s/new" % (new_iso, cdrom_dir)) @error.context_aware def check_media(session, target_file, action): """ Check guest cdrom files @param: session: guest session @param: target_file: the expected files @action: action: test case action """ if action != "--eject ": error.context("Checking guest cdrom files") session.cmd("mount /dev/cdrom /media || mount /dev/cdrom /media") session.cmd("test -f /media/%s" % target_file) session.cmd("umount /dev/cdrom") else: error.context("Ejecting guest cdrom files") if session.cmd_status("mount /dev/cdrom /media -o loop") == 32: logging.info("Eject succeeded") def add_cdrom_device(vm_name, init_cdrom): """ Add cdrom device for test vm @param: vm_name: guest name @param: init_cdrom: source file """ if vm.is_alive(): virsh.destroy(vm_name) virsh.attach_disk(vm_name, init_cdrom, disk_device, " --type cdrom --sourcetype file --config", debug=True) def update_cdrom(vm_name, init_iso, options, start_vm): """ Update cdrom iso file for test case @param: vm_name: guest name @param: init_iso: source file @param: options: update-device option @param: start_vm: guest start flag """ snippet = """ <disk type='file' device='cdrom'> <driver name='qemu' type='raw'/> <source file='%s'/> <target dev='%s' bus='ide'/> <readonly/> </disk> """ % (init_iso, disk_device) update_iso_file = open(update_iso_xml, "w") update_iso_file.write(snippet) update_iso_file.close() cmd_options = "--force " if options == "--config" or start_vm == "no": cmd_options += " --config" # Give domain the ISO image file virsh.update_device(domainarg=vm_name, filearg=update_iso_xml, flagstr=cmd_options, debug=True) vm_name = params.get("main_vm") vm = env.get_vm(vm_name) vm_ref = params.get("change_media_vm_ref") action = params.get("change_media_action") start_vm = params.get("start_vm") options = params.get("change_media_options") disk_device = params.get("change_media_disk_device") libvirtd = params.get("libvirtd", "on") source_name = params.get("change_media_source") status_error = params.get("status_error", "no") check_file = params.get("change_media_check_file") init_cdrom = params.get("change_media_init_cdrom") update_iso_xml_name = params.get("change_media_update_iso_xml") init_iso_name = params.get("change_media_init_iso") old_iso_name = params.get("change_media_old_iso") new_iso_name = params.get("change_media_new_iso") cdrom_dir = os.path.join(test.tmpdir, "tmp") old_iso = os.path.join(cdrom_dir, old_iso_name) new_iso = os.path.join(cdrom_dir, new_iso_name) update_iso_xml = os.path.join(cdrom_dir, update_iso_xml_name) if not os.path.exists(cdrom_dir): os.mkdir(cdrom_dir) if not init_iso_name : init_iso = "" else: init_iso = os.path.join(cdrom_dir, init_iso_name) if vm_ref == "name": vm_ref = vm_name env_pre(old_iso, new_iso) # Check domain's disk device disk_blk = vm_xml.VMXML.get_disk_blk(vm_name) logging.info("disk_blk %s" % disk_blk) if disk_device not in disk_blk: logging.info("Adding cdrom device") add_cdrom_device(vm_name, init_cdrom) if vm.is_alive() and start_vm == "no": logging.info("Destroying guest...") vm.destroy() elif vm.is_dead() and start_vm == "yes": logging.info("Starting guest...") vm.start() update_cdrom(vm_name, init_iso, options, start_vm) if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Libvirt will ignore --source when action is eject if action == "--eject ": source = "" else: source = os.path.join(cdrom_dir, source_name) all_options = action + options + " " + source result = virsh.change_media(vm_ref, disk_device, all_options, ignore_status=True, debug=True) status = result.exit_status if status_error == "no": if options == "--config" and vm.is_alive(): vm.destroy() if vm.is_dead(): vm.start() session = vm.wait_for_login() check_media(session, check_file, action) session.close() # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Clean the cdrom dir and clean the cdrom device update_cdrom(vm_name, "", options, start_vm) # Check status_error # Negative testing 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) # Positive testing elif status_error == "no": if status: raise error.TestFail("Unexpected error (positive testing). " "Output: %s" % result.stderr.strip()) else: logging.info("Expected success. Output: %s", result.stdout.strip()) else: raise error.TestError("Invalid value for status_error '%s' " "(must be 'yes' or 'no')" % status_error)
def run_virsh_domid(test, params, env): """ Test command: virsh domid. The command returns basic information about the domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh domid operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm", "vm1") vm = env.get_vm(vm_name) if vm.is_alive() and params.get("start_vm") == "no": vm.destroy() domid = vm.get_id() domuuid = vm.get_uuid() vm_ref = params.get("domid_vm_ref") extra = params.get("domid_extra", "") status_error = params.get("status_error", "no") libvirtd = params.get("libvirtd", "on") def remote_test(params, vm_name): """ Test remote case. """ remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", "") status = 0 output = "" err = "" try: 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.") 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 domid %s" % (uri, vm_name) status, output = session.cmd_status_output(command, internal_timeout=5) if status != 0: err = output session.close() except error.CmdError: status = 1 output = "" err = "remote test failed" return status, output, err # run test case if vm_ref == "id": vm_ref = domid elif vm_ref.find("invalid") != -1: vm_ref = params.get(vm_ref) elif vm_ref == "name": vm_ref = "%s %s" % (vm_name, extra) elif vm_ref == "uuid": vm_ref = domuuid if libvirtd == "off": utils_libvirtd.libvirtd_stop() if vm_ref != "remote": result = virsh.domid(vm_ref, ignore_status=True) status = result.exit_status output = result.stdout.strip() err = result.stderr.strip() else: status, output, err = remote_test(params, vm_name) # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error == "yes": if status == 0 or err == "": 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")
def run(test, params, env): """ Test the command virsh nodecpustats (1) Call the virsh nodecpustats command for all cpu host cpus separately (2) Get the output (3) Check the against /proc/stat output(o) for respective cpu user: o[0] + o[1] system: o[2] + o[5] + o[6] idle: o[3] iowait: o[4] (4) Call the virsh nodecpustats command with an unexpected option (5) Call the virsh nodecpustats command with libvirtd service stop """ def virsh_check_nodecpustats_percpu(actual_stats): """ Check the acual nodecpustats output value total time <= system uptime """ # Normalise to seconds from nano seconds total = float((actual_stats['system'] + actual_stats['user'] + actual_stats['idle'] + actual_stats['iowait']) / (10 ** 9)) uptime = float(utils.get_uptime()) if not total <= uptime: raise error.TestFail("Commands 'virsh nodecpustats' not succeeded" " as total time: %f is more" " than uptime: %f" % (total, uptime)) return True def virsh_check_nodecpustats(actual_stats, cpu_count): """ Check the acual nodecpustats output value total time <= system uptime """ # Normalise to seconds from nano seconds and get for one cpu total = float(((actual_stats['system'] + actual_stats['user'] + actual_stats['idle'] + actual_stats['iowait']) / (10 ** 9)) / ( cpu_count)) uptime = float(utils.get_uptime()) if not total <= uptime: raise error.TestFail("Commands 'virsh nodecpustats' not succeeded" " as total time: %f is more" " than uptime: %f" % (total, uptime)) return True def virsh_check_nodecpustats_percentage(actual_per): """ Check the actual nodecpustats percentage adds up to 100% """ total = int(round(actual_per['user'] + actual_per['system'] + actual_per['idle'] + actual_per['iowait'])) if not total == 100: raise error.TestFail("Commands 'virsh nodecpustats' not succeeded" " as the total percentage value: %d" " is not equal 100" % total) def parse_output(output): """ To get the output parsed into a dictionary :param virsh command output :return: dict of user,system,idle,iowait times """ # From the beginning of a line, group 1 is one or more word-characters, # followed by zero or more whitespace characters and a ':', # then one or more whitespace characters, # followed by group 2, which is one or more digit characters, # e.g as below # user: 6163690000000 # regex_obj = re.compile(r"^(\w+)\s*:\s+(\d+)") actual = {} for line in output.stdout.split('\n'): match_obj = regex_obj.search(line) # Due to the extra space in the list if match_obj is not None: name = match_obj.group(1) value = match_obj.group(2) actual[name] = int(value) return actual def parse_percentage_output(output): """ To get the output parsed into a dictionary :param virsh command output :return: dict of user,system,idle,iowait times """ # From the beginning of a line, group 1 is one or more word-characters, # followed by zero or more whitespace characters and a ':', # then one or more whitespace characters, # followed by group 2, which is one or more digit characters, # e.g as below # user: 1.5% # regex_obj = re.compile(r"^(\w+)\s*:\s+(\d+.\d+)") actual_percentage = {} for line in output.stdout.split('\n'): match_obj = regex_obj.search(line) # Due to the extra space in the list if match_obj is not None: name = match_obj.group(1) value = match_obj.group(2) actual_percentage[name] = float(value) return actual_percentage # Initialize the variables itr = int(params.get("inner_test_iterations")) option = params.get("virsh_cpunodestats_options") status_error = params.get("status_error") libvirtd = params.get("libvirtd", "on") # Prepare libvirtd service if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Get the host cpu count host_cpu_count = utils.count_cpus() # Run test case for 5 iterations default can be changed in subtests.cfg # file for i in range(itr): if status_error == "yes": output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: if libvirtd == "off": utils_libvirtd.libvirtd_start() raise error.TestFail("Command 'virsh nodecpustats' " "succeeded with libvirtd service " "stopped, incorrect") else: raise error.TestFail("Command 'virsh nodecpustats %s' " "succeeded (incorrect command)" % option) elif status_error == "no": # Run the testcase for each cpu to get the cpu stats for cpu in range(host_cpu_count): option = "--cpu %d" % cpu output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: actual_value = parse_output(output) virsh_check_nodecpustats_percpu(actual_value) else: raise error.TestFail("Command 'virsh nodecpustats %s'" "not succeeded" % option) # Run the test case for each cpu to get the cpu stats in percentage for cpu in range(host_cpu_count): option = "--cpu %d --percent" % cpu output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: actual_value = parse_percentage_output(output) virsh_check_nodecpustats_percentage(actual_value) else: raise error.TestFail("Command 'virsh nodecpustats %s'" " not succeeded" % option) option = '' # Run the test case for total cpus to get the cpus stats output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: actual_value = parse_output(output) virsh_check_nodecpustats(actual_value, host_cpu_count) else: raise error.TestFail("Command 'virsh nodecpustats %s'" " not succeeded" % option) # Run the test case for the total cpus to get the stats in # percentage option = "--percent" output = virsh.nodecpustats(ignore_status=True, option=option) status = output.exit_status if status == 0: actual_value = parse_percentage_output(output) virsh_check_nodecpustats_percentage(actual_value) else: raise error.TestFail("Command 'virsh nodecpustats %s'" " not succeeded" % option) # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start()
def run(test, params, env): """ Test the command virsh nodememstats (1) Call the virsh nodememstats command (2) Get the output (3) Check the against /proc/meminfo output (4) Call the virsh nodememstats command with an unexpected option (5) Call the virsh nodememstats command with libvirtd service stop """ # Initialize the variables expected = {} actual = {} deltas = [] name_stats = ['total', 'free', 'buffers', 'cached'] itr = int(params.get("itr")) def virsh_check_nodememtats(actual_stats, expected_stats, delta): """ Check the nodememstats output value with /proc/meminfo value """ delta_stats = {} for name in name_stats: delta_stats[name] = abs(actual_stats[name] - expected_stats[name]) if 'total' in name: if not delta_stats[name] == 0: test.fail("Command 'virsh nodememstats' not" " succeeded as the value for %s is " "deviated by %d\nThe total memory " "value is deviating-check" % (name, delta_stats[name])) else: if delta_stats[name] > delta: test.fail("Command 'virsh nodememstats' not " "succeeded as the value for %s" " is deviated by %d" % (name, delta_stats[name])) return delta_stats # Prepare libvirtd service check_libvirtd = "libvirtd" in params if check_libvirtd: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Get the option for the test case option = params.get("virsh_nodememstats_options") if option == "max": cell_dict = utils_test.libvirt.get_all_cells() option = len(list(cell_dict.keys())) # Run test case for 10 iterations # (default can be changed in subtests.cfg file) # and print the final statistics for i in range(itr): output = virsh.nodememstats(option) # Get the status of the virsh command executed status = output.exit_status # Get status_error option for the test case status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off": utils_libvirtd.libvirtd_start() test.fail("Command 'virsh nodememstats' " "succeeded with libvirtd service" " stopped, incorrect") else: test.fail("Command 'virsh nodememstats %s' " "succeeded (incorrect command)" % option) elif status_error == "no": if status == 0: if option: return # From the beginning of a line, group 1 is one or # more word-characters, followed by zero or more # whitespace characters and a ':', then one or # more whitespace characters, followed by group 2, # which is one or more digit characters, # then one or more whitespace characters followed by # a literal 'kB' or 'KiB' sequence, e.g as below # total : 3809340 kB # total : 3809340 KiB # Normalise the value to MBs regex_obj = re.compile(r"^(\w+)\s*:\s+(\d+)\s\w+") expected = {} for line in output.stdout.split('\n'): match_obj = regex_obj.search(line) # Due to the extra space in the list if match_obj is not None: name = match_obj.group(1) value = match_obj.group(2) expected[name] = int(value) // 1024 # Get the actual value from /proc/meminfo and normalise to MBs actual['total'] = int(utils_memory.memtotal()) // 1024 actual['free'] = int(utils_memory.freememtotal()) // 1024 actual['buffers'] = int( utils_memory.read_from_meminfo('Buffers')) // 1024 actual['cached'] = int( utils_memory.read_from_meminfo('Cached')) // 1024 # Currently the delta value is kept at 200 MB this can be # tuned based on the accuracy # Check subtests.cfg for more details delta = int(params.get("delta")) output = virsh_check_nodememtats(actual, expected, delta) deltas.append(output) else: test.fail("Command virsh nodememstats %s not " "succeeded:\n%s" % (option, status)) # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Print the deviated values for all iterations if status_error == "no": logging.debug("The following is the deviations from " "the actual(/proc/meminfo) and expected" " value(output of virsh nodememstats)") for i in range(itr): logging.debug("iteration %d:", i) for index, name in enumerate(name_stats): logging.debug("%19s : %d", name, deltas[i][name])
def run(test, params, env): """ Test command: virsh dommemstat. The command gets memory statistics for a domain 1.Prepare test environment. 2.When the ibvirtd == "off", stop the libvirtd service. 3.Perform virsh dommemstat operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(params["main_vm"]) domid = vm.get_id() domuuid = vm.get_uuid() status_error = params.get("status_error", "no") vm_ref = params.get("dommemstat_vm_ref", "name") libvirtd = params.get("libvirtd", "on") extra = params.get("dommemstat_extra", "") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # run test case if vm_ref == "id": vm_ref = domid elif vm_ref == "hex_id": vm_ref = hex(int(domid)) elif vm_ref == "uuid": vm_ref = domuuid elif vm_ref.count("_invalid_"): # vm_ref names parameter to fetch vm_ref = params.get(vm_ref) elif vm_ref == "name": vm_ref = "%s" % vm_name if libvirtd == "off": utils_libvirtd.libvirtd_stop() if vm_ref != "remote": status = virsh.dommemstat(vm_ref, extra, ignore_status=True, debug=True).exit_status else: remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") if remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM"): test.cancel("local/remote ip parameters not set.") 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 dommemstat %s %s" % (remote_uri, vm_name, extra) status = session.cmd_status(command, internal_timeout=5) session.close() except process.CmdError: status = 1 # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error == "yes": if status == 0: test.fail("Run successfully with wrong command!") elif status_error == "no": if status != 0: test.fail("Run failed with right command")
def run(test, params, env): """ Test command: virsh domjobinfo. The command returns information about jobs running on a domain. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform job action on a domain. 4.Get running and completed job info by virsh domjobinfo. 5.Recover test environment. 6.Confirm the test result. """ def get_subprocess(action, vm_name, file, remote_uri=None): """ Execute background virsh command, return subprocess w/o waiting for exit() :param action : virsh command and its option. :param vm_name : VM's name :param file : virsh command's file option, could be vm.dump, vm.save, etc. """ command = "virsh %s %s %s" % (action, vm_name, file) logging.debug("Action: %s", command) p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return p def cmp_jobinfo(result, info_list, job_type, actions): """ Compare the output jobinfo with expected one :param result : the return from domjobinfo cmd :param info_list : an expected domjobinfo list :param job_type : an expected value for 'Job Type' :param actions : the job operation """ logging.debug(result.stdout) out_list = result.stdout.strip().splitlines() out_dict = dict([x.split(':') for x in out_list]) ret_cmp = set(out_dict.keys()) == set(info_list) if not ret_cmp: if set(info_list) - set(out_dict.keys()): test.fail("Missing expected items in domjobinfo output: %s" % (set(info_list) - set(out_dict.keys()))) else: new_cmp = set(out_dict.keys()) - set(info_list) known_item = {'Memory bandwidth'} # For running domjobinfo, 'Memory bandwidth' appears sometimes. if new_cmp != known_item or job_type == "Completed": test.fail("New items appear: %s, pls modify script!", new_cmp) else: if out_dict["Job type"].strip() != job_type: test.fail("Expect %s Job type but got %s" % (job_type, out_dict["Job type"].strip())) if out_dict["Operation"].strip() != actions.capitalize(): test.fail( "Expect %s Operation but got %s" % (actions.capitalize(), out_dict["Operation"].strip())) vm_name = params.get("main_vm") vm = env.get_vm(vm_name) start_vm = params.get("start_vm") pre_vm_state = params.get("pre_vm_state", "start") if start_vm == "no" and vm.is_alive(): vm.destroy() # Instead of "paused_after_start_vm", use "pre_vm_state". # After start the VM, wait for some time to make sure the job # can be created on this domain. if start_vm == "yes": vm.wait_for_login() if params.get("pre_vm_state") == "suspend": vm.pause() domid = vm.get_id() domuuid = vm.get_uuid() actions = params.get("domjobinfo_action", "dump") act_opt = params.get("dump_opt", "") vm_ref = params.get("domjobinfo_vm_ref") status_error = params.get("status_error", "no") libvirtd = params.get("libvirtd", "on") # Use tmp_pipe to act as target file for job operation in subprocess, # such as vm.dump, vm.save, etc. tmp_pipe = os.path.join(data_dir.get_tmp_dir(), "domjobinfo.fifo") # Build job action action = ' '.join([actions, act_opt]) if actions == "managedsave": tmp_pipe = '/var/lib/libvirt/qemu/save/%s.save' % vm.name # Expected domjobinfo list info_list = [ "Job type", "Time elapsed", "Data processed", "Data remaining", "Data total", "Memory processed", "Memory remaining", "Memory total", "Dirty rate", "Iteration", "Constant pages", "Normal pages", "Normal data", "Expected downtime", "Setup time" ] if libvirt_version.version_compare(3, 2, 0): info_list.insert(1, "Operation") if libvirt_version.version_compare(3, 9, 0): info_list.insert(info_list.index("Dirty rate") + 1, "Page size") if libvirt_version.version_compare(5, 0, 0): info_list.insert( info_list.index("Iteration") + 1, "Postcopy requests") logging.debug("The expected info_list for running job is %s", info_list) # run test case if vm_ref == "id": vm_ref = domid elif vm_ref == "hex_id": vm_ref = hex(int(domid)) elif vm_ref == "name": vm_ref = "%s %s" % (vm_name, params.get("domjobinfo_extra")) elif vm_ref == "uuid": vm_ref = domuuid elif 'invalid' in vm_ref: vm_ref = params.get(vm_ref) # Get the subprocess of VM. # The command's effect is to get domjobinfo of running domain job. # So before do "domjobinfo", we must create a job on the domain. process = None if start_vm == "yes" and status_error == "no": if os.path.exists(tmp_pipe): os.unlink(tmp_pipe) os.mkfifo(tmp_pipe) # Target file param is not needed for managedsave operation if action == "managedsave ": process = get_subprocess(action, vm_name, "", None) else: process = get_subprocess(action, vm_name, tmp_pipe, None) f = open(tmp_pipe, 'rb') dummy = f.read(1024 * 1024).decode(locale.getpreferredencoding(), 'ignore') if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Give enough time for starting job t = 0 while t < 5: jobtype = vm.get_job_type() if "None" == jobtype: t += 1 time.sleep(1) continue elif jobtype is False: logging.error("Get job type failed.") break else: logging.debug("Job started: %s", jobtype) break # Get domjobinfo while job is running ret = virsh.domjobinfo(vm_ref, ignore_status=True, debug=True) status = ret.exit_status # Clear process env if process and f: dummy = f.read() f.close() try: os.unlink(tmp_pipe) except OSError as detail: logging.info("Can't remove %s: %s", tmp_pipe, detail) if process: if process.poll(): try: process.kill() except OSError: pass # Get completed domjobinfo if status_error == "no": time.sleep(5) if act_opt != "--live" and vm_ref == domid: # use vm_name but not id since domain shutoff vm_ref = vm_name vm_ref = "%s --completed" % vm_ref ret_cmplt = virsh.domjobinfo(vm_ref, ignore_status=True, debug=True) status_cmplt = ret_cmplt.exit_status # Recover the environment. if actions == "managedsave": virsh.managedsave_remove(vm_name, ignore_status=True) if pre_vm_state == "suspend": vm.resume() if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error if status_error == "yes": if status == 0: if libvirtd == "off" and libvirt_version.version_compare(5, 6, 0): logging.info("From libvirt 5.6.0 libvirtd is restarted " "and command should succeed") else: test.fail("Run successfully with wrong command!") elif status_error == "no": if status != 0 or status_cmplt != 0: test.fail("Run failed with right command") # if libvirtd wasn't running the jobinfo is expected to be empty if status_error == "no" and not libvirtd == "off": # The 'managedsave' Operation will be shown as 'Save' in domjobinfo if actions == "managedsave": actions = "save" # Check output of "virsh domjobinfo" cmp_jobinfo(ret, info_list, "Unbounded", actions) # Check output of "virsh domjobinfo --completed" info_list.insert( info_list.index("Memory total") + 1, "Memory bandwidth") info_list[info_list.index("Expected downtime")] = "Total downtime" logging.debug("The expected info_list for completed job is %s", info_list) cmp_jobinfo(ret_cmplt, info_list, "Completed", actions)
def run_virsh_domxml_from_native(test, params, env): """ Test command: virsh domxml-from-native. Convert native guest configuration format to domain XML format. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh domxml-from-native operation. 4.Recover test environment.(If the libvirtd service is stopped ,start the libvirtd service.) 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) vm.verify_alive() def virsh_convxml(guest_args): """ Put dumpxml vm'infomation to a file :param guest_args : File which will save config information. """ pid = vm.get_pid() cmdline = utils.system_output("cat -v /proc/%d/cmdline" % pid) cmdline = re.sub(r'\^@', ' ', cmdline) cmdline_tmp = re.sub(r'\s-drive\s[^\s]+', '\s', cmdline) guest_file = file(guest_args, 'w') guest_file.write(cmdline_tmp) guest_file.close() libvirtd = params.get("libvirtd") dfn_format = params.get("dfn_format") guest_args = params.get("dfn_guest_args", "") invalid_guest_args = params.get("dfn_invalid_guest_args") status_error = params.get("status_error") # put vm's information to a file if guest_args != "": if os.path.dirname(guest_args) is "": guest_args = os.path.join(test.tmpdir, guest_args) virsh_convxml(guest_args) # libvirtd off if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Ignore exception with ignore_status=True. ret = virsh.domxml_from_native(dfn_format, guest_args, invalid_guest_args, ignore_status=True) status = ret.exit_status # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # clean up if os.path.exists(guest_args): os.remove(guest_args) # 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: raise error.TestFail("Run failed with right command")
def run(test, params, env): """ Test the command virsh nodeinfo (1) Call virsh nodeinfo (2) Call virsh nodeinfo with an unexpected option (3) Call virsh nodeinfo with libvirtd service stop """ def _check_nodeinfo(nodeinfo_output, verify_str, column): cmd = "echo \"%s\" | grep \"%s\" | awk '{print $%s}'" % ( nodeinfo_output, verify_str, column) cmd_result = process.run(cmd, ignore_status=True, shell=True) stdout = cmd_result.stdout_text.strip() logging.debug("Info %s on nodeinfo output:%s" % (verify_str, stdout)) return stdout def output_check(nodeinfo_output): # Check CPU model cpu_model_nodeinfo = _check_nodeinfo(nodeinfo_output, "CPU model", 3) cpu_arch = platform.machine() if not re.match(cpu_model_nodeinfo, cpu_arch): test.fail( "Virsh nodeinfo output didn't match CPU model") # Check number of CPUs, nodeinfo CPUs represent online threads in the # system, check all online cpus in sysfs cpus_nodeinfo = _check_nodeinfo(nodeinfo_output, "CPU(s)", 2) cmd = "cat /sys/devices/system/cpu/cpu*/online | grep 1 | wc -l" cpus_online = process.run(cmd, ignore_status=True, shell=True).stdout.strip() cmd = "cat /sys/devices/system/cpu/cpu*/online | wc -l" cpus_total = process.run(cmd, ignore_status=True, shell=True).stdout.strip() if not os.path.exists('/sys/devices/system/cpu/cpu0/online'): cpus_online = str(int(cpus_online) + 1) cpus_total = str(int(cpus_total) + 1) logging.debug("host online cpus are %s", cpus_online) logging.debug("host total cpus are %s", cpus_total) if cpus_nodeinfo != cpus_online: if 'ppc' in cpu_arch: if cpus_nodeinfo != cpus_total: test.fail("Virsh nodeinfo output of CPU(s) on" " ppc did not match all threads in " "the system") else: test.fail("Virsh nodeinfo output didn't match " "number of CPU(s)") # Check CPU frequency, frequency is under clock for ppc cpu_frequency_nodeinfo = _check_nodeinfo( nodeinfo_output, 'CPU frequency', 3) cmd = ("cat /proc/cpuinfo | grep -E 'cpu MHz|clock|BogoMIPS' | " "head -n1 | awk -F: '{print $2}' | awk -F. '{print $1}'") cmd_result = process.run(cmd, ignore_status=True, shell=True) cpu_frequency_os = cmd_result.stdout_text.strip() logging.debug("cpu_frequency_nodeinfo=%s cpu_frequency_os=%s", cpu_frequency_nodeinfo, cpu_frequency_os) # # Matching CPU Frequency is not an exact science in today's modern # processors and OS's. CPU's can have their execution speed varied # based on current workload in order to save energy and keep cool. # Thus since we're getting the values at disparate points in time, # we cannot necessarily do a pure comparison. # So, let's get the absolute value of the difference and ensure # that it's within 20 percent of each value to give us enough of # a "fudge" factor to declare "close enough". Don't return a failure # just print a debug message and move on. diffval = abs(int(cpu_frequency_nodeinfo) - int(cpu_frequency_os)) if (float(diffval) / float(cpu_frequency_nodeinfo) > 0.20 or float(diffval) / float(cpu_frequency_os) > 0.20): logging.debug("Virsh nodeinfo output didn't match CPU " "frequency within 20 percent") # Get CPU topology from virsh capabilities xml cpu_topology = capability_xml.CapabilityXML()['cpu_topology'] logging.debug("Cpu topology in virsh capabilities output: %s", cpu_topology) # Check CPU socket(s) cpu_sockets_nodeinfo = int( _check_nodeinfo(nodeinfo_output, 'CPU socket(s)', 3)) # CPU socket(s) in virsh nodeinfo is Total sockets in each node, not # total sockets in the system, so get total sockets in one node and # check with it node_info = utils_misc.NumaInfo() node_online_list = node_info.get_online_nodes() cmd = "cat /sys/devices/system/node/node%s" % node_online_list[0] cmd += "/cpu*/topology/physical_package_id | uniq |wc -l" cmd_result = process.run(cmd, ignore_status=True, shell=True) total_sockets_in_node = int(cmd_result.stdout_text.strip()) if total_sockets_in_node != cpu_sockets_nodeinfo: test.fail("Virsh nodeinfo output didn't match CPU " "socket(s) of host OS") if cpu_sockets_nodeinfo != int(cpu_topology['sockets']): test.fail("Virsh nodeinfo output didn't match CPU " "socket(s) of virsh capabilities output") # Check Core(s) per socket cores_per_socket_nodeinfo = _check_nodeinfo( nodeinfo_output, 'Core(s) per socket', 4) cmd = "lscpu | grep 'Core(s) per socket' | head -n1 | awk '{print $4}'" cmd_result = process.run(cmd, ignore_status=True, shell=True) cores_per_socket_os = cmd_result.stdout_text.strip() spec_numa = False if not re.match(cores_per_socket_nodeinfo, cores_per_socket_os): # for spec NUMA arch, the output of nodeinfo is in a spec format cpus_os = cpu.get_cpu_info().get("CPU(s)") numa_cells_nodeinfo = _check_nodeinfo( nodeinfo_output, 'NUMA cell(s)', 3) if (re.match(cores_per_socket_nodeinfo, cpus_os) and re.match(numa_cells_nodeinfo, "1")): spec_numa = True else: test.fail("Virsh nodeinfo output didn't match " "CPU(s) or Core(s) per socket of host OS") if cores_per_socket_nodeinfo != cpu_topology['cores']: test.fail("Virsh nodeinfo output didn't match Core(s) " "per socket of virsh capabilities output") # Check Thread(s) per core threads_per_core_nodeinfo = _check_nodeinfo(nodeinfo_output, 'Thread(s) per core', 4) if not spec_numa: if threads_per_core_nodeinfo != cpu_topology['threads']: test.fail("Virsh nodeinfo output didn't match" "Thread(s) per core of virsh" "capabilities output") else: if threads_per_core_nodeinfo != "1": test.fail("Virsh nodeinfo output didn't match" "Thread(s) per core of virsh" "capabilities output") # Check Memory size memory_size_nodeinfo = int( _check_nodeinfo(nodeinfo_output, 'Memory size', 3)) memory_size_os = 0 if libvirt_version.version_compare(2, 0, 0): for i in node_online_list: node_memory = node_info.read_from_node_meminfo(i, 'MemTotal') memory_size_os += int(node_memory) else: memory_size_os = utils_memory.memtotal() logging.debug('The host total memory from nodes is %s', memory_size_os) if memory_size_nodeinfo != memory_size_os: test.fail("Virsh nodeinfo output didn't match " "Memory size") # Prepare libvirtd service if "libvirtd" in params: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case option = params.get("virsh_node_options") cmd_result = virsh.nodeinfo(ignore_status=True, extra=option) logging.info("Output:\n%s", cmd_result.stdout.strip()) logging.info("Status: %d", cmd_result.exit_status) logging.error("Error: %s", cmd_result.stderr.strip()) output = cmd_result.stdout.strip() status = cmd_result.exit_status # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off" and libvirt_version.version_compare(5, 6, 0): logging.info("From libvirt version 5.6.0 libvirtd is restarted " "and command should succeed") else: test.fail("Command 'virsh nodeinfo %s' succeeded" "(incorrect command)" % option) elif status_error == "no": output_check(output) if status != 0: test.fail("Command 'virsh nodeinfo %s' failed " "(correct command)" % option)
def run(test, params, env): """ Test command: virsh domxml-to-native. Convert domain XML config to a native guest configuration format. 1.Prepare test environment. 2.When the libvirtd == "off", stop the libvirtd service. 3.Perform virsh domxml-from-native operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(params["main_vm"]) vm.verify_alive() def buildcmd(arglist): """ Return a list of arguments of qemu command. Return a list based on the input string where each list element is put together with care to pair up options with their argument rather than being on separate lines. Thus rather than having "-option" "argument" in separate list elements, they will be in one element "-option argument". Take care to note the argument to an option may not be required. This will make it easier to determine what is causing the failure when printing error messages. """ # First separate everything by the first space into a list elems = arglist.split("\x20") # Peruse the list to build up a formatted output retlist retlist = [] i = 0 skip = False for e in elems: # If 'skip' is True, then we've appended an option and argument if skip: skip = False i = i + 1 continue # Need a peek at the next element enext = elems[i + 1] # If current and next element starts with "-", then the # is not an argument to the current, thus we just append. # Same for anything we find that doesn't start with a "-" if (e[0] == "-" and enext[0] == "-") or e[0] != "-": retlist.append(e) else: # Append this and the next and set our skip flag retlist.append(e + " " + enext) skip = True i = i + 1 # Now build a list where the return retlist def filtlist(arglist): """ Return a filtered list of arguments. Walk through the supplied list to filter out things that will be known to be different depending on the running environment. """ retlist = [] for arg in arglist: if re.search("mode=readline", arg): continue elif re.search("mac=", arg): continue elif re.search("127.0.0.1:", arg): continue elif re.search("tap", arg): continue # Upstream libvirt commit id 'e8400564': # XMLToNative: Don't show -S elif re.search("-S", arg): continue retlist.append(arg) return retlist def compare(conv_arg): """ Compare converted information with vm's information. :param conv_arg : Converted information. :return: True if converted information has no different from vm's information. """ pid = vm.get_pid() cmdline_tmp = utils.system_output("cat -v /proc/%d/cmdline" % pid) # Output has a trailing '^@' which gets converted into an empty # element when spliting by '\x20', so strip it on the end. cmdline = re.sub(r"\^@", " ", cmdline_tmp).strip(" ") # Fedora 19 replaces the /usr/bin/qemu-kvm with the string # "/usr/bin/qemu-system-x86_64 -machine accel=kvm", so let's # do the same if we find "/usr/bin/qemu-kvm" in the incoming # argument list and we find "qemu-system-x86_64 -machine accel=kvm" # in the running guest's cmdline if ( conv_arg.find("/usr/bin/qemu-kvm") != 1 and cmdline.find("/usr/bin/qemu-system-x86_64 -machine accel=kvm") != -1 ): cmdline = re.sub(r"/usr/bin/qemu-system-x86_64 -machine accel=kvm", "/usr/bin/qemu-kvm", cmdline) # Now prepend the various environment variables that will be in # the conv_arg, but not in the actual command tmp = ( re.search("LC_ALL.[^\s]\s", conv_arg).group(0) + re.search("PATH.[^\s]+\s", conv_arg).group(0) + re.search("QEMU_AUDIO_DRV.[^\s]+\s", conv_arg).group(0) ) qemu_arg = tmp + cmdline conv_arg_lines = buildcmd(conv_arg) qemu_arg_lines = buildcmd(qemu_arg) diff1 = filtlist(tuple(x for x in conv_arg_lines if x not in set(qemu_arg_lines))) if diff1: logging.debug("Found the following in conv_arg not in qemu_arg:") for elem in diff1: logging.debug("\t%s", elem) diff2 = filtlist(tuple(x for x in qemu_arg_lines if x not in set(conv_arg_lines))) if diff2: logging.debug("Found the following in qemu_arg not in conv_arg:") for elem in diff2: logging.debug("\t%s", elem) if diff1 or diff2: return False return True # run test case dtn_format = params.get("dtn_format") file_xml = params.get("dtn_file_xml") extra_param = params.get("dtn_extra_param") libvirtd = params.get("libvirtd") status_error = params.get("status_error") virsh.dumpxml(vm_name, extra="", to_file=file_xml) if libvirtd == "off": utils_libvirtd.libvirtd_stop() ret = virsh.domxml_to_native(dtn_format, file_xml, extra_param, ignore_status=True) status = ret.exit_status conv_arg = ret.stdout.strip() # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # clean up if os.path.exists(file_xml): os.remove(file_xml) # 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: raise error.TestFail("Run failed with right command") if compare(conv_arg) is not True: raise error.TestFail("Test failed!")
def run_virsh_managedsave(test, params, env): """ Test command: virsh managedsave. This command can save and destroy a running domain, so it can be restarted from the same state at a later time. """ vm_name = params.get("main_vm") vm = env.get_vm(params["main_vm"]) #define function def vm_recover_check(guest_name): """ Check if the vm can be recovered correctly. @param: guest_name : Checked vm's name. """ ret = virsh.dom_list() #This time vm should not be in the list if re.search(guest_name, ret.stdout): raise error.TestFail("virsh list output invalid") virsh.start(guest_name) if params.get("paused_after_start_vm") == "yes": virsh.resume(guest_name, ignore_status=True) #This time vm should be in the list ret = virsh.dom_list() if not re.search(guest_name, ret.stdout): raise error.TestFail("virsh list output invalid") domid = vm.get_id() domuuid = vm.get_uuid() libvirtd = params.get("managedsave_libvirtd", "on") #run test case vm_ref = params.get("managedsave_vm_ref") if vm_ref == "id": vm_ref = domid elif vm_ref == "uuid": vm_ref = domuuid elif vm_ref == "hex_id": vm_ref = hex(int(domid)) elif vm_ref == "managedsave_invalid_id" or\ vm_ref == "managedsave_invalid_uuid": vm_ref = params.get(vm_ref) elif vm_ref == "name" or vm_ref == "extra_parame": vm_ref = "%s %s" % (vm_name, params.get("managedsave_extra_parame")) #stop the libvirtd service if libvirtd == "off": utils_libvirtd.libvirtd_stop() #Ignore exception with "ignore_status=True" ret = virsh.managedsave(vm_ref, ignore_status=True) status = ret.exit_status #recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() #check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: if not virsh.has_command_help_match('managedsave', r'\s+--running\s+'): # Older libvirt does not have --running parameter raise error.TestNAError( "Older libvirt does not handle arguments consistently") else: raise error.TestFail("Run successfully with wrong command!") elif status_error == "no": if status != 0: raise error.TestFail("Run failed with right command") vm_recover_check(vm_name)
def run_virsh_nodememstats(test, params, env): """ Test the command virsh nodememstats (1) Call the virsh nodememstats command (2) Get the output (3) Check the against /proc/meminfo output (4) Call the virsh nodememstats command with an unexpected option (5) Call the virsh nodememstats command with libvirtd service stop """ # Initialize the variables expected = {} actual = {} deltas = [] name_stats = ['total', 'free', 'buffers', 'cached'] itr = int(params.get("itr")) def virsh_check_nodememtats(actual_stats, expected_stats, delta): """ Check the nodememstats output value with /proc/meminfo value """ delta_stats = {} for name in name_stats: delta_stats[name] = abs(actual_stats[name] - expected_stats[name]) if 'total' in name: if not delta_stats[name] == 0: raise error.TestFail("Command 'virsh nodememstats' not" " succeeded as the value for %s is " "deviated by %d\nThe total memory " "value is deviating-check" % (name, delta_stats[name])) else: if delta_stats[name] > delta: raise error.TestFail("Command 'virsh nodememstats' not " "succeeded as the value for %s" " is deviated by %d" % (name, delta_stats[name])) return delta_stats # Prepare libvirtd service check_libvirtd = params.has_key("libvirtd") if check_libvirtd: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Get the option for the test case option = params.get("virsh_nodememstats_options") # Run test case for 10 iterations # (default can be changed in subtests.cfg file) # and print the final statistics for i in range(itr): output = virsh.nodememstats(option) # Get the status of the virsh command executed status = output.exit_status # Get status_error option for the test case status_error = params.get("status_error") if status_error == "yes": if status == 0: if libvirtd == "off": utils_libvirtd.libvirtd_start() raise error.TestFail("Command 'virsh nodememstats' " "succeeded with libvirtd service" " stopped, incorrect") else: raise error.TestFail("Command 'virsh nodememstats %s' " "succeeded (incorrect command)" % option) elif status_error == "no": if status == 0: # From the beginning of a line, group 1 is one or # more word-characters, followed by zero or more # whitespace characters and a ':', then one or # more whitespace characters, followed by group 2, # which is one or more digit characters, # then one or more whitespace characters followed by # a literal 'kB' or 'KiB' sequence, e.g as below # total : 3809340 kB # total : 3809340 KiB # Normalise the value to MBs regex_obj = re.compile(r"^(\w+)\s*:\s+(\d+)\s\w+") expected = {} for line in output.stdout.split('\n'): match_obj = regex_obj.search(line) # Due to the extra space in the list if match_obj is not None: name = match_obj.group(1) value = match_obj.group(2) expected[name] = int(value) / 1024 # Get the actual value from /proc/meminfo and normalise to MBs actual['total'] = int(utils_memory.memtotal()) / 1024 actual['free'] = int(utils_memory.freememtotal()) / 1024 actual['buffers'] = int( utils_memory.read_from_meminfo('Buffers')) / 1024 actual['cached'] = int( utils_memory.read_from_meminfo('Cached')) / 1024 # Currently the delta value is kept at 200 MB this can be # tuned based on the accuracy # Check subtests.cfg for more details delta = int(params.get("delta")) output = virsh_check_nodememtats(actual, expected, delta) deltas.append(output) else: raise error.TestFail("Command virsh nodememstats %s not " "succeeded:\n%s" % (option, status)) # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Print the deviated values for all iterations if status_error == "no": logging.debug("The following is the deviations from " "the actual(/proc/meminfo) and expected" " value(output of virsh nodememstats)") for i in range(itr): logging.debug("iteration %d:", i) for index, name in enumerate(name_stats): logging.debug("%19s : %d", name, deltas[i][name])
def run(test, params, env): """ Test command: virsh start. 1) Get the params from params. 2) Prepare libvirtd's status. 3) Do the start operation. 4) Result check. 5) clean up. """ # get the params from params vm_name = params.get("main_vm", "avocado-vt-vm1") vm_ref = params.get("vm_ref", "vm1") opt = params.get("vs_opt", "") # Backup for recovery. vmxml_backup = libvirt_xml.vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) backup_name = vm_ref vm = None if vm_ref is not "": vm = env.get_vm(vm_ref) vmxml = libvirt_xml.VMXML() libvirtd_state = params.get("libvirtd", "on") pre_operation = params.get("vs_pre_operation", "") status_error = params.get("status_error", "no") try: # prepare before start vm if libvirtd_state == "on": utils_libvirtd.libvirtd_start() elif libvirtd_state == "off": utils_libvirtd.libvirtd_stop() if pre_operation == "rename": new_vm_name = params.get("vs_new_vm_name", "virsh_start_vm1") vm = libvirt_xml.VMXML.vm_rename(vm, new_vm_name) vm_ref = new_vm_name elif pre_operation == "undefine": vmxml = vmxml.new_from_dumpxml(vm_ref) vmxml.undefine() # do the start operation try: if pre_operation == "remote": # get the params for remote test remote_ip = params.get("remote_ip", "ENTER.YOUR.REMOTE.IP") remote_user = params.get("remote_user", "root") remote_pwd = params.get("remote_pwd", "ENTER.YOUR.REMOTE.PASSWORD") if pre_operation == "remote" and remote_ip.count( "ENTER.YOUR."): test.cancel("Remote test parameters not configured") ssh_key.setup_ssh_key(remote_ip, remote_user, remote_pwd) remote_uri = "qemu+ssh://%s/system" % remote_ip cmd_result = virsh.start(vm_ref, ignore_status=True, debug=True, uri=remote_uri) if cmd_result.exit_status: test.fail("Start vm failed.\n Detail: %s" % cmd_result) elif opt.count("console"): # With --console, start command will print the # dmesg of guest in starting and turn into the # login prompt. In this case, we start it with # --console and login vm in console by # remote.handle_prompts(). cmd = "start %s --console" % vm_ref virsh_session = virsh.VirshSession(virsh_exec=virsh.VIRSH_EXEC, auto_close=True) virsh_session.sendline(cmd) remote.handle_prompts(virsh_session, params.get("username", ""), params.get("password", ""), r"[\#\$]\s*$", timeout=60, debug=True) elif opt.count("autodestroy"): # With --autodestroy, vm will be destroyed when # virsh session closed. Then we execute start # command in a virsh session and start vm with # --autodestroy. Then we closed the virsh session, # and check the vm is destroyed or not. virsh_session = virsh.VirshSession(virsh_exec=virsh.VIRSH_EXEC, auto_close=True) cmd = "start %s --autodestroy" % vm_ref status = virsh_session.cmd_status(cmd) if status: test.fail("Failed to start vm with --autodestroy.") # Close the session, then the vm should be destroyed. virsh_session.close() elif opt.count("force-boot"): # With --force-boot, VM will be stared from boot # even we have saved it with virsh managedsave. # In this case, we start vm and execute sleep 1000&, # then save it with virsh managedsave. At last, we # start vm with --force-boot. To verify the result, # we check the sleep process. If the process exists, # force-boot failed, else case pass. vm.start() session = vm.wait_for_login() status = session.cmd_status("sleep 1000&") if status: test.error("Can not execute command in guest.") sleep_pid = session.cmd_output("echo $!").strip() virsh.managedsave(vm_ref) virsh.start(vm_ref, options=opt) else: cmd_result = virsh.start(vm_ref, options=opt) if cmd_result.exit_status: if status_error == "no": test.fail("Start vm failed.\n Detail: %s" % cmd_result) else: # start vm successfully if status_error == "yes": if libvirtd_state == "off" and libvirt_version.version_compare( 5, 6, 0): logging.info( "From libvirt version 5.6.0 libvirtd is restarted," " command should succeed.") else: test.fail("Run successfully with wrong " "command!\n Detail:%s" % cmd_result) if opt.count("paused"): if not (vm.state() == "paused"): test.fail("VM is not paused when started with " "--paused.") elif opt.count("autodestroy"): if vm.is_alive(): test.fail("VM was started with --autodestroy," "but not destroyed when virsh session " "closed.") elif opt.count("force-boot"): session = vm.wait_for_login() status = session.cmd_status("ps %s |grep '[s]leep 1000'" % sleep_pid) if not status: test.fail("VM was started with --force-boot," "but it is restored from a" " managedsave.") else: if status_error == "no" and not vm.is_alive( ) and pre_operation != "remote": test.fail("VM was started but it is not alive.") except remote.LoginError as detail: test.fail("Failed to login guest.") finally: # clean up if libvirtd_state == "off": utils_libvirtd.libvirtd_start() elif pre_operation == "rename": libvirt_xml.VMXML.vm_rename(vm, backup_name) elif pre_operation == "remote": virsh.destroy(vm_ref, ignore_status=False, debug=True, uri=remote_uri) if vm and vm.is_paused(): vm.resume() # Restore VM vmxml_backup.sync()
def run(test, params, env): """ Test command: virsh destroy. The command can destroy (stop) a domain. 1.Prepare test environment. 2.When the ibvirtd == "off", stop the libvirtd service. 3.Perform virsh destroy operation. 4.Recover test environment. 5.Confirm the test result. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) domid = vm.get_id() domuuid = vm.get_uuid() vm_ref = params.get("destroy_vm_ref") status_error = params.get("status_error", "no") libvirtd = params.get("libvirtd", "on") remote_ip = params.get("remote_ip", "REMOTE.EXAMPLE.COM") remote_pwd = params.get("remote_pwd", None) local_ip = params.get("local_ip", "LOCAL.EXAMPLE.COM") local_pwd = params.get("local_pwd", "LOCAL.EXAMPLE.COM") if vm_ref == "remote" and (remote_ip.count("EXAMPLE.COM") or local_ip.count("EXAMPLE.COM")): raise error.TestNAError( "Remote test parameters unchanged from default") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' if not libvirt_version.version_compare(1, 1, 1): if params.get('setup_libvirt_polkit') == 'yes': raise error.TestNAError("API acl test not supported in current" " libvirt version.") 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("destroy_extra")) elif vm_ref == "uuid": vm_ref = domuuid if libvirtd == "off": utils_libvirtd.libvirtd_stop() if vm_ref != "remote": status = virsh.destroy(vm_ref, ignore_status=True, unprivileged_user=unprivileged_user, uri=uri, debug=True).exit_status output = "" else: 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') # Setup up remote to remote login in local host ssh_key.setup_remote_ssh_key(remote_ip, "root", remote_pwd, local_ip, "root", local_pwd) command = "virsh -c %s destroy %s" % (remote_uri, vm_name) status, output = session.cmd_status_output(command, internal_timeout=5) session.close() except error.CmdError: status = 1 if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_error == "yes": if status == 0: raise error.TestFail("Run successfully with wrong command! " "Output:\n%s" % output) elif status_error == "no": if status != 0: raise error.TestFail("Run failed with right command! Output:\n%s" % output)
def run(test, params, env): """ Test the command virsh uri (1) Call virsh uri (2) Call virsh -c remote_uri uri (3) Call virsh uri with an unexpected option (4) Call virsh uri with libvirtd service stop """ connect_uri = libvirt_vm.normalize_connect_uri( params.get("connect_uri", "default")) option = params.get("virsh_uri_options") target_uri = params.get("target_uri") remote_ref = params.get("uri_remote_ref", "") if target_uri: if target_uri.count('EXAMPLE.COM'): raise error.TestNAError( 'target_uri configuration set to sample value') logging.info("The target_uri: %s", target_uri) cmd = "virsh -c %s uri" % target_uri else: cmd = "virsh uri %s" % option # Prepare libvirtd service check_libvirtd = params.has_key("libvirtd") if check_libvirtd: libvirtd = params.get("libvirtd") if libvirtd == "off": utils_libvirtd.libvirtd_stop() # Run test case logging.info("The command: %s", cmd) try: if remote_ref == "remote": connect_uri = target_uri uri_test = virsh.canonical_uri(option, uri=connect_uri, ignore_status=False, debug=True) status = 0 # good except error.CmdError: status = 1 # bad uri_test = '' # Recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # Check status_error status_error = params.get("status_error") if status_error == "yes": if status == 0: raise error.TestFail("Command: %s succeeded " "(incorrect command)" % cmd) else: logging.info("command: %s is a expected error", cmd) elif status_error == "no": if cmp(target_uri, uri_test) != 0: raise error.TestFail("Virsh cmd uri %s != %s." % (uri_test, target_uri)) if status != 0: raise error.TestFail("Command: %s failed " "(correct command)" % cmd)