def create_virsh_instance(hypervisor, uri, remote_ip, remote_user, remote_pwd, debug=True): """ Create a virsh instance for all hypervisors(VMWARE, XEN, KVM) :param hypervisor: a hypervisor type :param uri: uri of libvirt instance to connect to :param remote_ip: Hostname/IP of remote system to ssh into (if any) :param remote_user: Username to ssh in as (if any) :param remote_pwd: Password to use, or None for host/pubkey :param debug: Whether to enable debug """ logging.debug("virsh connection info: uri=%s ip=%s", uri, remote_ip) if hypervisor == 'kvm': v2v_virsh = virsh else: virsh_dargs = { 'uri': uri, 'remote_ip': remote_ip, 'remote_user': remote_user, 'remote_pwd': remote_pwd, 'debug': debug } v2v_virsh = virsh.VirshPersistent(**virsh_dargs) return v2v_virsh
def __init__(self, test, params, env): self.errors = [] self.params = params self.vm_name = params.get('main_vm') self.original_vm_name = params.get('original_vm_name') # The expected boottype of guest, default 0 is 'i440fx+bios' # Other values are 1 for q35+bios, 2 for q35+uefi, 3 for # q35+secure_uefi self.boottype = int(params.get("boottype", 0)) self.hypervisor = params.get("hypervisor") self.target = params.get('target') self.os_type = params.get('os_type') self.os_version = params.get('os_version', 'OS_VERSION_V2V_EXAMPLE') self.original_vmxml = params.get('original_vmxml') self.vmx_nfs_src = params.get('vmx_nfs_src') self.virsh_session = None self.virsh_session_id = None self.setup_session() self.checker = utils_v2v.VMCheck(test, params, env) self.checker.virsh_session_id = self.virsh_session_id self.virsh_instance = virsh.VirshPersistent( session_id=self.virsh_session_id) self.vmxml = virsh.dumpxml( self.vm_name, session_id=self.virsh_session_id).stdout.strip() # Save NFS mount records like {0:(src, dst, fstype)} self.mount_records = {}
def run(test, params, env): """ Test virt-admin srv-clients-info 1) Change the clients related parameters in daemon config file; 2) Restart daemon; 3) Start several virsh connections; 4) Check whether the parameters value listed by srv-clients-info are the same with the above settings. """ max_clients = params.get("max_clients") max_anonymous_clients = params.get("max_anonymous_clients") server_name = params.get("server_name") num_clients = params.get("num_clients") local_pwd = params.get("local_pwd") if not server_name: server_name = virt_admin.check_server_name() config = virt_admin.managed_daemon_config() daemon = utils_libvirtd.Libvirtd() ssh_key.setup_remote_ssh_key("localhost", "root", local_pwd) try: config.max_clients = max_clients config.max_anonymous_clients = max_anonymous_clients daemon.restart() vp = virt_admin.VirtadminPersistent() virsh_instant = [] for _ in range(int(num_clients)): # Under split daemon mode, we can connect to virtproxyd via # remote connections,can not connect to virtproxyd direct # on local host virsh_instant.append( virsh.VirshPersistent(uri="qemu+ssh://localhost/system")) result = vp.srv_clients_info(server_name, ignore_status=True, debug=True) output = result.stdout.strip().splitlines() out_split = [item.split(':') for item in output] out_dict = dict([[item[0].strip(), item[1].strip()] for item in out_split]) if result.exit_status: test.fail("This operation should success " "but failed. Output:\n %s" % result) else: if not (out_dict["nclients_max"] == max_clients and out_dict["nclients_unauth_max"] == max_anonymous_clients): test.fail("attributes info listed by " "srv-clients-info is not correct.") if not out_dict["nclients"] == num_clients: test.fail("the number of clients connect to daemon " "is not correct.") finally: config.restore() daemon.restart()
def set_virsh_instance(self): """ Create a virsh instance for migration. TODO: support remote instance VirshConnectBack """ # rs_dargs = {'remote_ip': remote_host, 'remote_user': host_user, # 'remote_pwd': host_passwd, 'uri': srcuri} #rvirsh = virsh.VirshConnectBack(**rs_dargs) self.virsh_instance = virsh.VirshPersistent()
def create_destroy_pool_on_remote(test, action, params): """ This is to create or destroy a specified pool on remote. :param action: "create" or "destroy" :type str :param params: a dict for parameters :type dict :return: True if successful, otherwise False :rtype: Boolean """ remote_ip = params.get("migrate_dest_host") remote_user = params.get("migrate_dest_user", "root") remote_pwd = params.get("migrate_dest_pwd") virsh_dargs = { 'remote_ip': remote_ip, 'remote_user': remote_user, 'remote_pwd': remote_pwd, 'unprivileged_user': None, 'ssh_remote_auth': True } new_session = virsh.VirshPersistent(**virsh_dargs) pool_name = params.get("precreation_pool_name", "tmp_pool_1") timeout = params.get("timeout", 60) prompt = params.get("prompt", r"[\#\$]\s*$") if action == 'create': # Firstly check if the pool already exists all_pools = new_session.pool_list(option="--all") logging.debug("Pools on remote host:\n%s", all_pools) if all_pools.stdout.find(pool_name) >= 0: logging.debug( "The pool %s already exists and skip " "to create it.", pool_name) new_session.close_session() return True pool_type = params.get("precreation_pool_type", "dir") pool_target = params.get("precreation_pool_target") cmd = "mkdir -p %s" % pool_target session = remote.wait_for_login("ssh", remote_ip, 22, remote_user, remote_pwd, prompt) status, output = session.cmd_status_output(cmd, timeout) session.close() if status: new_session.close_session() test.fail("Run '%s' on remote host '%s' failed: %s." % (cmd, remote_ip, output)) ret = new_session.pool_create_as(pool_name, pool_type, pool_target) else: # suppose it is to destroy ret = new_session.pool_destroy(pool_name) new_session.close_session() return ret
def create_or_del_network(net_dict, is_del=False, remote_args=None): """ Create or delete network on local or remote :param net_dict: Dictionary with the network parameters :param is_del: Whether the networks should be deleted :param remote_args: The parameters for remote """ remote_virsh_session = None if remote_args: remote_virsh_session = virsh.VirshPersistent(**remote_args) if not is_del: net_dev = libvirt.create_net_xml(net_dict.get("net_name"), net_dict) if not remote_virsh_session: if net_dev.get_active(): net_dev.undefine() net_dev.define() net_dev.start() else: remote_ip = remote_args.get("remote_ip") remote_user = remote_args.get("remote_user") remote_pwd = remote_args.get("remote_pwd") if not all([remote_ip, remote_user, remote_pwd]): raise exceptions.TestError( "remote_[ip|user|pwd] are necessary!") remote.scp_to_remote(remote_ip, '22', remote_user, remote_pwd, net_dev.xml, net_dev.xml, limit="", log_filename=None, timeout=600, interface=None) remote_virsh_session.net_define(net_dev.xml, debug=True) remote_virsh_session.net_start(net_dict.get("net_name"), debug=True) remote.run_remote_cmd("rm -rf %s" % net_dev.xml, remote_args) else: virsh_session = virsh if remote_virsh_session: virsh_session = remote_virsh_session if net_dict.get("net_name") in virsh_session.net_state_dict(): virsh_session.net_destroy(net_dict.get("net_name"), debug=True, ignore_status=True) virsh_session.net_undefine(net_dict.get("net_name"), debug=True, ignore_status=True) if remote_virsh_session: remote_virsh_session.close_session()
def run_domcap_in_guest(virsh_dargs): """ Execute 'virsh domcapabilities' within the guest :param virsh_dargs: dict, parameters used """ remote_session = None try: remote_session = virsh.VirshPersistent(**virsh_dargs) remote_session.domcapabilities(ignore_status=False) finally: if remote_session: remote_session.close_session()
def run_virsh_net_info(test, params, env): """ Test command: virsh net-info <network> The command returns basic information about virtual network. """ # Gather test parameters uri = libvirt_vm.normalize_connect_uri(params.get("connect_uri", "default")) status_error = params.get("status_error", "no") net_name = params.get("testing_net_name", "default") net_ref = params.get("netinfo_net_ref", "name") extra = params.get("netinfo_options_extra", "") virsh_dargs = {'uri': uri, 'debug': True, 'ignore_status': True} virsh_instance = virsh.VirshPersistent(**virsh_dargs) # Get all network instance origin_nets = network_xml.NetworkXML.new_all_networks_dict(virsh_instance) # Prepare network for following test. try: netxml = origin_nets[net_name] except KeyError: virsh_instance.close_session() raise error.TestNAError("'%s' virtual network doesn't exist." % net_name) if net_ref == "name": net_ref = netxml.name elif net_ref == "uuid": net_ref = netxml.uuid elif net_ref.find("invalid") != -1: net_ref = params.get(net_ref) # Run test case result = virsh.net_info(net_ref, extra, **virsh_dargs) status = result.exit_status output = result.stdout.strip() err = result.stderr.strip() virsh_instance.close_session() # 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 virt-admin srv-clients-info 1) Change the clients related parameters in libvirtd.conf; 2) Restart libvirtd daemon; 3) Start several virsh connections; 4) Check whether the parameters value listed by srv-clents-info are the same with the above settings. """ max_clients = params.get("max_clients") max_anonymous_clients = params.get("max_anonymous_clients") server_name = params.get("server_name") num_clients = params.get("num_clients") config = utils_config.LibvirtdConfig() libvirtd = utils_libvirtd.Libvirtd() try: config.max_clients = max_clients config.max_anonymous_clients = max_anonymous_clients libvirtd.restart() vp = virt_admin.VirtadminPersistent() virsh_instant = [] for _ in range(int(num_clients)): virsh_instant.append(virsh.VirshPersistent(uri="qemu:///system")) result = vp.srv_clients_info(server_name, ignore_status=True, debug=True) output = result.stdout.strip().splitlines() out_split = [item.split(':') for item in output] out_dict = dict([[item[0].strip(), item[1].strip()] for item in out_split]) if result.exit_status: raise exceptions.TestFail("This operation should success " "but failed. Output:\n %s" % result) else: if not (out_dict["nclients_max"] == max_clients and out_dict["nclients_unauth_max"] == max_anonymous_clients): raise exceptions.TestFail("attributes info listed by " "srv-clients-info is not correct.") if not out_dict["nclients"] == num_clients: raise exceptions.TestFail( "the number of clients connect to libvirtd " "is not correct.") finally: config.restore() libvirtd.restart()
def check_domjobinfo(vm, params, option="", remote_virsh_dargs=None): """ Check given item in domjobinfo of the guest is as expected :param vm: the vm object :param params: the parameters used :param option: options for domjobinfo :param remote_virsh_dargs: the parameters for remote host :raise: exceptions.TestFail if the value of given item is unexpected """ def _search_jobinfo(jobinfo, ignore_status=False): """ Find value of given item in domjobinfo :param jobinfo: cmdResult object :param ignore_status: False to raise Error, True to ignore :raise: exceptions.TestFail if not found """ for item in jobinfo.stdout.splitlines(): if item.count(jobinfo_item): groups = re.findall(r'[0-9.]+', item.strip()) logging.debug("In '%s' search '%s'\n", item, groups[0]) if (math.fabs(float(groups[0]) - float(compare_to_value)) // float(compare_to_value) > diff_rate): err_msg = ("{} {} has too much difference from " "{}".format(jobinfo_item, groups[0], compare_to_value)) if ignore_status: logging.error(err_msg) else: raise exceptions.TestFail(err_msg) break jobinfo_item = params.get("jobinfo_item") compare_to_value = params.get("compare_to_value") ignore_status = params.get("domjob_ignore_status", False) logging.debug("compare_to_value:%s", compare_to_value) diff_rate = float(params.get("diff_rate", "0")) if not jobinfo_item or not compare_to_value: return jobinfo = virsh.domjobinfo(vm.name, option, debug=True) _search_jobinfo(jobinfo, ignore_status) check_domjobinfo_remote = params.get("check_domjobinfo_remote") if check_domjobinfo_remote and remote_virsh_dargs: remote_virsh_session = virsh.VirshPersistent(**remote_virsh_dargs) jobinfo = remote_virsh_session.domjobinfo(vm.name, option, debug=True) _search_jobinfo(jobinfo, ignore_status) remote_virsh_session.close_session()
def check_multi_netcards(mac_list, virsh_session_id): """ Check if number and type of network cards meet expectation """ virsh_instance = virsh.VirshPersistent(session_id=virsh_session_id) vmxml = vm_xml.VMXML.new_from_inactive_dumpxml( vm_name, virsh_instance=virsh_instance) iflist = vmxml.get_iface_all() logging.debug('MAC list before v2v: %s' % mac_list) logging.debug('MAC list after v2v: %s' % iflist.keys()) if set(mac_list).difference(iflist.keys()): raise exceptions.TestFail('Missing network interface') for mac in iflist: if iflist[mac].find('model').get('type') != 'virtio': raise exceptions.TestFail('Network not convert to virtio')
def run_domcap_in_guest(virsh_dargs): """ Execute 'virsh domcapabilities' within the guest :param virsh_dargs: dict, parameters used :return: CmdResult object, the execution result of the command """ remote_session = None try: remote_session = virsh.VirshPersistent(**virsh_dargs) cmd_result = remote_session.domcapabilities(ignore_status=False) finally: if remote_session: remote_session.close_session() return cmd_result
def check_migration_timeout_suspend(params): """ Handle option '--timeout --timeout-suspend'. As the migration thread begins to execute, this function is executed at same time almostly. It will sleep the specified seconds and check the VM state on both hosts. Both should be 'paused'. :param params: The parameters used :raise: exceptions.TestFail if the VM state is not as expected """ timeout = int(params.get("timeout_before_suspend", 5)) server_ip = params.get("server_ip") server_user = params.get("server_user", "root") server_pwd = params.get("server_pwd") vm_name = params.get("migrate_main_vm") vm = params.get("vm_migration") logging.debug("Wait for %s seconds as specified by --timeout", timeout) # --timeout <seconds> --timeout-suspend means the vm state will change # to paused when live migration exceeds <seconds>. Here migration # command is executed on a separate thread asynchronously, so there # may need seconds to run the thread and other helper function logic # before virsh migrate command is executed. So a buffer is suggested # to be added to avoid of timing gap. '1' second is a usable choice. time.sleep(timeout + 1) logging.debug("Check vm state on source host after timeout") vm_state = vm.state() if vm_state != "paused": raise exceptions.TestFail( "After timeout '%s' seconds, " "the vm state on source host should " "be 'paused', but %s found", timeout, vm_state) logging.debug("Check vm state on target host after timeout") virsh_dargs = { 'remote_ip': server_ip, 'remote_user': server_user, 'remote_pwd': server_pwd, 'unprivileged_user': None, 'ssh_remote_auth': True } new_session = virsh.VirshPersistent(**virsh_dargs) vm_state = new_session.domstate(vm_name).stdout.strip() if vm_state != "paused": raise exceptions.TestFail( "After timeout '%s' seconds, " "the vm state on target host should " "be 'paused', but %s found", timeout, vm_state) new_session.close_session()
def setup_session(self): for index in range(RETRY_TIMES): logging.info('Trying %d times', index + 1) try: if self.target == "ovirt": self.virsh_session = utils_sasl.VirshSessionSASL(self.params) self.virsh_session_id = self.virsh_session.get_id() else: self.virsh_session = virsh.VirshPersistent() self.virsh_session_id = self.virsh_session.session_id except Exception as detail: logging.error(detail) else: break if not self.virsh_session_id: raise exceptions.TestError('Fail to create SASL virsh session')
def __init__(self, persistent=False, virsh_dargs=None): """ Initialize instance's internal virsh interface from virsh_dargs @param: persistent: Use persistent virsh connection for this instance @param: virsh_dargs: virsh module Virsh class dargs API keywords """ if virsh_dargs is None: virsh_dargs = {} # avoid additional conditionals below if persistent: self.super_set('__virsh__', virsh.VirshPersistent(**virsh_dargs)) else: self.super_set('__virsh__', virsh.Virsh(**virsh_dargs)) # Don't define any initial property values super(LibvirtXMLBase, self).__init__()
def create_destroy_pool_on_remote(action, params): """ This is to create or destroy a specified pool on remote. :param action: "create" or "destory" :type str :param params: a dict for parameters :type dict :return: True if successful, otherwise False :rtype: Boolean """ remote_ip = params.get("migrate_dest_host") remote_user = params.get("migrate_dest_user", "root") remote_pwd = params.get("migrate_dest_pwd") virsh_dargs = { 'remote_ip': remote_ip, 'remote_user': remote_user, 'remote_pwd': remote_pwd, 'unprivileged_user': None, 'ssh_remote_auth': True } new_session = virsh.VirshPersistent(**virsh_dargs) pool_name = params.get("precreation_pool_name", "tmp_pool_1") timeout = params.get("timeout", 60) prompt = params.get("prompt", r"[\#\$]\s*$") if action == 'create': pool_type = params.get("precreation_pool_type", "dir") pool_target = params.get("precreation_pool_target") cmd = "mkdir -p %s" % pool_target session = remote.wait_for_login("ssh", remote_ip, 22, remote_user, remote_pwd, prompt) status, output = session.cmd_status_output(cmd, timeout) session.close() if status: new_session.close_session() raise error.TestFail("Run '%s' on remote host '%s' failed: %s." % (cmd, remote_ip, output)) ret = new_session.pool_create_as(pool_name, pool_type, pool_target) else: # suppose it is to destroy ret = new_session.pool_destroy(pool_name) new_session.close_session() return ret
def chk_connect_to_daemon(connect_able): try: virsh_instance.append(virsh.VirshPersistent(**remote_virsh_dargs)) except Exception as info: if connect_able == "yes": test.fail("Connection to daemon is not success, error:\n %s" % info) else: logging.info("Connections to daemon should not success, " "this is a correct test result!") else: if connect_able == "yes": logging.info("Connections to daemon is successful, " "this is a correct test result!") else: test.fail("error: Connection to daemon should not success! " "Check the attributes.")
def __init__(self, test, params, env): self.errors = [] self.params = params self.vm_name = params.get('main_vm') self.hypervisor = params.get("hypervisor") self.target = params.get('target') self.os_type = params.get('os_type') self.os_version = params.get('os_version', 'OS_VERSION_V2V_EXAMPLE') self.original_vmxml = params.get('original_vmxml') self.virsh_session = None self.virsh_session_id = None self.setup_session() self.checker = utils_v2v.VMCheck(test, params, env) self.checker.virsh_session_id = self.virsh_session_id self.virsh_instance = virsh.VirshPersistent(session_id=self.virsh_session_id) self.vmxml = virsh.dumpxml(self.vm_name, session_id=self.virsh_session_id).stdout.strip()
def check_virsh_connect_alive(test, params): virsh_instance = virsh.VirshPersistent() try: virsh_instance.dom_list(debug=True) ret = virsh_instance.connect("test", debug=True, ignore_status=True) # Return value should be an error if ret.exit_status: # But, there is no output in stderr, all output is in stdout if not ret.stderr: # Therefore copy stdout to stderr to check by check_result ret.stderr = ret.stdout utlv.check_result(ret, expected_fails=[params['expected_result_patt']]) virsh_instance.dom_list(debug=True) virsh_instance.connect(debug=True) virsh_instance.dom_list(debug=True) except Exception as e: test.fail('Unexpected failure: {}'.format(e))
def create_secret(sec_dict, remote_args=None): """ Create a secret with 'virsh secret-define' :param sec_dict: dict to create secret :param remote_args: Parameters for remote host :return: UUID of the secret Example: secret_dict = {'secret_ephemeral': 'no', 'secret_private': 'yes', 'description': 'secret desc', 'usage': 'volume', 'volume': '/path/to/volume'} sec_uuid = libvirt_secret.create_secret(sec_dict=secret_dict) """ sec_xml = secret_xml.SecretXML() sec_xml.setup_attrs(**sec_dict) sec_xml.xmltreefile.write() # define the secret and get its uuid if remote_args: server_ip = remote_args.get("remote_ip", "") server_user = remote_args.get("remote_user", "") server_pwd = remote_args.get("remote_pwd", "") if not all([server_ip, server_user, server_pwd]): raise exceptions.TestError("remote_[ip|user|pwd] are necessary!") remote_virsh_session = virsh.VirshPersistent(**remote_args) remote.scp_to_remote(server_ip, '22', server_user, server_pwd, sec_xml.xml, sec_xml.xml, limit="", log_filename=None, timeout=600, interface=None) ret = remote_virsh_session.secret_define(sec_xml.xml) remote_virsh_session.close_session() else: ret = virsh.secret_define(sec_xml.xml) libvirt.check_exit_status(ret) try: sec_uuid = re.findall(r".+\S+(\ +\S+)\ +.+\S+", ret.stdout_text)[0].lstrip() except IndexError: raise exceptions.TestError("Fail to get newly created secret uuid") return sec_uuid
def chk_connect_to_libvirtd(connect_able): try: virsh_instance.append(virsh.VirshPersistent(uri='qemu:///system')) except Exception as info: if connect_able == "yes": test.fail( "Connection to libvirtd is not success, error:\n %s" % info) else: logging.info("Connections to libvirtd should not success, " "this is a correct test result!") else: if connect_able == "yes": logging.info("Connections to libvirtd is successful, " "this is a correct test result!") else: test.fail("error: Connection to libvirtd should not success! " "Check the attributes.")
def check_timeout_postcopy(params): """ Check the vm state on target host after timeout when --postcopy and --timeout-postcopy are used. The vm state is expected as running. :param params: the parameters used """ timeout = int(params.get("timeout_postcopy", 10)) time.sleep(timeout + 1) remote_virsh_session = virsh.VirshPersistent(**remote_virsh_dargs) vm_state = results_stdout_52lts(remote_virsh_session.domstate(vm_name)).strip() if vm_state != "running": remote_virsh_session.close_session() test.fail("After timeout '%s' seconds, " "the vm state on target host should " "be 'running', but '%s' found" % (timeout, vm_state)) remote_virsh_session.close_session()
def verify_test_mem_balloon(vm, params, test): """ Verify steps for memory balloon device :param vm: VM object :param params: dict, test parameters :param test: test object """ remote_ip = params.get("remote_ip") remote_user = params.get("remote_user") remote_pwd = params.get("remote_pwd") remote_virsh_dargs = { 'remote_ip': remote_ip, 'remote_user': remote_user, 'remote_pwd': remote_pwd, 'unprivileged_user': None, 'ssh_remote_auth': True } ballooned_mem = params.get("ballooned_mem") vm_name = params.get("migrate_main_vm") virsh_args = {"debug": True} remote_virsh_session = virsh.VirshPersistent(**remote_virsh_dargs) remote_virsh_session.setmem(vm_name, ballooned_mem, None, None, False, "", **virsh_args) def check_mem_balloon(): """Check if memory balloon worked""" memstat_ouput = remote_virsh_session.dommemstat( vm_name, "", **virsh_args) memstat_after = memstat_ouput.stdout_text mem_after = memstat_after.splitlines()[0].split()[1] if mem_after != ballooned_mem: test.log.debug("Current memory size is: %s", mem_after) return False return True check_ret = utils_misc.wait_for(check_mem_balloon, timeout=20) if not check_ret: test.fail("Memory is not ballooned to the expected size: %s" % ballooned_mem) remote_virsh_session.close_session()
def check_domjobinfo(params, option=""): """ Check given item in domjobinfo of the guest is as expected :param params: the parameters used :param option: options for domjobinfo :raise: test.fail if the value of given item is unexpected """ def search_jobinfo(jobinfo): """ Find value of given item in domjobinfo :param jobinfo: cmdResult object :raise: test.fail if not found """ for item in jobinfo.stdout.splitlines(): if item.count(jobinfo_item): groups = re.findall(r'[0-9.]+', item.strip()) logging.debug("In '%s' search '%s'\n", item, groups[0]) if (math.fabs(float(groups[0]) - float(compare_to_value)) // float(compare_to_value) > diff_rate): test.fail("{} {} has too much difference from " "{}".format(jobinfo_item, groups[0], compare_to_value)) break jobinfo_item = params.get("jobinfo_item") compare_to_value = params.get("compare_to_value") logging.debug("compare_to_value:%s", compare_to_value) diff_rate = float(params.get("diff_rate", "0")) if not jobinfo_item or not compare_to_value: return vm_ref = '{}{}'.format(vm_name, option) jobinfo = virsh.domjobinfo(vm_ref, **virsh_args) search_jobinfo(jobinfo) check_domjobinfo_remote = params.get("check_domjobinfo_remote") if check_domjobinfo_remote: remote_virsh_session = virsh.VirshPersistent(**remote_virsh_dargs) jobinfo = remote_virsh_session.domjobinfo(vm_ref, **virsh_args) search_jobinfo(jobinfo) remote_virsh_session.close_session()
def run(test, params, env): """ This case open multiple connections to libvirtd. """ def get_netlink(service_obj): """ Get netlink list of service :params service_obj: service object :return: netlink list of service """ cmd = "lsof -p `pidof %s` | grep netlink" % service_obj.service_name netlink_list = process.run(cmd, shell=True, verbose=True).stdout_text.strip() return netlink_list conn_num = params.get("conn_num", 1) virsh_instance = [] # Install lsof pkg if not installed if not utils_package.package_install("lsof"): test.cancel("Failed to install lsof in host.") libvirtd = utils_libvirtd.Libvirtd() if not libvirtd.is_running(): libvirtd.start() try: original_netlink = get_netlink(libvirtd) logging.info("original netlink: %s" % original_netlink) for _ in range(int(conn_num)): virsh_instance.append(virsh.VirshPersistent()) time.sleep(5) after_netlink = get_netlink(libvirtd) logging.info("after netlink: %s" % after_netlink) if original_netlink != after_netlink: test.fail("Open netcf more than once in libvirtd.") finally: for session in virsh_instance: session.close_session()
def check_graphics(self, param): """ Check if graphics attributes value in vm xml match with given param. """ logging.info('Check graphics parameters') virsh_instance = virsh.VirshPersistent( session_id=self.virsh_session_id) vmxml = vm_xml.VMXML.new_from_inactive_dumpxml( self.vm_name, options='--security-info', virsh_instance=virsh_instance) graphic = vmxml.xmltreefile.find('devices').find('graphics') status = True for key in param: logging.debug('%s = %s' % (key, graphic.get(key))) if graphic.get(key) != param[key]: logging.error('Attribute "%s" match failed' % key) status = False if not status: self.log_err('Graphic parameter check failed')
def do_virsh_connect(uri, options): """ Execute connect command in a virsh session and return the uri of this virsh session after connect. Raise a process.CmdError if execute virsh connect command failed. :param uri: argument of virsh connect command. :param options: options pass to command connect. :return: the uri of the virsh session after connect. """ virsh_instance = virsh.VirshPersistent() virsh_instance.connect(uri, options) uri_result = virsh_instance.canonical_uri() del virsh_instance logging.debug("uri after connect is %s.", (uri_result)) return uri_result
def run(test, params, env): """ Test virt-admin client-disconnect 1) Start several virsh connections; 2) disconnect some connections; 3) check whether virsh gives out the correct error messages; 4) check whether srv_clients_info gives out the correct info about the virsh clients. """ num_clients = params.get("num_clients") server_name = params.get("server_name") vp = virt_admin.VirtadminPersistent() daemon = utils_libvirtd.Libvirtd() local_pwd = params.get("local_pwd") if not server_name: server_name = virt_admin.check_server_name() ssh_key.setup_remote_ssh_key("localhost", "root", local_pwd) try: virsh_instant = [] for _ in range(int(num_clients)): virsh_instant.append( virsh.VirshPersistent(uri="qemu+ssh://localhost/system")) out = vp.srv_clients_list(server_name, ignore_status=True, debug=True) client_id = out.stdout.strip().splitlines()[-1].split()[0] result = vp.client_disconnect(server_name, client_id, ignore_status=True, debug=True) if result.exit_status: test.fail("This operation should " "success but failed. output: \n %s" % result) elif result.stdout.strip().split()[1][1:-1] != client_id: test.fail("virt-admin did not " "disconnect the correct client.") finally: daemon.restart()
def setup_session(self): if self.virsh_session and self.virsh_session_id: logging.debug('virsh session %s has already been set', self.virsh_session) return for index in range(RETRY_TIMES): logging.info('Trying %d times', index + 1) try: if self.target == "ovirt": self.virsh_session = utils_sasl.VirshSessionSASL( self.params) self.virsh_session_id = self.virsh_session.get_id() else: self.virsh_session = virsh.VirshPersistent(auto_close=True) self.virsh_session_id = self.virsh_session.session_id except Exception as detail: logging.error(detail) else: break logging.debug('new virsh session %s is created', self.virsh_session) if not self.virsh_session_id: raise exceptions.TestError('Fail to create virsh session')
def do_virsh_connect(uri, options): """ Execute connect command in a virsh session and return the uri of this virsh session after connect. Raise a error.TestError if execute virsh connect command failed. :param uri: argument of virsh connect command. :param options: options pass to command connect. :return: the uri of the virsh session after connect. """ virsh_instance = virsh.VirshPersistent() result = virsh_instance.connect(uri, options) if result.exit_status: raise error.TestError("Connect to %s Failed.\n %s" % (uri, result.stdout.rstrip())) uri_result = virsh_instance.canonical_uri() del virsh_instance logging.debug("uri after connect is %s.", (uri_result)) return uri_result