def destroy_net(net_name): """ destroy network in conversion server """ if virsh.net_state_dict()[net_name]['active']: logging.info("Remove network %s in conversion server", net_name) virsh.net_destroy(net_name) if virsh.net_state_dict()[net_name]['autostart']: virsh.net_autostart(net_name, "--disable") output = virsh.net_list("--all").stdout.strip() logging.info(output)
def start_net(net_name): """ start network in conversion server """ logging.info("Recover network %s in conversion server", net_name) virsh.net_autostart(net_name) if not virsh.net_state_dict()[net_name]['active']: virsh.net_start(net_name) output = virsh.net_list("--all").stdout.strip() logging.info(output)
def ensure_default_network(): """ Ensure the default network exists on the host and in active status :return: None """ net_state = virsh.net_state_dict() if 'default' not in net_state: # define and start the default network virsh.net_define("/usr/share/libvirt/networks/default.xml", debug=True, ignore_status=False) if not net_state["default"].get("active"): virsh.net_start("default", debug=True, ignore_status=False) virsh.net_autostart("default", debug=True, ignore_status=False)
def run(test, params, env): """ Test command: virsh net-autostart. """ # Gather test parameters status_error = "yes" == params.get("status_error", "no") net_ref = params.get("net_autostart_net_ref", "netname") disable = "yes" == params.get("net_autostart_disable", "no") extra = params.get("net_autostart_extra", "") # extra cmd-line params. net_name = params.get("net_autostart_net_name", "autotest") # Prepare environment and record current net_state_dict backup = network_xml.NetworkXML.new_all_networks_dict() backup_state = virsh.net_state_dict() logging.debug("Backed up network(s): %s", backup_state) # Generate our own bridge # First check if a bridge of this name already exists try: _ = backup[net_name] except (KeyError, AttributeError): pass # Not found - good else: raise error.TestNAError("Found network bridge '%s' - skipping" % (net_name)) # Define a very bare bones bridge, don't provide UUID - use whatever # libvirt ends up generating. We need to define a persistent network # since we'll be looking to restart libvirtd as part of this test. # # This test cannot use the 'default' bridge (virbr0) since undefining # it causes issues for libvirtd restart since it's expected that a # default network is defined # temp_bridge = """ <network> <name>%s</name> <bridge name="vir%sbr0"/> </network> """ % (net_name, net_name) try: test_xml = network_xml.NetworkXML(network_name=net_name) test_xml.xml = temp_bridge test_xml.define() except xcepts.LibvirtXMLError, detail: raise error.TestNAError("Failed to define a test network.\n" "Detail: %s." % detail)
def find_net(bridge_name): """ Find which network use specified bridge :param bridge_name: bridge name you want to find """ net_list = virsh.net_state_dict(only_names=True) net_name = '' if len(net_list): for net in net_list: net_info = virsh.net_info(net).stdout.strip() search = re.search(r'Bridge:\s+(\S+)', net_info) if search: if bridge_name == search.group(1): net_name = net else: logging.info('Conversion server has no network') return net_name
def run(test, params, env): """ Test command: virsh net-destroy. The command can forcefully stop a given network. 1.Make sure the network exists. 2.Prepare network status. 3.Perform virsh net-destroy operation. 4.Check if the network has been destroied. 5.Recover network environment. 6.Confirm the test result. """ net_ref = params.get("net_destroy_net_ref") extra = params.get("net_destroy_extra", "") network_name = params.get("net_destroy_network", "default") network_status = params.get("net_destroy_status", "active") status_error = params.get("status_error", "no") # libvirt acl polkit related params 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.") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' # Confirm the network exists. output_all = virsh.net_list("--all").stdout.strip() if not re.search(network_name, output_all): raise error.TestNAError("Make sure the network exists!!") # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(network_name).stdout.strip() elif net_ref == "name": net_ref = network_name # Get status of network and prepare network status. network_current_status = "active" try: if not virsh.net_state_dict()[network_name]['active']: network_current_status = "inactive" if network_status == "active": virsh.net_start(network_name) else: if network_status == "inactive": virsh.net_destroy(network_name) except error.CmdError: raise error.TestError("Prepare network status failed!") status = virsh.net_destroy(net_ref, extra, uri=uri, debug=True, unprivileged_user=unprivileged_user, ignore_status=True).exit_status # Confirm the network has been destroied. if virsh.net_state_dict()[network_name]['active']: status = 1 # Recover network status try: if (network_current_status == "active" and not virsh.net_state_dict()[network_name]['active']): virsh.net_start(network_name) if (network_current_status == "inactive" and virsh.net_state_dict()[network_name]['active']): virsh.net_destroy(network_name) except error.CmdError: raise error.TestError("Recover network status failed!") # 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") else: raise error.TestError("The status_error must be 'yes' or 'no'!")
def run(test, params, env): """ Test bridge support from network 1) create a linux bridge and connect a physical interface to it 2) define nwfilter with "vdsm-no-mac-spoofing" 3) redefine the vm with the new create bridge and filter 4) check if guest can get public ip after vm start 5) check if guest and host can ping each other 6) check if guest and host can ping outside 7) start another vm connected to the same bridge 8) check if the 2 guests can ping each other """ def create_bridge(br_name, iface_name): """ Create a linux bridge by virsh cmd: 1. Stop NetworkManager and Start network service 2. virsh iface-bridge <iface> <name> [--no-stp] :param br_name: bridge name :param iface_name: physical interface name :return: bridge created or raise exception """ # Make sure the bridge not exist if libvirt.check_iface(br_name, "exists", "--all"): test.cancel("The bridge %s already exist" % br_name) # Create bridge utils_package.package_install('tmux') cmd = 'tmux -c "ip link add name {0} type bridge; ip link set {1} up;' \ ' ip link set {1} master {0}; ip link set {0} up;' \ ' pkill dhclient; sleep 6; dhclient {0}; ifconfig {1} 0"'.format(br_name, iface_name) process.run(cmd, shell=True, verbose=True) def create_bridge_network(br_name, net_name): """ Define and start the bridge type network """ # check if network with the same name already exists output_all = virsh.net_list("--all").stdout.strip() if re.search(net_name, output_all): test.cancel("Network with the same name already exists!") test_xml = network_xml.NetworkXML(network_name="%s" % net_name) test_xml.forward = {"mode": "bridge"} test_xml.bridge = {"name": br_name} test_xml.create() def define_nwfilter(filter_name): """ Define nwfilter vdsm-no-mac-spoofing with content like: <filter name='vdsm-no-mac-spoofing' chain='root'> <filterref filter='no-mac-spoofing'/> <filterref filter='no-arp-mac-spoofing'/> </filter> :param filter_name: the name of nwfilter :return: filter created or raise exception """ filter_uuid = params.get("filter_uuid", "11111111-b071-6127-b4ec-111111111111") filter_params = { "filter_name": "vdsm-no-mac-spoofing", "filter_chain": "root", "filter_uuid": filter_uuid, "filterref_name_1": "no-mac-spoofing", "filterref_name_2": "no-arp-mac-spoofing" } filter_xml = libvirt.create_nwfilter_xml(filter_params).xml # Run command result = virsh.nwfilter_define(filter_xml, ignore_status=True, debug=True) if result.exit_status: test.fail("Failed to define nwfilter with %s" % filter_xml) def ping(src_ip, dest_ip, ping_count, timeout, session=None): """ Wrap of ping :param src_ip: source address :param dest_ip: destination address :param ping_count: count of icmp packet :param timeout: timeout for the ping command :param session: local execution or session to execute the ping command :return: ping succeed or raise exception """ status, output = utils_net.ping(dest=dest_ip, count=ping_count, interface=src_ip, timeout=timeout, session=session, force_ipv4=True) if status: test.fail("Fail to ping %s from %s" % (dest_ip, src_ip)) def check_net_functions(guest_ip, ping_count, ping_timeout, guest_session, host_ip, remote_url, endpoint_ip): # make sure host network works well # host ping remote url ping(host_ip, remote_url, ping_count, ping_timeout) # host ping guest ping(host_ip, guest_ip, ping_count, ping_timeout) # guest ping host ping(guest_ip, host_ip, ping_count, ping_timeout, session=guest_session) # guest ping remote url ping(guest_ip, remote_url, ping_count, ping_timeout, session=guest_session) # guest ping endpoint ping(guest_ip, endpoint_ip, ping_count, ping_timeout, session=guest_session) # Get test params bridge_name = params.get("bridge_name", "test_br0") filter_name = params.get("filter_name", "vdsm-no-mac-spoofing") ping_count = params.get("ping_count", "5") ping_timeout = float(params.get("ping_timeout", "10")) iface_name = utils_net.get_net_if(state="UP")[0] bridge_script = NETWORK_SCRIPT + bridge_name iface_script = NETWORK_SCRIPT + iface_name iface_script_bk = os.path.join(data_dir.get_tmp_dir(), "iface-%s.bk" % iface_name) attach_interface = "yes" == params.get("attach_interface", "no") iface_model = params.get("iface_model", "virtio") iface_source = eval(params.get("iface_source", "{'bridge':'test_br0'}")) iface_type = params.get("iface_type", None) iface_target = params.get("iface_target", "br_target") iface_alias = params.get("iface_alias", None) hotplug = "yes" == params.get("hotplug", "no") iface_driver = params.get("iface_driver", None) start_vm2 = "yes" == params.get("start_vm2", "no") create_network = "yes" == params.get("create_network", "no") update_device = "yes" == params.get("update_with_diff_type", "no") vms = params.get("vms").split() if len(vms) <= 1: test.cancel("Need two VMs to test") else: vm1_name = vms[0] vm2_name = vms[1] vm1 = env.get_vm(vm1_name) vm2 = env.get_vm(vm2_name) # Back up the interface script process.run("cp %s %s" % (iface_script, iface_script_bk), shell=True, verbose=True) # Back up vm xml vm1_xml_bak = vm_xml.VMXML.new_from_dumpxml(vm1_name) vm2_xml_bak = vm_xml.VMXML.new_from_dumpxml(vm2_name) # Stop NetworkManager service NM_service = service.Factory.create_service("NetworkManager") NM_status = NM_service.status() if not NM_status: NM_service.start() mac = utils_net.generate_mac_address_simple() try: create_bridge(bridge_name, iface_name) define_nwfilter(filter_name) if hotplug: err_msgs = ("No more available PCI slots", "No more available PCI addresses") # delete the original interface on the vm before hot-plug if vm1.is_alive(): vm1.destroy() vmxml = vm_xml.VMXML.new_from_dumpxml(vm1_name) iface_xml = vmxml.get_devices('interface')[0] logging.debug("Delete the original interface") vmxml.del_device(iface_xml) vmxml.sync() vm1.start() # do hot-plug if attach_interface: logging.info("Try to hot-plug interface") options = ( "%s %s --model %s --mac %s" % (iface_type, iface_source['bridge'], iface_model, mac)) ret = virsh.attach_interface(vm1_name, options, ignore_status=True) else: logging.info("Try to hot-plug device") if create_network: create_bridge_network(bridge_name, iface_source["network"]) target = str({'dev': iface_target}) iface_alias = str({'name': iface_alias}) vm_iface_source = str(iface_source) iface_params = { "type": iface_type, "source": vm_iface_source, "filter": filter_name, "mac": mac, 'alias': iface_alias, 'target': target, 'model': iface_model, 'driver': iface_driver } attach_xml = interface.Interface(iface_params['type']) attach_xml.xml = libvirt.modify_vm_iface( vm1_name, 'get_xml', iface_params) ret = virsh.attach_device(vm1_name, attach_xml.xml, ignore_status=True, debug=True) if ret.exit_status: if any([msg in ret.stderr for msg in err_msgs]): test.error("No more pci slots, can't attach more devices") else: test.fail("Failed to attach-interface: %s" % ret.stderr.strip()) else: logging.debug("Hot-plug interface or device pass") if update_device: # As the interface type will change to actual type "bridge" in live xml, we need to ensure # the update with original "network" type will not fail. # Try to delete the nwfilter with original type in iface_params update_xml = interface.Interface(iface_type) iface_params_update = { "del_filter": "yes", "type": "network", "source": vm_iface_source } update_xml.xml = libvirt.modify_vm_iface( vm1_name, 'get_xml', iface_params_update) ret = virsh.update_device(vm1_name, update_xml.xml, ignore_status=True, debug=True) libvirt.check_exit_status(ret) else: vm_iface_source = str(iface_source) vm1_iface_params = { "type": "bridge", "source": vm_iface_source, "filter": filter_name, "mac": mac, 'driver': iface_driver, "iface_model": iface_model } libvirt.modify_vm_iface(vm1_name, "update_iface", vm1_iface_params) if vm1.is_alive(): vm1.destroy() vm1.start() # apply ip address as it may not be initialized session1 = session2 = None session1 = vm1.wait_for_serial_login() utils_net.restart_guest_network(session1) output = session1.cmd_output("ifconfig || ip a") logging.debug("guest1 ip info %s" % output) # Check guest's network function host_ip = utils_net.get_ip_address_by_interface(bridge_name) remote_url = params.get("remote_ip", "www.google.com") try: vm1_ip = utils_net.get_guest_ip_addr(session1, mac) except Exception as errs: test.fail("vm1 can't get IP with the new create bridge: %s" % errs) if hotplug: # reboot vm1 then check network function to ensure the interface still there and works fine logging.info("reboot the vm") virsh.reboot(vm1) if session1 is None: session1 = vm1.wait_for_serial_login() ping(vm1_ip, remote_url, ping_count, ping_timeout, session=session1) # restart libvirtd service then check the interface still works fine libvirtd = utils_libvirtd.Libvirtd() libvirtd.restart() vm1.cleanup_serial_console() vm1.create_serial_console() session1 = vm1.wait_for_serial_login() ping(vm1_ip, remote_url, ping_count, ping_timeout, session=session1) logging.info( "after reboot and restart libvirtd, the network works fine") if iface_driver: try: driver_dict = eval(iface_driver) if session1 is None: session1 = vm1.wait_for_serial_login() guest_iface_info = session1.cmd_output("ip l").strip() guest_iface_name = re.findall( r"^\d+: (\S+?)[@:].*state UP.*$", guest_iface_info, re.MULTILINE)[0] comb_size = driver_dict.get('queues') rx_size = driver_dict.get('rx_queue_size') session1.cmd_status("ethtool -L %s combined %s" % (guest_iface_name, comb_size)) ret, outp = session1.cmd_status_output("ethtool -l %s" % guest_iface_name) logging.debug("ethtool cmd output:%s" % outp) if not ret: pre_comb = re.search( "Pre-set maximums:[\s\S]*?Combined:.*?(\d+)", outp).group(1) cur_comb = re.search( "Current hardware settings:[\s\S]*?Combined:.*?(\d+)", outp).group(1) if int(pre_comb) != int(comb_size) or int( cur_comb) != int(comb_size): test.fail( "Fail to check the combined size: setting: %s," "Pre-set: %s, Current-set: %s" % (comb_size, pre_comb, cur_comb)) else: logging.info( "Getting correct Pre-set and Current set value" ) else: test.error("ethtool list fail: %s" % outp) # as tx_queue size is only supported for vhost-user interface, only check rx_queue size ret1, outp1 = session1.cmd_status_output("ethtool -g %s" % guest_iface_name) logging.debug("guest queue size setting is %s" % outp1) if not ret1: pre_set = re.search(r"Pre-set maximums:\s*RX:\s*(\d+)", outp1).group(1) cur_set = re.search( r"Current hardware settings:\s*RX:\s*(\d+)", outp1).group(1) if int(pre_set) != int(rx_size) or int(cur_set) != int( rx_size): test.fail("Fail to check the rx_queue_size!") except Exception as errs: test.fail("fail to get driver info") # hot-unplug interface/device if attach_interface: ret = virsh.detach_interface(vm1_name, "bridge", ignore_status=True) else: ret = virsh.detach_device(vm1_name, attach_xml.xml, ignore_status=True, debug=True) if ret.exit_status: test.fail("Hot-unplug interface/device fail") else: logging.info("hot-unplug interface/device succeed") else: if start_vm2: # Start vm2 connect to the same bridge mac2 = utils_net.generate_mac_address_simple() vm2_iface_params = { "type": "bridge", "source": vm_iface_source, "filter": filter_name, "mac": mac2 } libvirt.modify_vm_iface(vm2_name, "update_iface", vm2_iface_params) if vm2.is_alive(): vm2.destroy() vm2.start() # Check if vm1 and vm2 can ping each other try: utils_net.update_mac_ip_address(vm2, timeout=120) vm2_ip = vm2.get_address() except Exception as errs: test.fail( "vm2 can't get IP with the new create bridge: %s" % errs) session2 = vm2.wait_for_login() # make sure guest has got ip address utils_net.restart_guest_network(session2) output2 = session2.cmd_output("ifconfig || ip a") logging.debug("guest ip info %s" % output2) # check 2 guests' network functions check_net_functions(vm1_ip, ping_count, ping_timeout, session1, host_ip, remote_url, vm2_ip) check_net_functions(vm2_ip, ping_count, ping_timeout, session2, host_ip, remote_url, vm1_ip) finally: logging.debug("Start to restore") vm1_xml_bak.sync() vm2_xml_bak.sync() virsh.nwfilter_undefine(filter_name, ignore_status=True) if libvirt.check_iface(bridge_name, "exists", "--all"): virsh.iface_unbridge(bridge_name, timeout=60, debug=True) if os.path.exists(iface_script_bk): process.run("mv %s %s" % (iface_script_bk, iface_script), shell=True, verbose=True) if os.path.exists(bridge_script): process.run("rm -rf %s" % bridge_script, shell=True, verbose=True) cmd = 'tmux -c "ip link set {1} nomaster; ip link delete {0};' \ 'pkill dhclient; sleep 6; dhclient {1}"'.format(bridge_name, iface_name) process.run(cmd, shell=True, verbose=True) # reload network configuration NM_service.restart() # recover NetworkManager if NM_status is True: NM_service.start() if 'network' in iface_source and iface_source[ "network"] in virsh.net_state_dict(): virsh.net_destroy(iface_source["network"], ignore_status=False)
def run(test, params, env): """ Test command: virsh net-event 1. Prepare a new network. 2. Running virsh net-event with different options, and start/stop the network if needed, then check the output of net-event. 3. Clean the environment. """ prepare_net = "yes" == params.get("prepare_net", "yes") net_addr = params.get("net_addr") net_name = params.get("net_name") net_event_list = "yes" == params.get("net_event_list", "no") net_event_loop = "yes" == params.get("net_event_loop", "no") net_event_name = params.get("net_event_name") net_event_timeout = params.get("net_event_timeout") net_event_amount = int(params.get("net_event_amount", 1)) status_error = "yes" == params.get("status_error", "no") net_event_option = params.get("net_event_option", "") virsh_dargs = {'debug': True, 'ignore_status': True} net_event_interrupt = False libv_net = None expected_event_list = [] virsh_session = aexpect.ShellSession(virsh.VIRSH_EXEC, auto_close=True) def trigger_net_event(event_amount=1): """ Trigger network start/stop actions in event_number times """ i = event_amount // 2 event_list = [] try: while i > 0: virsh.net_start(net_name, **virsh_dargs) event_list.append("Started") virsh.net_destroy(net_name, **virsh_dargs) event_list.append("Stopped") i -= 1 if event_amount % 2: virsh.net_start(net_name, **virsh_dargs) event_list.append("Started") finally: return event_list def check_output(output, expected_event_list): """ Check received net-event in output. :param output: The virsh shell output, such as: Welcome to virsh, the virtualization interactive terminal. Type: 'help' for help with commands 'quit' to quit virsh # event 'lifecycle' for network virttest_net: Started events received: 1 virsh # : expected_event_list: A list of expected events ['Started', 'Stopped', ..] """ event_match_str = "event 'lifecycle' for network %s: %s" if net_event_interrupt: output = output.strip().splitlines()[5:] else: output = output.strip().splitlines()[5:-2] output = [o.replace("virsh #", "").strip() for o in output] # Both order and content should match index = 0 for event_str in expected_event_list: match_str = event_match_str % (net_name, event_str) logging.debug("Expected output: %s", match_str) logging.debug("Actual output: %s", output[index]) if not output[index].count(match_str): test.fail("Event received not match") index += 1 try: if prepare_net: libv_net = utlv.LibvirtNetwork("vnet", address=net_addr, net_name=net_name, persistent=True) # Destroy the network if virsh.net_state_dict()[net_name]['active']: virsh.net_destroy(net_name) logging.info("Defined network %s", net_name) if net_event_list: net_event_option += " --list" if net_event_loop: net_event_option += " --loop" if not status_error and not net_event_list: # Assemble the net-event command net_event_cmd = "net-event %s" % net_event_option if net_name: net_event_cmd += " --network %s" % net_name if net_event_name: net_event_cmd += " --event %s" % net_event_name if net_event_timeout: net_event_cmd += " --timeout %s" % net_event_timeout if not status_error: net_event_timeout = int(net_event_timeout) # Run the command in a new virsh session, then waiting for # 'lifecycle' events logging.info("Sending '%s' to virsh shell", net_event_cmd) virsh_session.sendline(net_event_cmd) else: result = virsh.net_event(network=net_name, event=net_event_name, event_timeout=net_event_timeout, options=net_event_option, **virsh_dargs) utlv.check_exit_status(result, status_error) if not status_error: # Verify 'lifecycle' events if not net_event_list and net_event_name == 'lifecycle': expected_event_list = trigger_net_event(net_event_amount) if net_event_timeout: # Make sure net-event will timeout on time time.sleep(net_event_timeout) elif net_event_loop: virsh_session.send_ctrl("^C") net_event_interrupt = True ret_output = virsh_session.get_stripped_output() check_output(ret_output, expected_event_list) finally: virsh_session.close() if libv_net: libv_net.cleanup()
def run_virsh_net_list(test, params, env): """ Test command: virsh net-list. The command returns list of networks. 1.Get all parameters from configuration. 2.Get current network's status(State, Autostart). 3.Do some prepare works for testing. 4.Perform virsh net-list operation. 5.Recover network status. 6.Confirm the result. """ option = params.get("net_list_option", "") extra = params.get("net_list_extra", "") status_error = params.get("status_error", "no") net_name = params.get("net_list_name", "default") persistent = params.get("net_list_persistent", "yes") net_status = params.get("net_list_error", "active") tmp_xml = os.path.join(test.tmpdir, "tmp.xml") net_current_status = "active" autostart_status = "yes" if not virsh.net_state_dict()[net_name]["active"]: net_current_status = "inactive" if not virsh.net_state_dict()[net_name]["autostart"]: autostart_status = "no" # Create a transient network. try: if persistent == "no": virsh.net_dumpxml(net_name, to_file=tmp_xml, ignore_status=False) if net_current_status == "inactive": virsh.net_destroy(net_name, ignore_status=False) virsh.net_undefine(net_name, ignore_status=False) virsh.net_create(tmp_xml, ignore_status=False) except error.CmdError: raise error.TestFail("Transient network test failed!") # Prepare network's status for testing. if net_status == "active": try: if not virsh.net_state_dict()[net_name]["active"]: virsh.net_start(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Active network test failed!") else: try: if virsh.net_state_dict()[net_name]["active"]: virsh.net_destroy(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Inactive network test failed!") result = virsh.net_list(option, extra, ignore_status=True) status = result.exit_status output = result.stdout.strip() # Recover network try: if persistent == "no": virsh.net_destroy(net_name, ignore_status=False) virsh.net_define(tmp_xml, ignore_status=False) if net_current_status == "active": virsh.net_start(net_name, ignore_status=False) if autostart_status == "yes": virsh.net_autostart(net_name, ignore_status=False) else: if net_current_status == "active" and net_status == "inactive": virsh.net_start(net_name, ignore_status=False) elif net_current_status == "inactive" and net_status == "active": virsh.net_destroy(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Recover network failed!") # check result 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 option == "--inactive": if net_status == "active": if re.search(net_name, output): raise error.TestFail("Found an active network with" " --inactive option") else: if persistent == "yes": if not re.search(net_name, output): raise error.TestFail("Found no inactive networks with" " --inactive option") else: # If network is transient, after net-destroy it, # it will disapear. if re.search(net_name, output): raise error.TestFail("Found transient inactive networks" " with --inactive option") elif option == "": if net_status == "active": if not re.search(net_name, output): raise error.TestFail("Can't find active network with no" " option") else: if re.search(net_name, output): raise error.TestFail("Found inactive network with" " no option") elif option == "--all": if net_status == "active": if not re.search(net_name, output): raise error.TestFail("Can't find active network with" " --all option") else: if persistent == "yes": if not re.search(net_name, output): raise error.TestFail("Can't find inactive network with" " --all option") else: # If network is transient, after net-destroy it, # it will disapear. if re.search(net_name, output): raise error.TestFail("Found transient inactive network" " with --all option")
def run(test, params, env): """ Test command: virsh net-dumpxml. This command can output the network information as an XML dump to stdout. 1.Get all parameters from config file. 2.If test case's network status is inactive, destroy it. 3.Perform virsh net-dumpxml operation. 4.Recover test environment(network status). 5.Confirm the test result. """ status_error = params.get("status_error", "no") net_ref = params.get("net_dumpxml_net_ref") net_name = params.get("net_dumpxml_network", "default") net_status = params.get("net_dumpxml_network_status", "active") xml_flie = params.get("net_dumpxml_xml_file", "default.xml") extra = params.get("net_dumpxml_extra", "") network_xml = os.path.join(data_dir.get_tmp_dir(), xml_flie) # acl polkit 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.") # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(net_name).stdout.strip() elif net_ref == "name": net_ref = net_name net_status_current = "active" if not virsh.net_state_dict()[net_name]['active']: net_status_current = "inactive" if not virsh.net_state_dict()[net_name]['persistent']: test.error("Network is transient!") try: if net_status == "inactive" and net_status_current == "active": status_destroy = virsh.net_destroy(net_name, ignore_status=True).exit_status if status_destroy != 0: test.error("Network destroied failed!") virsh_dargs = {'ignore_status': True} if params.get('setup_libvirt_polkit') == 'yes': virsh_dargs['unprivileged_user'] = unprivileged_user virsh_dargs['uri'] = uri result = virsh.net_dumpxml(net_ref, extra, network_xml, **virsh_dargs) status = result.exit_status err = result.stderr.strip() xml_validate_cmd = "virt-xml-validate %s network" % network_xml valid_s = process.run(xml_validate_cmd, ignore_status=True, shell=True).exit_status # Check option valid or not. if extra.find("--") != -1: options = extra.split("--") for option in options: if option.strip() == "": continue if not virsh.has_command_help_match("net-dumpxml", option.strip()) and\ status_error == "no": test.cancel("The current libvirt version" " doesn't support '%s' option" % option.strip()) finally: # Recover network if net_status == "inactive" and net_status_current == "active": status_start = virsh.net_start(net_name, ignore_status=True).exit_status if status_start != 0: test.error("Network started failed!") # Check status_error if status_error == "yes": if status == 0: test.fail("Run successfully with wrong command!") if err == "": test.fail("The wrong command has no error outputed!") elif status_error == "no": if status != 0: test.fail("Run failed with right command!") if valid_s != 0: test.fail("Command output is invalid!") else: test.error("The status_error must be 'yes' or 'no'!")
def run(test, params, env): """ Test command: virsh net-list. The command returns list of networks. 1.Get all parameters from configuration. 2.Get current network's status(State, Autostart). 3.Do some prepare works for testing. 4.Perform virsh net-list operation. 5.Recover network status. 6.Confirm the result. """ option = params.get("net_list_option", "") extra = params.get("net_list_extra", "") status_error = params.get("status_error", "no") net_name = params.get("net_list_name", "default") persistent = params.get("net_list_persistent", "yes") net_status = params.get("net_list_error", "active") tmp_xml = os.path.join(test.tmpdir, "tmp.xml") net_current_status = "active" autostart_status = "yes" if not virsh.net_state_dict()[net_name]['active']: net_current_status = "inactive" if not virsh.net_state_dict()[net_name]['autostart']: autostart_status = "no" # acl polkit 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.") # Create a transient network. try: if persistent == "no": virsh.net_dumpxml(net_name, to_file=tmp_xml, ignore_status=False) if net_current_status == "inactive": virsh.net_destroy(net_name, ignore_status=False) virsh.net_undefine(net_name, ignore_status=False) virsh.net_create(tmp_xml, ignore_status=False) except error.CmdError: raise error.TestFail("Transient network test failed!") # Prepare network's status for testing. if net_status == "active": try: if not virsh.net_state_dict()[net_name]['active']: virsh.net_start(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Active network test failed!") else: try: if virsh.net_state_dict()[net_name]['active']: virsh.net_destroy(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Inactive network test failed!") virsh_dargs = {'ignore_status': True} if params.get('setup_libvirt_polkit') == 'yes': virsh_dargs['unprivileged_user'] = unprivileged_user virsh_dargs['uri'] = uri result = virsh.net_list(option, extra, **virsh_dargs) status = result.exit_status output = result.stdout.strip() # Recover network try: if persistent == "no": virsh.net_destroy(net_name, ignore_status=False) virsh.net_define(tmp_xml, ignore_status=False) if net_current_status == "active": virsh.net_start(net_name, ignore_status=False) if autostart_status == "yes": virsh.net_autostart(net_name, ignore_status=False) else: if net_current_status == "active" and net_status == "inactive": virsh.net_start(net_name, ignore_status=False) elif net_current_status == "inactive" and net_status == "active": virsh.net_destroy(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Recover network failed!") # check result 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 option == "--inactive": if net_status == "active": if re.search(net_name, output): raise error.TestFail("Found an active network with" " --inactive option") else: if persistent == "yes": if not re.search(net_name, output): raise error.TestFail("Found no inactive networks with" " --inactive option") else: # If network is transient, after net-destroy it, # it will disapear. if re.search(net_name, output): raise error.TestFail("Found transient inactive networks" " with --inactive option") elif option == "": if net_status == "active": if not re.search(net_name, output): raise error.TestFail("Can't find active network with no" " option") else: if re.search(net_name, output): raise error.TestFail("Found inactive network with" " no option") elif option == "--all": if net_status == "active": if not re.search(net_name, output): raise error.TestFail("Can't find active network with" " --all option") else: if persistent == "yes": if not re.search(net_name, output): raise error.TestFail("Can't find inactive network with" " --all option") else: # If network is transient, after net-destroy it, # it will disapear. if re.search(net_name, output): raise error.TestFail("Found transient inactive network" " with --all option")
def check_result(result, status_error): """ Check virt-v2v command result """ libvirt.check_exit_status(result, status_error) output = result.stdout_text + result.stderr_text if checkpoint == 'empty_cdrom': if status_error: log_fail('Virsh dumpxml failed for empty cdrom image') elif not status_error: vmchecker = VMChecker(test, params, env) params['vmchecker'] = vmchecker if output_mode == 'rhev': if not utils_v2v.import_vm_to_ovirt(params, address_cache, timeout=v2v_timeout): test.fail('Import VM failed') elif output_mode == 'libvirt': virsh.start(vm_name, debug=True) # Check guest following the checkpoint document after convertion logging.info('Checking common checkpoints for v2v') if skip_vm_check != 'yes': if checkpoint == 'ogac': # windows guests will reboot at any time after qemu-ga is # installed. The process cannot be controled. In order to # don't break vmchecker.run() process, It's better to put # check_windows_ogac before vmchecker.run(). Because in # check_windows_ogac, it waits until rebooting completes. vmchecker.checker.create_session() if os_type == 'windows': check_windows_ogac(vmchecker.checker) else: check_linux_ogac(vmchecker.checker) ret = vmchecker.run() if len(ret) == 0: logging.info("All common checkpoints passed") else: logging.info( 'Skip checking vm after conversion: %s' % skip_reason) # Check specific checkpoints if checkpoint == 'cdrom': virsh_session = utils_sasl.VirshSessionSASL(params) virsh_session_id = virsh_session.get_id() check_device_exist('cdrom', virsh_session_id) virsh_session.close() if checkpoint.startswith('vmtools'): check_vmtools(vmchecker.checker, checkpoint) if checkpoint == 'modprobe': check_modprobe(vmchecker.checker) if checkpoint == 'device_map': check_device_map(vmchecker.checker) if checkpoint == 'resume_swap': check_resume_swap(vmchecker.checker) if checkpoint == 'rhev_file': check_rhev_file_exist(vmchecker.checker) if checkpoint == 'file_architecture': check_file_architecture(vmchecker.checker) if checkpoint == 'ubuntu_tools': check_ubuntools(vmchecker.checker) if checkpoint == 'without_default_net': if virsh.net_state_dict()[net_name]['active']: log_fail("Bridge virbr0 already started during conversion") # Merge 2 error lists error_list.extend(vmchecker.errors) log_check = utils_v2v.check_log(params, output) if log_check: log_fail(log_check) if len(error_list): test.fail('%d checkpoints failed: %s' % (len(error_list), error_list))
def run(test, params, env): """ Test command: virsh net-list. The command returns list of networks. 1.Get all parameters from configuration. 2.Get current network's status(State, Autostart). 3.Do some prepare works for testing. 4.Perform virsh net-list operation. 5.Recover network status. 6.Confirm the result. """ option = params.get("net_list_option", "") extra = params.get("net_list_extra", "") status_error = params.get("status_error", "no") set_status = params.get("set_status", "active") set_persistent = params.get("set_persistent", "persistent") set_autostart = params.get("set_autostart", "autostart") error_msg = params.get("error_msg", "") net_name = params.get("net_name", "net-br") net_xml = network_xml.NetworkXML(network_name=net_name) # acl polkit 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 exceptions.TestSkipError("API acl test not supported" " in current libvirt version.") # Record current net_state_dict net_backup = network_xml.NetworkXML.new_all_networks_dict() net_backup_state = virsh.net_state_dict() logging.debug("Backed up network(s): %s", net_backup_state) # Check the network name is not duplicated try: _ = net_backup[net_name] except (KeyError, AttributeError): pass else: raise exceptions.TestSkipError("Duplicated network name: '%s'" % net_name) # Default the network is persistent, active, autostart # Create a persistent/transient network. if set_persistent == "persistent": net_xml.define() logging.debug("Created persistent network") else: net_xml.create() logging.debug("Created transient network") # Prepare an active/inactive network # For the new defined network, it's inactive by default if set_status == "active" and set_persistent == "persistent": net_xml.start() # Prepare an autostart/no-autostart network # For the new create network, it's no-autostart by default if set_autostart == "autostart": net_xml.set_autostart(True) try: virsh_dargs = {'ignore_status': True} if params.get('setup_libvirt_polkit') == 'yes': virsh_dargs['unprivileged_user'] = unprivileged_user virsh_dargs['uri'] = uri ret = virsh.net_list(option, extra, **virsh_dargs) output = ret.stdout.strip() # Check test results if status_error == "yes": # Check the results with error parameter if error_msg: libvirt.check_result(ret, error_msg) # Check the results with correct option but inconsistent network status else: libvirt.check_exit_status(ret) if re.search(net_name, output): raise exceptions.TestFail("virsh net-list %s get wrong results" % option) # Check the results with correct option and consistent network status else: libvirt.check_exit_status(ret) if option == "--uuid": uuid = virsh.net_uuid(net_name).stdout.strip() if not re.search(uuid, output): raise exceptions.TestFail("Failed to find network: '%s' with:" "virsh net-list '%s'." % (net_name, option)) else: if not re.search(net_name, output): raise exceptions.TestFail("Failed to find network: '%s' with:" "virsh net-list '%s'." % (net_name, option)) finally: # Recover network try: if set_status == "active": net_xml.del_active() if set_persistent == "persistent": net_xml.del_defined() except Exception: virsh.net_undefine()
def run(test, params, env): """ Test command: virsh net-event 1. Prepare a new network. 2. Running virsh net-event with different options, and start/stop the network if needed, then check the output of net-event. 3. Clean the environment. """ prepare_net = "yes" == params.get("prepare_net", "yes") net_addr = params.get("net_addr") net_name = params.get("net_name") net_event_list = "yes" == params.get("net_event_list", "no") net_event_loop = "yes" == params.get("net_event_loop", "no") net_event_timestamp = "yes" == params.get("net_event_timestamp", "no") net_event_name = params.get("net_event_name") net_event_timeout = params.get("net_event_timeout") net_event_amount = int(params.get("net_event_amount", 1)) status_error = "yes" == params.get("status_error", "no") net_event_option = params.get("net_event_option", "") virsh_dargs = {'debug': True, 'ignore_status': True} net_event_interrupt = False libv_net = None expected_event_list = [] virsh_session = aexpect.ShellSession(virsh.VIRSH_EXEC, auto_close=True) def trigger_net_event(event_amount=1): """ Trigger network start/stop actions in event_number times """ i = event_amount // 2 event_list = [] try: while i > 0: virsh.net_start(net_name, **virsh_dargs) event_list.append("Started") virsh.net_destroy(net_name, **virsh_dargs) event_list.append("Stopped") i -= 1 if event_amount % 2: virsh.net_start(net_name, **virsh_dargs) event_list.append("Started") finally: return event_list def check_output(output, expected_event_list): """ Check received net-event in output. :param output: The virsh shell output, such as: Welcome to virsh, the virtualization interactive terminal. Type: 'help' for help with commands 'quit' to quit virsh # event 'lifecycle' for network virttest_net: Started events received: 1 virsh # : expected_event_list: A list of expected events ['Started', 'Stopped', ..] """ event_match_str = "event 'lifecycle' for network %s: %s" if net_event_interrupt: output = output.strip().splitlines()[5:] else: output = output.strip().splitlines()[5:-2] output = [o.replace("virsh #", "").strip() for o in output] # Both order and content should match index = 0 for event_str in expected_event_list: match_str = event_match_str % (net_name, event_str) logging.debug("Expected output: %s", match_str) logging.debug("Actual output: %s", output[index]) if not output[index].count(match_str): test.fail("Event received not match") if net_event_timestamp: if not re.match(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})", output[index]): test.fail("Can not get timestamp in output") index += 1 try: if prepare_net: libv_net = utlv.LibvirtNetwork("vnet", address=net_addr, net_name=net_name, persistent=True) # Destroy the network if virsh.net_state_dict()[net_name]['active']: virsh.net_destroy(net_name) logging.info("Defined network %s", net_name) if net_event_list: net_event_option += " --list" if net_event_loop: net_event_option += " --loop" if net_event_timestamp: net_event_option += " --timestamp" if not status_error and not net_event_list: # Assemble the net-event command net_event_cmd = "net-event %s" % net_event_option if net_name: net_event_cmd += " --network %s" % net_name if net_event_name: net_event_cmd += " --event %s" % net_event_name if net_event_timeout: net_event_cmd += " --timeout %s" % net_event_timeout if not status_error: net_event_timeout = int(net_event_timeout) # Run the command in a new virsh session, then waiting for # 'lifecycle' events logging.info("Sending '%s' to virsh shell", net_event_cmd) virsh_session.sendline(net_event_cmd) else: result = virsh.net_event(network=net_name, event=net_event_name, event_timeout=net_event_timeout, options=net_event_option, **virsh_dargs) utlv.check_exit_status(result, status_error) if not status_error: # Verify 'lifecycle' events if not net_event_list and net_event_name == 'lifecycle': expected_event_list = trigger_net_event(net_event_amount) if net_event_timeout: # Make sure net-event will timeout on time time.sleep(net_event_timeout) elif net_event_loop: virsh_session.send_ctrl("^C") net_event_interrupt = True ret_output = virsh_session.get_stripped_output() check_output(ret_output, expected_event_list) finally: virsh_session.close() if libv_net: libv_net.cleanup()
try: test_xml = network_xml.NetworkXML(network_name=net_name) test_xml.xml = temp_bridge test_xml.define() except xcepts.LibvirtXMLError, detail: raise error.TestNAError("Failed to define a test network.\n" "Detail: %s." % detail) # To guarantee cleanup will be executed try: # Run test case # Get the updated list and make sure our new bridge exists currents = network_xml.NetworkXML.new_all_networks_dict() current_state = virsh.net_state_dict() logging.debug("Current network(s): %s", current_state) try: testbr_xml = currents[net_name] except (KeyError, AttributeError): raise error.TestError("Did not find newly defined bridge '%s'" % (net_name)) # Prepare default property for network # Transient network can not be set autostart # So confirm persistent is true for test testbr_xml['persistent'] = True # Set network to inactive # Since we do not reboot host to check(instead of restarting libvirtd) # If default network is active, we cannot check "--disable".
def run(test, params, env): """ Test command: virsh net-autostart. """ # Gather test parameters status_error = "yes" == params.get("status_error", "no") net_ref = params.get("net_autostart_net_ref", "netname") disable = "yes" == params.get("net_autostart_disable", "no") extra = params.get("net_autostart_extra", "") # extra cmd-line params. net_name = params.get("net_autostart_net_name", "autotest") net_transient = "yes" == params.get("net_transient", "no") readonly = ("yes" == params.get("readonly", "no")) sim_reboot = "yes" == params.get("sim_reboot", "no") # Prepare environment and record current net_state_dict backup = network_xml.NetworkXML.new_all_networks_dict() backup_state = virsh.net_state_dict() logging.debug("Backed up network(s): %s", backup_state) # Generate our own bridge # First check if a bridge of this name already exists try: _ = backup[net_name] except (KeyError, AttributeError): pass # Not found - good else: test.cancel("Found network bridge '%s' - skipping" % net_name) # Define a very bare bones bridge, don't provide UUID - use whatever # libvirt ends up generating. We need to define a persistent network # since we'll be looking to restart libvirtd as part of this test. # # This test cannot use the 'default' bridge (virbr0) since undefining # it causes issues for libvirtd restart since it's expected that a # default network is defined # temp_bridge = """ <network> <name>%s</name> <bridge name="vir%sbr0"/> </network> """ % (net_name, net_name) try: test_xml = network_xml.NetworkXML(network_name=net_name) test_xml.xml = temp_bridge test_xml.define() except xcepts.LibvirtXMLError as detail: test.error("Failed to define a test network.\n" "Detail: %s." % detail) # To guarantee cleanup will be executed try: # Run test case # Get the updated list and make sure our new bridge exists currents = network_xml.NetworkXML.new_all_networks_dict() current_state = virsh.net_state_dict() logging.debug("Current network(s): %s", current_state) try: testbr_xml = currents[net_name] except (KeyError, AttributeError): test.error("Did not find newly defined bridge '%s'" % net_name) # Prepare default property for network # Transient network can not be set autostart # So confirm persistent is true for test testbr_xml['persistent'] = True # Set network to inactive # Since we do not reboot host to check(instead of restarting libvirtd) # If default network is active, we cannot check "--disable". # Because active network will not be inactive after restarting libvirtd # even we set autostart to False. While inactive network will be active # after restarting libvirtd if we set autostart to True testbr_xml['active'] = False # Prepare options and arguments if net_ref == "netname": net_ref = testbr_xml.name elif net_ref == "netuuid": net_ref = testbr_xml.uuid if disable: net_ref += " --disable" if net_transient: # make the network to transient and active ret = virsh.net_start(net_name) libvirt.check_exit_status(ret) ret = virsh.net_undefine(net_name) libvirt.check_exit_status(ret) logging.debug("after make it transistent: %s" % virsh.net_state_dict()) # Run test case # Use function in virsh module directly for both normal and error test result = virsh.net_autostart(net_ref, extra, readonly=readonly) status = result.exit_status if status: logging.debug("autostart cmd return:\n%s" % result.stderr.strip()) else: logging.debug("set autostart succeed: %s" % virsh.net_state_dict()) # Check if autostart or disable is successful with libvirtd restart. # TODO: Since autostart is designed for host reboot, # we'd better check it with host reboot. autostart_file = '/var/run/libvirt/network/autostarted' check_version = libvirt_version.version_compare(5, 6, 0) if check_version and os.path.exists(autostart_file): logging.debug("the sim_reboot is %s" % sim_reboot) if sim_reboot: os.unlink(autostart_file) utils_libvirtd.libvirtd_restart() # Reopen testbr_xml currents = network_xml.NetworkXML.new_all_networks_dict() current_state = virsh.net_state_dict() logging.debug("After libvirtd reboot, current network(s): %s", current_state) testbr_xml = currents[net_name] is_active = testbr_xml['active'] # undefine the persistent&autostart network, # if "autostart" should change to 'no" if not disable and not net_transient: logging.debug("undefine the persistent/autostart network:") ret = virsh.net_undefine(net_name) libvirt.check_exit_status(ret) # after undefine, the network can not be "autostart" if net_name in virsh.net_list("").stdout.strip(): current_state = virsh.net_state_dict()[net_name] logging.debug("Current network(s): %s", current_state) net_autostart_now = current_state['autostart'] if not status_error and not disable and net_autostart_now: test.fail("transient network can not be autostart") finally: persistent_net = virsh.net_list("--persistent --all").stdout.strip() if net_name in persistent_net: virsh.net_undefine(net_name) active_net = virsh.net_list("").stdout.strip() if net_name in active_net: virsh.net_destroy(net_name) # Check Result if status_error: if status == 0: test.fail("Run successfully with wrong command!") else: if disable: if status or is_active: test.fail("Disable autostart failed.") else: if status: test.fail("The virsh cmd return error when enable autostart!") # If host reboot(sim_reboot=True), the network should be active # If host do not reboot, restart libvirtd will not start inactive # autostart network after libvirt 5.6.0 if sim_reboot: if not is_active: test.fail("Set network autostart failed.") else: if check_version and is_active: test.fail( "net turn active with libvirtd restart without host reboot!" )
def run(test, params, env): """ Test command: virsh net-destroy. The command can forcefully stop a given network. 1.Make sure the network exists. 2.Prepare network status. 3.Perform virsh net-destroy operation. 4.Check if the network has been destroied. 5.Recover network environment. 6.Confirm the test result. """ net_ref = params.get("net_destroy_net_ref") extra = params.get("net_destroy_extra", "") network_name = params.get("net_destroy_network", "default") network_status = params.get("net_destroy_status", "active") status_error = params.get("status_error", "no") # Confirm the network exists. output_all = virsh.net_list("--all").stdout.strip() if not re.search(network_name, output_all): raise error.TestNAError("Make sure the network exists!!") # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(network_name).stdout.strip() elif net_ref == "name": net_ref = network_name # Get status of network and prepare network status. network_current_status = "active" try: if not virsh.net_state_dict()[network_name]['active']: network_current_status = "inactive" if network_status == "active": virsh.net_start(network_name) else: if network_status == "inactive": virsh.net_destroy(network_name) except error.CmdError: raise error.TestError("Prepare network status failed!") status = virsh.net_destroy(net_ref, extra, ignore_status=True).exit_status # Confirm the network has been destroied. if virsh.net_state_dict()[network_name]['active']: status = 1 # Recover network status try: if (network_current_status == "active" and not virsh.net_state_dict()[network_name]['active']): virsh.net_start(network_name) if (network_current_status == "inactive" and virsh.net_state_dict()[network_name]['active']): virsh.net_destroy(network_name) except error.CmdError: raise error.TestError("Recover network status failed!") # 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") else: raise error.TestError("The status_error must be 'yes' or 'no'!")
def run_virsh_net_list(test, params, env): """ Test command: virsh net-list. The command returns list of networks. 1.Get all parameters from configuration. 2.Get current network's status(State, Autostart). 3.Do some prepare works for testing. 4.Perform virsh net-list operation. 5.Recover network status. 6.Confirm the result. """ option = params.get("net_list_option", "") extra = params.get("net_list_extra", "") status_error = params.get("status_error", "no") net_name = params.get("net_list_name", "default") persistent = params.get("net_list_persistent", "yes") net_status = params.get("net_list_error", "active") tmp_xml = os.path.join(test.tmpdir, "tmp.xml") net_current_status = "active" autostart_status = "yes" if not virsh.net_state_dict()[net_name]['active']: net_current_status = "inactive" if not virsh.net_state_dict()[net_name]['autostart']: autostart_status = "no" # Create a transient network. try: if persistent == "no": virsh.net_dumpxml(net_name, to_file=tmp_xml, ignore_status=False) if net_current_status == "inactive": virsh.net_destroy(net_name, ignore_status=False) virsh.net_undefine(net_name, ignore_status=False) virsh.net_create(tmp_xml, ignore_status=False) except error.CmdError: raise error.TestFail("Transient network test failed!") # Prepare network's status for testing. if net_status == "active": try: if not virsh.net_state_dict()[net_name]['active']: virsh.net_start(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Active network test failed!") else: try: if virsh.net_state_dict()[net_name]['active']: virsh.net_destroy(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Inactive network test failed!") result = virsh.net_list(option, extra, ignore_status=True) status = result.exit_status output = result.stdout.strip() # Recover network try: if persistent == "no": virsh.net_destroy(net_name, ignore_status=False) virsh.net_define(tmp_xml, ignore_status=False) if net_current_status == "active": virsh.net_start(net_name, ignore_status=False) if autostart_status == "yes": virsh.net_autostart(net_name, ignore_status=False) else: if net_current_status == "active" and net_status == "inactive": virsh.net_start(net_name, ignore_status=False) elif net_current_status == "inactive" and net_status == "active": virsh.net_destroy(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Recover network failed!") # check result 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 option == "--inactive": if net_status == "active": if re.search(net_name, output): raise error.TestFail("Found an active network with" " --inactive option") else: if persistent == "yes": if not re.search(net_name, output): raise error.TestFail("Found no inactive networks with" " --inactive option") else: # If network is transient, after net-destroy it, # it will disapear. if re.search(net_name, output): raise error.TestFail("Found transient inactive networks" " with --inactive option") elif option == "": if net_status == "active": if not re.search(net_name, output): raise error.TestFail("Can't find active network with no" " option") else: if re.search(net_name, output): raise error.TestFail("Found inactive network with" " no option") elif option == "--all": if net_status == "active": if not re.search(net_name, output): raise error.TestFail("Can't find active network with" " --all option") else: if persistent == "yes": if not re.search(net_name, output): raise error.TestFail("Can't find inactive network with" " --all option") else: # If network is transient, after net-destroy it, # it will disapear. if re.search(net_name, output): raise error.TestFail("Found transient inactive network" " with --all option")
def run(test, params, env): """ Test command: virsh net-autostart. """ # Gather test parameters status_error = "yes" == params.get("status_error", "no") net_ref = params.get("net_autostart_net_ref", "netname") disable = "yes" == params.get("net_autostart_disable", "no") extra = params.get("net_autostart_extra", "") # extra cmd-line params. net_name = params.get("net_autostart_net_name", "autotest") # Prepare environment and record current net_state_dict backup = network_xml.NetworkXML.new_all_networks_dict() backup_state = virsh.net_state_dict() logging.debug("Backed up network(s): %s", backup_state) # Generate our own bridge # First check if a bridge of this name already exists try: _ = backup[net_name] except (KeyError, AttributeError): pass # Not found - good else: test.cancel("Found network bridge '%s' - skipping" % net_name) # Define a very bare bones bridge, don't provide UUID - use whatever # libvirt ends up generating. We need to define a persistent network # since we'll be looking to restart libvirtd as part of this test. # # This test cannot use the 'default' bridge (virbr0) since undefining # it causes issues for libvirtd restart since it's expected that a # default network is defined # temp_bridge = """ <network> <name>%s</name> <bridge name="vir%sbr0"/> </network> """ % (net_name, net_name) try: test_xml = network_xml.NetworkXML(network_name=net_name) test_xml.xml = temp_bridge test_xml.define() except xcepts.LibvirtXMLError as detail: test.error("Failed to define a test network.\n" "Detail: %s." % detail) # To guarantee cleanup will be executed try: # Run test case # Get the updated list and make sure our new bridge exists currents = network_xml.NetworkXML.new_all_networks_dict() current_state = virsh.net_state_dict() logging.debug("Current network(s): %s", current_state) try: testbr_xml = currents[net_name] except (KeyError, AttributeError): test.error("Did not find newly defined bridge '%s'" % net_name) # Prepare default property for network # Transient network can not be set autostart # So confirm persistent is true for test testbr_xml['persistent'] = True # Set network to inactive # Since we do not reboot host to check(instead of restarting libvirtd) # If default network is active, we cannot check "--disable". # Because active network will not be inactive after restarting libvirtd # even we set autostart to False. While inactive network will be active # after restarting libvirtd if we set autostart to True testbr_xml['active'] = False # Prepare options and arguments if net_ref == "netname": net_ref = testbr_xml.name elif net_ref == "netuuid": net_ref = testbr_xml.uuid if disable: net_ref += " --disable" # Run test case # Use function in virsh module directly for both normal and error test result = virsh.net_autostart(net_ref, extra) logging.debug(result) status = result.exit_status # Check if autostart or disable is successful with libvirtd restart. # TODO: Since autostart is designed for host reboot, # we'd better check it with host reboot. utils_libvirtd.libvirtd_restart() # Reopen testbr_xml currents = network_xml.NetworkXML.new_all_networks_dict() current_state = virsh.net_state_dict() logging.debug("Current network(s): %s", current_state) testbr_xml = currents[net_name] is_active = testbr_xml['active'] finally: test_xml.undefine() # Check Result if status_error: if status == 0: test.fail("Run successfully with wrong command!") else: if disable: if status or is_active: test.fail("Disable autostart failed.") else: if status or (not is_active): test.fail("Set network autostart failed.")
def run(test, params, env): """ Test command: virsh net-dhcp-leases 1. Create a new network and run virsh command to check dhcp leases info. 2. Attach an interface before or after start the domain, then check the dhcp leases info. 3. Clean the environment. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) net_name = params.get("net_name", "default") net_option = params.get("net_option", "") status_error = "yes" == params.get("status_error", "no") prepare_net = "yes" == params.get("prepare_net", "yes") hotplug_iface = "yes" == params.get("hotplug_interface", "no") filter_by_mac = "yes" == params.get("filter_by_mac", "no") invalid_mac = "yes" == params.get("invalid_mac", "no") expect_msg = params.get("leases_err_msg") # Generate a random string as the MAC address nic_mac = None if invalid_mac: nic_mac = utils_misc.generate_random_string(17) # Command won't fail on old libvirt if not libvirt_version.version_compare(1, 3, 1) and invalid_mac: logging.debug("Reset case to positive as BZ#1261432") status_error = False def create_network(): """ Create a network """ net_ip_addr = params.get("net_ip_addr", "192.168.200.1") net_ip_netmask = params.get("net_ip_netmask", "255.255.255.0") net_dhcp_start = params.get("net_dhcp_start", "192.168.200.2") net_dhcp_end = params.get("net_dhcp_end", "192.168.200.254") netxml = network_xml.NetworkXML() netxml.name = net_name netxml.forward = {'mode': "nat"} ipxml = network_xml.IPXML() ipxml.address = net_ip_addr ipxml.netmask = net_ip_netmask ipxml.dhcp_ranges = {'start': net_dhcp_start, "end": net_dhcp_end} netxml.set_ip(ipxml) netxml.create() def get_net_dhcp_leases(output): """ Return the dhcp lease info in a list """ leases = [] lines = output.splitlines() if not lines: return leases try: pat = r"\S+\ ?\S+\ ?\S+\ ?\S+|\S+" keys = re.findall(pat, lines[0]) for line in lines[2:]: values = re.findall(pat, line) leases.append(dict(list(zip(keys, values)))) return leases except Exception: test.error("Fail to parse output: %s" % output) def get_ip_by_mac(mac_addr, try_dhclint=False, timeout=120): """ Get interface IP address by given MAC addrss. If try_dhclint is True, then try to allocate IP addrss for the interface. """ session = vm.wait_for_login(login_nic_index, timeout=timeout, serial=True) def f(): return utils_net.get_guest_ip_addr(session, mac_addr) try: ip_addr = utils_misc.wait_for(f, 10) if ip_addr is None: iface_name = utils_net.get_linux_ifname(session, mac_addr) if try_dhclint: session.cmd("dhclient %s" % iface_name) ip_addr = utils_misc.wait_for(f, 10) else: # No IP for the interface, just print the interface name logging.warn("Find '%s' with MAC address '%s', " "but which has no IP address", iface_name, mac_addr) finally: session.close() return ip_addr def check_net_lease(net_leases, expected_find=True): """ Check the dhcp lease info. """ if not net_leases: if expected_find: test.fail("Lease info is empty") else: logging.debug("No dhcp lease info find as expected") else: if not expected_find: test.fail("Find unexpected dhcp lease info: %s" % net_leases) find_mac = False for net_lease in net_leases: net_mac = net_lease['MAC address'] net_ip = net_lease['IP address'][:-3] if vm_xml.VMXML.get_iface_by_mac(vm_name, net_mac): find_mac = True logging.debug("Find '%s' in domain XML", net_mac) else: logging.debug("Not find '%s' in domain XML", net_mac) continue iface_ip = get_ip_by_mac(net_mac) if iface_ip and iface_ip != net_ip: test.fail("Address '%s' is not expected" % iface_ip) if expected_find and not find_mac: test.fail("No matched MAC address") vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) vmxml_backup = vmxml.copy() if vm.is_alive(): vm.destroy(gracefully=False) login_nic_index = 0 new_nic_index = 0 # Cleanup dirty dnsmaq, firstly get all network,and destroy all networks except # default net_state = virsh.net_state_dict(only_names=True) logging.debug("current networks: %s, destroy and undefine networks " "except default!", net_state) for net in net_state: if net != "default": virsh.net_destroy(net) virsh.net_undefine(net) cmd = "ps aux|grep dnsmasq|grep -v grep | grep -v default | awk '{print $2}'" pid_list = results_stdout_52lts(process.run(cmd, shell=True)).strip().splitlines() logging.debug(pid_list) for pid in pid_list: utils_misc.safe_kill(pid, signal.SIGKILL) # Create new network if prepare_net: create_network() nets = virsh.net_state_dict() if net_name not in list(nets.keys()) and not status_error: test.error("Not find network '%s'" % net_name) expected_find = False try: result = virsh.net_dhcp_leases(net_name, mac=nic_mac, options=net_option, debug=True, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) if not status_error: iface_mac = utils_net.generate_mac_address_simple() if filter_by_mac: nic_mac = iface_mac op = "--type network --model virtio --source %s --mac %s" \ % (net_name, iface_mac) nic_params = {'mac': iface_mac, 'nettype': 'bridge', 'ip_version': 'ipv4'} login_timeout = 120 if not hotplug_iface: op += " --config" virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) vm.add_nic(**nic_params) vm.start() new_nic_index = vm.get_nic_index_by_mac(iface_mac) if new_nic_index > 0: login_nic_index = new_nic_index else: vm.start() # wait for VM start before hotplug interface vm.wait_for_serial_login() virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) vm.add_nic(**nic_params) # As VM already started, so the login timeout could be shortened login_timeout = 10 new_interface_ip = get_ip_by_mac(iface_mac, try_dhclint=True, timeout=login_timeout) # Allocate IP address for the new interface may fail, so only # check the result if get new IP address if new_interface_ip: expected_find = True result = virsh.net_dhcp_leases(net_name, mac=nic_mac, debug=False, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) else: if expect_msg: utlv.check_result(result, expect_msg.split(';')) finally: # Delete the new attached interface if new_nic_index > 0: vm.del_nic(new_nic_index) if vm.is_alive(): vm.destroy(gracefully=False) vmxml_backup.sync() if prepare_net: virsh.net_destroy(net_name)
def run(test, params, env): """ Test command: virsh net-list. The command returns list of networks. 1.Get all parameters from configuration. 2.Get current network's status(State, Autostart). 3.Do some prepare works for testing. 4.Perform virsh net-list operation. 5.Recover network status. 6.Confirm the result. """ option = params.get("net_list_option", "") extra = params.get("net_list_extra", "") status_error = params.get("status_error", "no") net_name = params.get("net_list_name", "default") persistent = params.get("net_list_persistent", "yes") net_status = params.get("net_list_error", "active") tmp_xml = os.path.join(test.tmpdir, "tmp.xml") net_current_status = "active" autostart_status = "yes" if not virsh.net_state_dict()[net_name]['active']: net_current_status = "inactive" if not virsh.net_state_dict()[net_name]['autostart']: autostart_status = "no" # acl polkit 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.") # Create a transient network. try: if persistent == "no": virsh.net_dumpxml(net_name, to_file=tmp_xml, ignore_status=False) if net_current_status == "inactive": virsh.net_destroy(net_name, ignore_status=False) virsh.net_undefine(net_name, ignore_status=False) virsh.net_create(tmp_xml, ignore_status=False) except error.CmdError: raise error.TestFail("Transient network test failed!") # Prepare network's status for testing. if net_status == "active": try: if not virsh.net_state_dict()[net_name]['active']: virsh.net_start(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Active network test failed!") else: try: if virsh.net_state_dict()[net_name]['active']: virsh.net_destroy(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Inactive network test failed!") virsh_dargs = {'ignore_status': True} if params.get('setup_libvirt_polkit') == 'yes': virsh_dargs['unprivileged_user'] = unprivileged_user virsh_dargs['uri'] = uri result = virsh.net_list(option, extra, **virsh_dargs) status = result.exit_status output = result.stdout.strip() # Recover network try: if persistent == "no": virsh.net_destroy(net_name, ignore_status=False) virsh.net_define(tmp_xml, ignore_status=False) if net_current_status == "active": virsh.net_start(net_name, ignore_status=False) if autostart_status == "yes": virsh.net_autostart(net_name, ignore_status=False) else: if net_current_status == "active" and net_status == "inactive": virsh.net_start(net_name, ignore_status=False) elif net_current_status == "inactive" and net_status == "active": virsh.net_destroy(net_name, ignore_status=False) except error.CmdError: raise error.TestFail("Recover network failed!") # check result 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 option == "--inactive": if net_status == "active": if re.search(net_name, output): raise error.TestFail("Found an active network with" " --inactive option") else: if persistent == "yes": if not re.search(net_name, output): raise error.TestFail("Found no inactive networks with" " --inactive option") else: # If network is transient, after net-destroy it, # it will disapear. if re.search(net_name, output): raise error.TestFail( "Found transient inactive networks" " with --inactive option") elif option == "": if net_status == "active": if not re.search(net_name, output): raise error.TestFail("Can't find active network with no" " option") else: if re.search(net_name, output): raise error.TestFail("Found inactive network with" " no option") elif option == "--all": if net_status == "active": if not re.search(net_name, output): raise error.TestFail("Can't find active network with" " --all option") else: if persistent == "yes": if not re.search(net_name, output): raise error.TestFail("Can't find inactive network with" " --all option") else: # If network is transient, after net-destroy it, # it will disapear. if re.search(net_name, output): raise error.TestFail("Found transient inactive network" " with --all option")
def run(test, params, env): """ Test command: virsh net-destroy. The command can forcefully stop a given network. 1.Make sure the network exists. 2.Prepare network status. 3.Perform virsh net-destroy operation. 4.Check if the network has been destroied. 5.Recover network environment. 6.Confirm the test result. """ net_ref = params.get("net_destroy_net_ref") extra = params.get("net_destroy_extra", "") network_name = params.get("net_destroy_network", "default") network_status = params.get("net_destroy_status", "active") status_error = params.get("status_error", "no") net_persistent = "yes" == params.get("net_persistent", "yes") net_cfg_file = params.get("net_cfg_file", "/usr/share/libvirt/networks/default.xml") check_libvirtd = "yes" == params.get("check_libvirtd") vm_defined = "yes" == params.get("vm_defined") # libvirt acl polkit related params 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.") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' output_all = virsh.net_list("--all").stdout.strip() # prepare the network status: active, persistent if not re.search(network_name, output_all): if net_persistent: virsh.net_define(net_cfg_file, ignore_status=False) virsh.net_start(network_name, ignore_status=False) else: virsh.create(net_cfg_file, ignore_status=False) if net_persistent: if not virsh.net_state_dict()[network_name]['persistent']: logging.debug("make the network persistent...") make_net_persistent(network_name) else: if virsh.net_state_dict()[network_name]['persistent']: virsh.net_undefine(network_name, ignore_status=False) if not virsh.net_state_dict()[network_name]['active']: if network_status == "active": virsh.net_start(network_name, ignore_status=False) else: if network_status == "inactive": logging.debug("destroy network as we need to test inactive network...") virsh.net_destroy(network_name, ignore_status=False) logging.debug("After prepare: %s" % virsh.net_state_dict()) # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(network_name).stdout.strip() elif net_ref == "name": net_ref = network_name if check_libvirtd: vm_name = params.get("main_vm") if virsh.is_alive(vm_name): virsh.destroy(vm_name) vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) vmxml_backup = vmxml # make sure there is interface with source network as default iface_devices = vmxml.get_devices(device_type="interface") has_default_net = False for iface in iface_devices: source = iface.get_source() if 'network' in source.keys() and source['network'] == 'default': has_default_net = True break elif 'bridge' in source.keys() and source['bridge'] == 'virbr0': has_default_net = True break if not has_default_net: options = "network default --current" virsh.attach_interface(vm_name, options, ignore_status=False) try: if vm_defined: ret = virsh.start(vm_name) else: logging.debug("undefine the vm, then create the vm...") vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) virsh.undefine(vm_name) ret = virsh.create(vmxml.xml) logging.debug(ret.stdout) # check the create or start cmd status utils_test.libvirt.check_exit_status(ret, expect_error=(network_status != 'active')) status = 1 if status_error != 'yes': cmd = "ps -ef | grep /usr/sbin/libvirtd | grep -v grep" # record the libvirt pid then destroy network libvirtd_pid = process.run(cmd, shell=True).stdout_text.strip().split()[1] ret = virsh.net_destroy(net_ref, extra, uri=uri, debug=True, unprivileged_user=unprivileged_user, ignore_status=True) utils_test.libvirt.check_exit_status(ret, expect_error=False) # check_libvirtd pid no change result = check_libvirtd_restart(libvirtd_pid, cmd) if result: test.fail("libvirtd crash after destroy network!") status = 1 else: logging.debug("libvirtd do not crash after destroy network!") status = 0 # destroy vm, check libvirtd pid no change ret = virsh.destroy(vm_name) utils_test.libvirt.check_exit_status(ret, expect_error=False) result = check_libvirtd_restart(libvirtd_pid, cmd) if result: test.fail("libvirtd crash after destroy vm!") status = 1 else: logging.debug("libvirtd do not crash after destroy vm!") status = 0 finally: if not vm_defined: vmxml_backup.define() vmxml_backup.sync() else: readonly = (params.get("net_destroy_readonly", "no") == "yes") status = virsh.net_destroy(net_ref, extra, uri=uri, readonly=readonly, debug=True, unprivileged_user=unprivileged_user, ignore_status=True).exit_status # Confirm the network has been destroied. if net_persistent: if virsh.net_state_dict()[network_name]['active']: status = 1 else: output_all = virsh.net_list("--all").stdout.strip() if re.search(network_name, output_all): status = 1 logging.debug("transient network should not exists after destroy") # Recover network status to system default status try: if network_name not in virsh.net_state_dict(): virsh.net_define(net_cfg_file, ignore_status=False) if not virsh.net_state_dict()[network_name]['active']: virsh.net_start(network_name, ignore_status=False) if not virsh.net_state_dict()[network_name]['persistent']: make_net_persistent(network_name) if not virsh.net_state_dict()[network_name]['autostart']: virsh.net_autostart(network_name, ignore_status=False) except process.CmdError: test.error("Recover network status failed!") # 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") else: test.error("The status_error must be 'yes' or 'no'!")
def run(test, params, env): """ Test command: virsh net-destroy. The command can forcefully stop a given network. 1.Make sure the network exists. 2.Prepare network status. 3.Perform virsh net-destroy operation. 4.Check if the network has been destroied. 5.Recover network environment. 6.Confirm the test result. """ net_ref = params.get("net_destroy_net_ref") extra = params.get("net_destroy_extra", "") network_name = params.get("net_destroy_network", "default") network_status = params.get("net_destroy_status", "active") status_error = params.get("status_error", "no") net_persistent = "yes" == params.get("net_persistent", "yes") net_cfg_file = params.get("net_cfg_file", "/usr/share/libvirt/networks/default.xml") # libvirt acl polkit related params 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.") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' output_all = virsh.net_list("--all").stdout.strip() # prepare the network status: active, persistent if not re.search(network_name, output_all): if net_persistent: virsh.net_define(net_cfg_file, ignore_status=False) virsh.net_start(network_name, ignore_status=False) else: virsh.create(net_cfg_file, ignore_status=False) if net_persistent: if not virsh.net_state_dict()[network_name]['persistent']: logging.debug("!!!make the network persistent") make_net_persistent(network_name) else: if virsh.net_state_dict()[network_name]['persistent']: virsh.net_undefine(network_name, ignore_status=False) if not virsh.net_state_dict()[network_name]['active']: if network_status == "active": virsh.net_start(network_name, ignore_status=False) else: if network_status == "inactive": logging.debug("!!!destroy the network as we need to test inactive") virsh.net_destroy(network_name, ignore_status=False) logging.debug("After prepare: %s" % virsh.net_state_dict()) # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(network_name).stdout.strip() elif net_ref == "name": net_ref = network_name status = virsh.net_destroy(net_ref, extra, uri=uri, debug=True, unprivileged_user=unprivileged_user, ignore_status=True).exit_status # Confirm the network has been destroied. if net_persistent: if virsh.net_state_dict()[network_name]['active']: status = 1 else: output_all = virsh.net_list("--all").stdout.strip() if re.search(network_name, output_all): status = 1 logging.debug("transient network should not exists after destroy") # Recover network status to system default status try: if network_name not in virsh.net_state_dict(): virsh.net_define(net_cfg_file, ignore_status=False) if not virsh.net_state_dict()[network_name]['active']: virsh.net_start(network_name, ignore_status=False) if not virsh.net_state_dict()[network_name]['persistent']: make_net_persistent(network_name) if not virsh.net_state_dict()[network_name]['autostart']: virsh.net_autostart(network_name, ignore_status=False) except process.CmdError: test.error("Recover network status failed!") # 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") else: test.error("The status_error must be 'yes' or 'no'!")
def run(test, params, env): """ Test command: virsh net-dhcp-leases 1. Create a new network and run virsh command to check dhcp leases info. 2. Attach an interface before or after start the domain, then check the dhcp leases info. 3. Clean the environment. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) net_name = params.get("net_name", "default") nic_mac = params.get("nic_mac", "") net_option = params.get("net_option", "") status_error = "yes" == params.get("status_error", "no") prepare_net = "yes" == params.get("prepare_net", "yes") hotplug_iface = "yes" == params.get("hotplug_interface", "no") filter_by_mac = "yes" == params.get("filter_by_mac", "no") exist_bug = params.get("exist_bug") def create_network(): """ Create a network """ net_ip_addr = params.get("net_ip_addr", "192.168.200.1") net_ip_netmask = params.get("net_ip_netmask", "255.255.255.0") net_dhcp_start = params.get("net_dhcp_start", "192.168.200.2") net_dhcp_end = params.get("net_dhcp_end", "192.168.200.254") netxml = network_xml.NetworkXML() netxml.name = net_name netxml.forward = {'mode': "nat"} ipxml = network_xml.IPXML() ipxml.address = net_ip_addr ipxml.netmask = net_ip_netmask ipxml.dhcp_ranges = {'start': net_dhcp_start, "end": net_dhcp_end} netxml.set_ip(ipxml) netxml.create() def get_net_dhcp_leases(output): """ Return the dhcp lease info in a list """ leases = [] lines = output.splitlines() if not lines: return leases try: pat = r"\S+\ ?\S+\ ?\S+\ ?\S+|\S+" keys = re.findall(pat, lines[0]) for line in lines[2:]: values = re.findall(pat, line) leases.append(dict(zip(keys, values))) return leases except: raise error.TestError("Fail to parse output: %s" % output) def get_ip_by_mac(mac_addr, try_dhclint=False): """ Get interface IP address by given MAC addrss. If try_dhclint is True, then try to allocate IP addrss for the interface. """ session = vm.wait_for_login() def f(): return utils_net.get_guest_ip_addr(session, mac_addr) try: ip_addr = utils_misc.wait_for(f, 10) if ip_addr is None: iface_name = utils_net.get_linux_ifname(session, mac_addr) if try_dhclint: session.cmd("dhclient %s" % iface_name) ip_addr = utils_misc.wait_for(f, 10) else: # No IP for the interface, just print the interface name logging.warn("Find '%s' with MAC address '%s', " "but which has no IP address", iface_name, mac_addr) finally: session.close() return ip_addr def check_net_lease(net_leases, expected_find=True): """ Check the dhcp lease info. """ if not net_leases: if expected_find: raise error.TestFail("Lease info is empty") else: logging.debug("No dhcp lease info find as expected") else: if not expected_find: raise error.TestFail("Find unexpected dhcp lease info: %s" % net_leases) find_mac = False for net_lease in net_leases: net_mac = net_lease['MAC address'] net_ip = net_lease['IP address'][:-3] if vm_xml.VMXML.get_iface_by_mac(vm_name, net_mac): find_mac = True logging.debug("Find '%s' in domain XML", net_mac) else: logging.debug("Not find '%s' in domain XML", net_mac) continue iface_ip = get_ip_by_mac(net_mac) if iface_ip and iface_ip != net_ip: raise error.TestFail("Address '%s' is not expected" % iface_ip) if expected_find and not find_mac: raise error.TestFail("No matched MAC address") vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) vmxml_backup = vmxml.copy() # Remove all interfaces of the VM if vm.is_alive(): vm.destroy(gracefully=False) vm.free_mac_address(0) vmxml.remove_all_device_by_type("interface") # Create new network if prepare_net: create_network() nets = virsh.net_state_dict() if net_name not in nets.keys() and not status_error: raise error.TestError("Not find network '%s'" % net_name) expected_find = False try: result = virsh.net_dhcp_leases(net_name, mac=nic_mac, options=net_option, debug=True, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) if not status_error: iface_mac = utils_net.generate_mac_address_simple() if filter_by_mac: nic_mac = iface_mac op = "--type network --source %s --mac %s" % (net_name, iface_mac) if not hotplug_iface: op += " --config" virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) vm.start() else: vm.start() virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) new_interface_ip = get_ip_by_mac(iface_mac, try_dhclint=True) # Allocate IP address for the new interface may fail, so only # check the result if get new IP address if new_interface_ip: expected_find = True result = virsh.net_dhcp_leases(net_name, mac=nic_mac, debug=False, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) finally: if exist_bug: logging.warn("Case may failed as bug: %s", BUG_URL % exist_bug) if vm.is_alive(): vm.destroy(gracefully=False) vmxml_backup.sync() if prepare_net: virsh.net_destroy(net_name)
def run(test, params, env): """ Test command: virsh net-dhcp-leases 1. Create a new network and run virsh command to check dhcp leases info. 2. Attach an interface before or after start the domain, then check the dhcp leases info. 3. Clean the environment. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) net_name = params.get("net_name", "default") nic_mac = params.get("nic_mac", "") net_option = params.get("net_option", "") status_error = "yes" == params.get("status_error", "no") prepare_net = "yes" == params.get("prepare_net", "yes") hotplug_iface = "yes" == params.get("hotplug_interface", "no") filter_by_mac = "yes" == params.get("filter_by_mac", "no") exist_bug = params.get("exist_bug") def create_network(): """ Create a network """ net_ip_addr = params.get("net_ip_addr", "192.168.200.1") net_ip_netmask = params.get("net_ip_netmask", "255.255.255.0") net_dhcp_start = params.get("net_dhcp_start", "192.168.200.2") net_dhcp_end = params.get("net_dhcp_end", "192.168.200.254") netxml = network_xml.NetworkXML() netxml.name = net_name netxml.forward = {'mode': "nat"} ipxml = network_xml.IPXML() ipxml.address = net_ip_addr ipxml.netmask = net_ip_netmask ipxml.dhcp_ranges = {'start': net_dhcp_start, "end": net_dhcp_end} netxml.set_ip(ipxml) netxml.create() def get_net_dhcp_leases(output): """ Return the dhcp lease info in a list """ leases = [] lines = output.splitlines() if not lines: return leases try: pat = r"\S+\ ?\S+\ ?\S+\ ?\S+|\S+" keys = re.findall(pat, lines[0]) for line in lines[2:]: values = re.findall(pat, line) leases.append(dict(zip(keys, values))) return leases except: raise error.TestError("Fail to parse output: %s" % output) def get_ip_by_mac(mac_addr, try_dhclint=False): """ Get interface IP address by given MAC addrss. If try_dhclint is True, then try to allocate IP addrss for the interface. """ session = vm.wait_for_login() def f(): return utils_net.get_guest_ip_addr(session, mac_addr) try: ip_addr = utils_misc.wait_for(f, 10) if ip_addr is None: iface_name = utils_net.get_linux_ifname(session, mac_addr) if try_dhclint: session.cmd("dhclient %s" % iface_name) ip_addr = utils_misc.wait_for(f, 10) else: # No IP for the interface, just print the interface name logging.warn( "Find '%s' with MAC address '%s', " "but which has no IP address", iface_name, mac_addr) finally: session.close() return ip_addr def check_net_lease(net_leases, expected_find=True): """ Check the dhcp lease info. """ if not net_leases: if expected_find: raise error.TestFail("Lease info is empty") else: logging.debug("No dhcp lease info find as expected") else: if not expected_find: raise error.TestFail("Find unexpected dhcp lease info: %s" % net_leases) find_mac = False for net_lease in net_leases: net_mac = net_lease['MAC address'] net_ip = net_lease['IP address'][:-3] if vm_xml.VMXML.get_iface_by_mac(vm_name, net_mac): find_mac = True logging.debug("Find '%s' in domain XML", net_mac) else: logging.debug("Not find '%s' in domain XML", net_mac) continue iface_ip = get_ip_by_mac(net_mac) if iface_ip and iface_ip != net_ip: raise error.TestFail("Address '%s' is not expected" % iface_ip) if expected_find and not find_mac: raise error.TestFail("No matched MAC address") vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) vmxml_backup = vmxml.copy() # Remove all interfaces of the VM if vm.is_alive(): vm.destroy(gracefully=False) vm.free_mac_address(0) vmxml.remove_all_device_by_type("interface") # Create new network if prepare_net: create_network() nets = virsh.net_state_dict() if net_name not in nets.keys() and not status_error: raise error.TestError("Not find network '%s'" % net_name) expected_find = False try: result = virsh.net_dhcp_leases(net_name, mac=nic_mac, options=net_option, debug=True, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) if not status_error: iface_mac = utils_net.generate_mac_address_simple() if filter_by_mac: nic_mac = iface_mac op = "--type network --source %s --mac %s" % (net_name, iface_mac) if not hotplug_iface: op += " --config" virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) vm.start() else: vm.start() virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) new_interface_ip = get_ip_by_mac(iface_mac, try_dhclint=True) # Allocate IP address for the new interface may fail, so only # check the result if get new IP address if new_interface_ip: expected_find = True result = virsh.net_dhcp_leases(net_name, mac=nic_mac, debug=False, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) finally: if exist_bug: logging.warn("Case may failed as bug: %s", BUG_URL % exist_bug) if vm.is_alive(): vm.destroy(gracefully=False) vmxml_backup.sync() if prepare_net: virsh.net_destroy(net_name)
def run(test, params, env): """ Test command: virsh net-destroy. The command can forcefully stop a given network. 1.Make sure the network exists. 2.Prepare network status. 3.Perform virsh net-destroy operation. 4.Check if the network has been destroied. 5.Recover network environment. 6.Confirm the test result. """ net_ref = params.get("net_destroy_net_ref") extra = params.get("net_destroy_extra", "") network_name = params.get("net_destroy_network", "default") network_status = params.get("net_destroy_status", "active") status_error = params.get("status_error", "no") net_persistent = "yes" == params.get("net_persistent", "yes") net_cfg_file = params.get("net_cfg_file", "/usr/share/libvirt/networks/default.xml") check_libvirtd = "yes" == params.get("check_libvirtd") vm_defined = "yes" == params.get("vm_defined") check_vm = "yes" == params.get("check_vm") # libvirt acl polkit related params 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.") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' output_all = virsh.net_list("--all").stdout.strip() # prepare the network status: active, persistent if not re.search(network_name, output_all): if net_persistent: virsh.net_define(net_cfg_file, ignore_status=False) virsh.net_start(network_name, ignore_status=False) else: virsh.create(net_cfg_file, ignore_status=False) # Backup the current network xml net_xml_bk = os.path.join(data_dir.get_tmp_dir(), "%s.xml" % network_name) virsh.net_dumpxml(network_name, to_file=net_xml_bk) if net_persistent: if not virsh.net_state_dict()[network_name]['persistent']: logging.debug("make the network persistent...") virsh.net_define(net_xml_bk) else: if virsh.net_state_dict()[network_name]['persistent']: virsh.net_undefine(network_name, ignore_status=False) if not virsh.net_state_dict()[network_name]['active']: if network_status == "active": virsh.net_start(network_name, ignore_status=False) else: if network_status == "inactive": logging.debug( "destroy network as we need to test inactive network...") virsh.net_destroy(network_name, ignore_status=False) logging.debug("After prepare: %s" % virsh.net_state_dict()) # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(network_name).stdout.strip() elif net_ref == "name": net_ref = network_name if check_libvirtd or check_vm: vm_name = params.get("main_vm") if virsh.is_alive(vm_name): virsh.destroy(vm_name) vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) vmxml_backup = vmxml # make sure there is interface with source network as default iface_devices = vmxml.get_devices(device_type="interface") has_default_net = False for iface in iface_devices: source = iface.get_source() if 'network' in source.keys() and source['network'] == 'default': has_default_net = True break elif 'bridge' in source.keys() and source['bridge'] == 'virbr0': has_default_net = True break if not has_default_net: options = "network default --current" virsh.attach_interface(vm_name, options, ignore_status=False) try: if vm_defined: ret = virsh.start(vm_name) else: logging.debug("undefine the vm, then create the vm...") vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) virsh.undefine(vm_name) ret = virsh.create(vmxml.xml) logging.debug(ret.stdout) # check the create or start cmd status utils_test.libvirt.check_exit_status( ret, expect_error=(network_status != 'active')) status = 1 if status_error != 'yes': libvirtd = utils_libvirtd.Libvirtd("virtqemud") daemon_name = libvirtd.service_name pid_before_run = utils_misc.get_pid(daemon_name) ret = virsh.net_destroy(net_ref, extra, uri=uri, debug=True, unprivileged_user=unprivileged_user, ignore_status=True) utils_test.libvirt.check_exit_status(ret, expect_error=False) # check_libvirtd pid no change pid_after_run = utils_misc.get_pid(daemon_name) if pid_after_run != pid_before_run: test.fail("libvirtd crash after destroy network!") status = 1 else: logging.debug( "libvirtd do not crash after destroy network!") status = 0 if check_libvirtd: # destroy vm, check libvirtd pid no change ret = virsh.destroy(vm_name) utils_test.libvirt.check_exit_status(ret, expect_error=False) pid_after_run2 = utils_misc.get_pid(daemon_name) if pid_after_run2 != pid_before_run: test.fail("libvirtd crash after destroy vm!") status = 1 else: logging.debug( "libvirtd do not crash after destroy vm!") status = 0 elif check_vm: # restart libvirtd and check vm is running libvirtd = utils_libvirtd.Libvirtd() libvirtd.restart() if not virsh.is_alive(vm_name): test.fail( "vm shutdown when transient network destroyed then libvirtd restart" ) else: status = 0 finally: if not vm_defined: vmxml_backup.define() vmxml_backup.sync() else: readonly = (params.get("net_destroy_readonly", "no") == "yes") status = virsh.net_destroy(net_ref, extra, uri=uri, readonly=readonly, debug=True, unprivileged_user=unprivileged_user, ignore_status=True).exit_status # Confirm the network has been destroyed. if net_persistent: if virsh.net_state_dict()[network_name]['active']: status = 1 else: output_all = virsh.net_list("--all").stdout.strip() if re.search(network_name, output_all): status = 1 logging.debug( "transient network should not exists after destroy") # Recover network status to system default status try: if network_name not in virsh.net_state_dict(): virsh.net_define(net_xml_bk, ignore_status=False) if not virsh.net_state_dict()[network_name]['active']: virsh.net_start(network_name, ignore_status=False) if not virsh.net_state_dict()[network_name]['persistent']: virsh.net_define(net_xml_bk, ignore_status=False) if not virsh.net_state_dict()[network_name]['autostart']: virsh.net_autostart(network_name, ignore_status=False) except process.CmdError: test.error("Recover network status failed!") # Clean up the backup network xml file if os.path.isfile(net_xml_bk): data_dir.clean_tmp_files() logging.debug("Cleaning up the network backup 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") else: test.error("The status_error must be 'yes' or 'no'!")
def run_virsh_net_destroy(test, params, env): """ Test command: virsh net-destroy. The command can forcefully stop a given network. 1.Make sure the network exists. 2.Prepare network status. 3.Perform virsh net-destroy operation. 4.Check if the network has been destroied. 5.Recover network environment. 6.Confirm the test result. """ net_ref = params.get("net_destroy_net_ref") extra = params.get("net_destroy_extra", "") network_name = params.get("net_destroy_network", "default") network_status = params.get("net_destroy_status", "active") status_error = params.get("status_error", "no") # Confirm the network exists. output_all = virsh.net_list("--all").stdout.strip() if not re.search(network_name, output_all): raise error.TestNAError("Make sure the network exists!!") # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(network_name).stdout.strip() elif net_ref == "name": net_ref = network_name # Get status of network and prepare network status. network_current_status = "active" try: if not virsh.net_state_dict()[network_name]['active']: network_current_status = "inactive" if network_status == "active": virsh.net_start(network_name) else: if network_status == "inactive": virsh.net_destroy(network_name) except error.CmdError: raise error.TestError("Prepare network status failed!") status = virsh.net_destroy(net_ref, extra, ignore_status=True).exit_status # Confirm the network has been destroied. if virsh.net_state_dict()[network_name]['active']: status = 1 # Recover network status try: if (network_current_status == "active" and not virsh.net_state_dict()[network_name]['active']): virsh.net_start(network_name) if (network_current_status == "inactive" and virsh.net_state_dict()[network_name]['active']): virsh.net_destroy(network_name) except error.CmdError: raise error.TestError("Recover network status failed!") # 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") else: raise error.TestError("The status_error must be 'yes' or 'no'!")
def run(test, params, env): """ Test command: virsh net-dhcp-leases 1. Create a new network and run virsh command to check dhcp leases info. 2. Attach an interface before or after start the domain, then check the dhcp leases info. 3. Clean the environment. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) net_name = params.get("net_name", "default") net_option = params.get("net_option", "") status_error = "yes" == params.get("status_error", "no") prepare_net = "yes" == params.get("prepare_net", "yes") hotplug_iface = "yes" == params.get("hotplug_interface", "no") filter_by_mac = "yes" == params.get("filter_by_mac", "no") invalid_mac = "yes" == params.get("invalid_mac", "no") expect_msg = params.get("leases_err_msg") # upstream expect msg may change on new libvirt new_expect_msg = params.get("new_leases_err_msg") range_lease = eval(params.get("range_lease", "None")) host_lease = eval(params.get("host_lease", "None")) host = eval(params.get("host", "None")) invalid_lease = "yes" == params.get("invalid_lease", "no") blank_lease = "yes" == params.get("blank_lease", "no") if (host_lease or range_lease) and not libvirt_version.version_compare(6, 2, 0): test.cancel( "Don't support: libvirt support lease setting since 6.2.0!") # Generate a random string as the MAC address nic_mac = None if invalid_mac: nic_mac = utils_misc.generate_random_string(17) # Command won't fail on old libvirt if not libvirt_version.version_compare(1, 3, 1) and invalid_mac: logging.debug("Reset case to positive as BZ#1261432") status_error = False def create_network(): """ Create a network """ net_ip_addr = params.get("net_ip_addr", "192.168.200.1") net_ip_netmask = params.get("net_ip_netmask", "255.255.255.0") net_dhcp_start = params.get("net_dhcp_start", "192.168.200.2") net_dhcp_end = params.get("net_dhcp_end", "192.168.200.254") netxml = network_xml.NetworkXML() netxml.name = net_name netxml.forward = {'mode': "nat"} range = network_xml.RangeXML() range.attrs = {'start': net_dhcp_start, "end": net_dhcp_end} ipxml = network_xml.IPXML() if range_lease: range.lease_attrs = range_lease ipxml.address = net_ip_addr ipxml.netmask = net_ip_netmask ipxml.dhcp_ranges = range if host: new_host = network_xml.DhcpHostXML() new_host.attrs = host new_host.lease_attrs = host_lease ipxml.hosts = [new_host] netxml.set_ip(ipxml) netxml.create() def get_net_dhcp_leases(output): """ Return the dhcp lease info in a list """ leases = [] lines = output.splitlines() if not lines: return leases try: pat = r"\S+\ ?\S+\ ?\S+\ ?\S+|\S+" keys = re.findall(pat, lines[0]) for line in lines[2:]: values = re.findall(pat, line) leases.append(dict(list(zip(keys, values)))) return leases except Exception: test.error("Fail to parse output: %s" % output) def check_lease_time(ex_time, duration): """ Compare the expiry time from the virsh cmd output and the setting :param ex_time: text, the expiry time get from the net-dhcp-lease output :param duration: dict, the configured expiry time """ now_time = datetime.now() # convert the lease time from str to the datetime structure # lease is in format like: 2021-01-18 02:15:35 get_ex_time = datetime.strptime(ex_time, '%Y-%m-%d %H:%M:%S') if duration['expiry'] == '0': if get_ex_time > now_time: test.fail("The expiry time is not correct!!") if 'unit' not in duration: duration['unit'] = 'minutes' else: if duration['unit'] == 'seconds': dur_sec = int(duration['expiry']) elif duration['unit'] == 'hours': dur_sec = int(duration['expiry']) * 3600 else: dur_sec = int(duration['expiry']) * 60 delta = get_ex_time - now_time logging.debug( "The get_ex_time is %s, the now_time is %s, " "duration is %s", get_ex_time, now_time, duration) if delta > timedelta(seconds=dur_sec): test.fail("Get expiry time %s longer than the setting %s!!" % (delta, timedelta(seconds=dur_sec))) elif delta < timedelta(seconds=(dur_sec - 30)): test.fail("Get expiry time %s shorter than the setting %s" % (delta, timedelta(seconds=dur_sec))) else: logging.info("Get expected lease info.") return None def get_ip_by_mac(mac_addr, try_dhclint=False, timeout=120): """ Get interface IP address by given MAC addrss. If try_dhclint is True, then try to allocate IP addrss for the interface. """ session = vm.wait_for_login(login_nic_index, timeout=timeout, serial=True) def f(): return utils_net.get_guest_ip_addr(session, mac_addr) try: ip_addr = utils_misc.wait_for(f, 10) if ip_addr is None: iface_name = utils_net.get_linux_ifname(session, mac_addr) if try_dhclint: session.cmd("dhclient %s" % iface_name) ip_addr = utils_misc.wait_for(f, 10) else: # No IP for the interface, just print the interface name logging.warn( "Find '%s' with MAC address '%s', " "but which has no IP address", iface_name, mac_addr) finally: session.close() return ip_addr def check_net_lease(net_leases, expected_find=True): """ Check the dhcp lease info. """ if not net_leases: if expected_find: test.fail("Lease info is empty") else: logging.debug("No dhcp lease info find as expected") else: if not expected_find: test.fail("Find unexpected dhcp lease info: %s" % net_leases) find_mac = False for net_lease in net_leases: net_mac = net_lease['MAC address'] net_ip = net_lease['IP address'][:-3] expiry_time = net_lease['Expiry Time'] if vm_xml.VMXML.get_iface_by_mac(vm_name, net_mac): find_mac = True logging.debug("Find '%s' in domain XML", net_mac) else: logging.debug("Not find '%s' in domain XML", net_mac) continue iface_ip = get_ip_by_mac(net_mac) if iface_ip and iface_ip != net_ip: test.fail("Address '%s' is not expected" % iface_ip) #check if lease time is correct if libvirt_version.version_compare(6, 2, 0): if host_lease and net_mac == host['mac']: check_lease_time(expiry_time, host_lease) elif range_lease: check_lease_time(expiry_time, range_lease) if expected_find and not find_mac: test.fail("No matched MAC address") vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) vmxml_backup = vmxml.copy() if vm.is_alive(): vm.destroy(gracefully=False) login_nic_index = 0 new_nic_index = 0 # Cleanup dirty dnsmaq, firstly get all network,and destroy all networks except # default net_state = virsh.net_state_dict(only_names=True) logging.debug( "current networks: %s, destroy and undefine networks " "except default!", net_state) for net in net_state: if net != "default": virsh.net_destroy(net) virsh.net_undefine(net) cmd = "ps aux|grep dnsmasq|grep -v grep | grep -v default | awk '{print $2}'" pid_list = process.run(cmd, shell=True).stdout_text.strip().splitlines() logging.debug(pid_list) for pid in pid_list: utils_misc.safe_kill(pid, signal.SIGKILL) try: # Create new network if prepare_net: nets_old = virsh.net_state_dict() if net_name in list(nets_old.keys()): virsh.net_destroy(net_name) virsh.net_undefine(net_name) create_network() nets = virsh.net_state_dict() if net_name not in list(nets.keys()) and not status_error: test.error("Not find network '%s'" % net_name) expected_find = False result = virsh.net_dhcp_leases(net_name, mac=nic_mac, options=net_option, debug=True, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) if not status_error: if host: iface_mac = host['mac'] else: iface_mac = utils_net.generate_mac_address_simple() if filter_by_mac: nic_mac = iface_mac op = "--type network --model virtio --source %s --mac %s" \ % (net_name, iface_mac) nic_params = { 'mac': iface_mac, 'nettype': 'bridge', 'ip_version': 'ipv4' } login_timeout = 120 if not hotplug_iface: op += " --config" virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) vm.add_nic(**nic_params) vm.start() new_nic_index = vm.get_nic_index_by_mac(iface_mac) if new_nic_index > 0: login_nic_index = new_nic_index else: vm.start() # wait for VM start before hotplug interface vm.wait_for_serial_login() virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) vm.add_nic(**nic_params) # As VM already started, so the login timeout could be shortened login_timeout = 10 new_interface_ip = get_ip_by_mac(iface_mac, try_dhclint=True, timeout=login_timeout) if new_interface_ip: expected_find = True result = virsh.net_dhcp_leases(net_name, mac=nic_mac, debug=False, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) else: if expect_msg: utlv.check_result(result, expect_msg.split(';')) except LibvirtXMLError as e: if status_error and invalid_lease: if blank_lease and libvirt_version.version_compare(7, 1, 0): expect_msg = new_expect_msg if expect_msg not in e.details: test.fail("Network create fail unexpected: %s" % e.details) else: logging.debug("Network create fail expected: %s", e.details) finally: # Delete the new attached interface if new_nic_index > 0: vm.del_nic(new_nic_index) if vm.is_alive(): vm.destroy(gracefully=False) vmxml_backup.sync() if prepare_net: virsh.net_destroy(net_name)
test_xml.xml = virtual_net if test_create: test_xml.create() else: test_xml.define() except xcepts.LibvirtXMLError, detail: raise error.TestNAError("Failed to define a test network.\n" "Detail: %s." % detail) # Run test case try: libvirtd = utils_libvirtd.Libvirtd() if test_create: # Restart libvirtd and check state libvirtd.restart() net_state = virsh.net_state_dict() if (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or net_state[net_name]['persistent']): raise error.TestFail("Found wrong network states" " after restarting libvirtd: %s" % net_state) edit_net_xml() if test_create: # Network become persistent after editing net_state = virsh.net_state_dict() if (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or not net_state[net_name]['persistent']): raise error.TestFail("Found wrong network states" " after editing: %s" % net_state)
def run_virsh_net_dumpxml(test, params, env): """ Test command: virsh net-dumpxml. This command can output the network information as an XML dump to stdout. 1.Get all parameters from config file. 2.If test case's network status is inactive, destroy it. 3.Perform virsh net-dumpxml operation. 4.Recover test environment(network status). 5.Confirm the test result. """ status_error = params.get("status_error", "no") net_ref = params.get("net_dumpxml_net_ref") net_name = params.get("net_dumpxml_network", "default") net_status = params.get("net_dumpxml_network_status", "active") xml_flie = params.get("net_dumpxml_xml_file", "default.xml") extra = params.get("net_dumpxml_extra", "") network_xml = os.path.join(test.tmpdir, xml_flie) # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(net_name).stdout.strip() elif net_ref == "name": net_ref = net_name net_status_current = "active" if not virsh.net_state_dict()[net_name]['active']: net_status_current = "inactive" if not virsh.net_state_dict()[net_name]['persistent']: raise error.TestError("Network is transient!") try: if net_status == "inactive" and net_status_current == "active": status_destroy = virsh.net_destroy(net_name, ignore_status=True).exit_status if status_destroy != 0: raise error.TestError("Network destroied failed!") result = virsh.net_dumpxml(net_ref, extra, network_xml, ignore_status=True) status = result.exit_status err = result.stderr.strip() xml_validate_cmd = "virt-xml-validate %s network" % network_xml valid_s = utils.run(xml_validate_cmd, ignore_status=True).exit_status # Check option valid or not. if extra.find("--") != -1: options = extra.split("--") for option in options: if option.strip() == "": continue if not virsh.has_command_help_match("net-dumpxml", option.strip()): status_error = "yes" break finally: # Recover network if net_status == "inactive" and net_status_current == "active": status_start = virsh.net_start(net_name, ignore_status=True).exit_status if status_start != 0: raise error.TestError("Network started failed!") # Check status_error if status_error == "yes": if status == 0: raise error.TestFail("Run successfully with wrong command!") if err == "": raise error.TestFail("The wrong command has no error outputed!") elif status_error == "no": if status != 0: raise error.TestFail("Run failed with right command!") if valid_s != 0: raise error.TestFail("Command output is invalid!") else: raise error.TestError("The status_error must be 'yes' or 'no'!")
def run(test, params, env): """ Test command: virsh net-dhcp-leases 1. Create a new network and run virsh command to check dhcp leases info. 2. Attach an interface before or after start the domain, then check the dhcp leases info. 3. Clean the environment. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) net_name = params.get("net_name", "default") net_option = params.get("net_option", "") status_error = "yes" == params.get("status_error", "no") prepare_net = "yes" == params.get("prepare_net", "yes") hotplug_iface = "yes" == params.get("hotplug_interface", "no") filter_by_mac = "yes" == params.get("filter_by_mac", "no") invalid_mac = "yes" == params.get("invalid_mac", "no") expect_msg = params.get("leases_err_msg") # Generate a random string as the MAC address nic_mac = None if invalid_mac: nic_mac = utils_misc.generate_random_string(17) # Command won't fail on old libvirt if not libvirt_version.version_compare(1, 3, 1) and invalid_mac: logging.debug("Reset case to positive as BZ#1261432") status_error = False def create_network(): """ Create a network """ net_ip_addr = params.get("net_ip_addr", "192.168.200.1") net_ip_netmask = params.get("net_ip_netmask", "255.255.255.0") net_dhcp_start = params.get("net_dhcp_start", "192.168.200.2") net_dhcp_end = params.get("net_dhcp_end", "192.168.200.254") netxml = network_xml.NetworkXML() netxml.name = net_name netxml.forward = {'mode': "nat"} ipxml = network_xml.IPXML() ipxml.address = net_ip_addr ipxml.netmask = net_ip_netmask ipxml.dhcp_ranges = {'start': net_dhcp_start, "end": net_dhcp_end} netxml.set_ip(ipxml) netxml.create() def get_net_dhcp_leases(output): """ Return the dhcp lease info in a list """ leases = [] lines = output.splitlines() if not lines: return leases try: pat = r"\S+\ ?\S+\ ?\S+\ ?\S+|\S+" keys = re.findall(pat, lines[0]) for line in lines[2:]: values = re.findall(pat, line) leases.append(dict(list(zip(keys, values)))) return leases except Exception: test.error("Fail to parse output: %s" % output) def get_ip_by_mac(mac_addr, try_dhclint=False, timeout=120): """ Get interface IP address by given MAC addrss. If try_dhclint is True, then try to allocate IP addrss for the interface. """ session = vm.wait_for_login(login_nic_index, timeout=timeout, serial=True) def f(): return utils_net.get_guest_ip_addr(session, mac_addr) try: ip_addr = utils_misc.wait_for(f, 10) if ip_addr is None: iface_name = utils_net.get_linux_ifname(session, mac_addr) if try_dhclint: session.cmd("dhclient %s" % iface_name) ip_addr = utils_misc.wait_for(f, 10) else: # No IP for the interface, just print the interface name logging.warn( "Find '%s' with MAC address '%s', " "but which has no IP address", iface_name, mac_addr) finally: session.close() return ip_addr def check_net_lease(net_leases, expected_find=True): """ Check the dhcp lease info. """ if not net_leases: if expected_find: test.fail("Lease info is empty") else: logging.debug("No dhcp lease info find as expected") else: if not expected_find: test.fail("Find unexpected dhcp lease info: %s" % net_leases) find_mac = False for net_lease in net_leases: net_mac = net_lease['MAC address'] net_ip = net_lease['IP address'][:-3] if vm_xml.VMXML.get_iface_by_mac(vm_name, net_mac): find_mac = True logging.debug("Find '%s' in domain XML", net_mac) else: logging.debug("Not find '%s' in domain XML", net_mac) continue iface_ip = get_ip_by_mac(net_mac) if iface_ip and iface_ip != net_ip: test.fail("Address '%s' is not expected" % iface_ip) if expected_find and not find_mac: test.fail("No matched MAC address") vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name) vmxml_backup = vmxml.copy() if vm.is_alive(): vm.destroy(gracefully=False) login_nic_index = 0 new_nic_index = 0 # Cleanup dirty dnsmaq, firstly get all network,and destroy all networks except # default net_state = virsh.net_state_dict(only_names=True) logging.debug( "current networks: %s, destroy and undefine networks " "except default!", net_state) for net in net_state: if net != "default": virsh.net_destroy(net) virsh.net_undefine(net) cmd = "ps aux|grep dnsmasq|grep -v grep | grep -v default | awk '{print $2}'" pid_list = process.run(cmd, shell=True).stdout_text.strip().splitlines() logging.debug(pid_list) for pid in pid_list: utils_misc.safe_kill(pid, signal.SIGKILL) # Create new network if prepare_net: create_network() nets = virsh.net_state_dict() if net_name not in list(nets.keys()) and not status_error: test.error("Not find network '%s'" % net_name) expected_find = False try: result = virsh.net_dhcp_leases(net_name, mac=nic_mac, options=net_option, debug=True, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) if not status_error: iface_mac = utils_net.generate_mac_address_simple() if filter_by_mac: nic_mac = iface_mac op = "--type network --model virtio --source %s --mac %s" \ % (net_name, iface_mac) nic_params = { 'mac': iface_mac, 'nettype': 'bridge', 'ip_version': 'ipv4' } login_timeout = 120 if not hotplug_iface: op += " --config" virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) vm.add_nic(**nic_params) vm.start() new_nic_index = vm.get_nic_index_by_mac(iface_mac) if new_nic_index > 0: login_nic_index = new_nic_index else: vm.start() # wait for VM start before hotplug interface vm.wait_for_serial_login() virsh.attach_interface(vm_name, option=op, debug=True, ignore_status=False) vm.add_nic(**nic_params) # As VM already started, so the login timeout could be shortened login_timeout = 10 new_interface_ip = get_ip_by_mac(iface_mac, try_dhclint=True, timeout=login_timeout) # Allocate IP address for the new interface may fail, so only # check the result if get new IP address if new_interface_ip: expected_find = True result = virsh.net_dhcp_leases(net_name, mac=nic_mac, debug=False, ignore_status=True) utlv.check_exit_status(result, status_error) lease = get_net_dhcp_leases(result.stdout.strip()) check_net_lease(lease, expected_find) else: if expect_msg: utlv.check_result(result, expect_msg.split(';')) finally: # Delete the new attached interface if new_nic_index > 0: vm.del_nic(new_nic_index) if vm.is_alive(): vm.destroy(gracefully=False) vmxml_backup.sync() if prepare_net: virsh.net_destroy(net_name)
def run(test, params, env): """ Test command: virsh net-destroy. The command can forcefully stop a given network. 1.Make sure the network exists. 2.Prepare network status. 3.Perform virsh net-destroy operation. 4.Check if the network has been destroied. 5.Recover network environment. 6.Confirm the test result. """ net_ref = params.get("net_destroy_net_ref") extra = params.get("net_destroy_extra", "") network_name = params.get("net_destroy_network", "default") network_status = params.get("net_destroy_status", "active") status_error = params.get("status_error", "no") # libvirt acl polkit related params 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.") uri = params.get("virsh_uri") unprivileged_user = params.get('unprivileged_user') if unprivileged_user: if unprivileged_user.count('EXAMPLE'): unprivileged_user = '******' # Confirm the network exists. output_all = virsh.net_list("--all").stdout.strip() if not re.search(network_name, output_all): raise error.TestNAError("Make sure the network exists!!") # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(network_name).stdout.strip() elif net_ref == "name": net_ref = network_name # Get status of network and prepare network status. network_current_status = "active" try: if not virsh.net_state_dict()[network_name]['active']: network_current_status = "inactive" if network_status == "active": virsh.net_start(network_name) else: if network_status == "inactive": virsh.net_destroy(network_name) except process.CmdError: raise error.TestError("Prepare network status failed!") status = virsh.net_destroy(net_ref, extra, uri=uri, debug=True, unprivileged_user=unprivileged_user, ignore_status=True).exit_status # Confirm the network has been destroied. if virsh.net_state_dict()[network_name]['active']: status = 1 # Recover network status try: if (network_current_status == "active" and not virsh.net_state_dict()[network_name]['active']): virsh.net_start(network_name) if (network_current_status == "inactive" and virsh.net_state_dict()[network_name]['active']): virsh.net_destroy(network_name) except process.CmdError: raise error.TestError("Recover network status failed!") # 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") else: raise error.TestError("The status_error must be 'yes' or 'no'!")
def run(test, params, env): """ Test command: virsh net-dumpxml. This command can output the network information as an XML dump to stdout. 1.Get all parameters from config file. 2.If test case's network status is inactive, destroy it. 3.Perform virsh net-dumpxml operation. 4.Recover test environment(network status). 5.Confirm the test result. """ status_error = params.get("status_error", "no") net_ref = params.get("net_dumpxml_net_ref") net_name = params.get("net_dumpxml_network", "default") net_status = params.get("net_dumpxml_network_status", "active") xml_flie = params.get("net_dumpxml_xml_file", "default.xml") extra = params.get("net_dumpxml_extra", "") network_xml = os.path.join(test.tmpdir, xml_flie) # acl polkit 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.") # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(net_name).stdout.strip() elif net_ref == "name": net_ref = net_name net_status_current = "active" if not virsh.net_state_dict()[net_name]['active']: net_status_current = "inactive" if not virsh.net_state_dict()[net_name]['persistent']: test.error("Network is transient!") try: if net_status == "inactive" and net_status_current == "active": status_destroy = virsh.net_destroy(net_name, ignore_status=True).exit_status if status_destroy != 0: test.error("Network destroied failed!") virsh_dargs = {'ignore_status': True} if params.get('setup_libvirt_polkit') == 'yes': virsh_dargs['unprivileged_user'] = unprivileged_user virsh_dargs['uri'] = uri result = virsh.net_dumpxml(net_ref, extra, network_xml, **virsh_dargs) status = result.exit_status err = result.stderr.strip() xml_validate_cmd = "virt-xml-validate %s network" % network_xml valid_s = process.run(xml_validate_cmd, ignore_status=True, shell=True).exit_status # Check option valid or not. if extra.find("--") != -1: options = extra.split("--") for option in options: if option.strip() == "": continue if not virsh.has_command_help_match("net-dumpxml", option.strip()) and\ status_error == "no": test.cancel("The current libvirt version" " doesn't support '%s' option" % option.strip()) finally: # Recover network if net_status == "inactive" and net_status_current == "active": status_start = virsh.net_start(net_name, ignore_status=True).exit_status if status_start != 0: test.error("Network started failed!") # Check status_error if status_error == "yes": if status == 0: test.fail("Run successfully with wrong command!") if err == "": test.fail("The wrong command has no error outputed!") elif status_error == "no": if status != 0: test.fail("Run failed with right command!") if valid_s != 0: test.fail("Command output is invalid!") else: test.error("The status_error must be 'yes' or 'no'!")
def run(test, params, env): """ Test command: virsh net-list. The command returns list of networks. 1.Get all parameters from configuration. 2.Get current network's status(State, Autostart). 3.Do some prepare works for testing. 4.Perform virsh net-list operation. 5.Recover network status. 6.Confirm the result. """ option = params.get("net_list_option", "") extra = params.get("net_list_extra", "") status_error = params.get("status_error", "no") set_status = params.get("set_status", "active") set_persistent = params.get("set_persistent", "persistent") set_autostart = params.get("set_autostart", "autostart") error_msg = params.get("error_msg", "") net_name = params.get("net_name", "net-br") net_xml = network_xml.NetworkXML(network_name=net_name) # acl polkit 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 exceptions.TestSkipError("API acl test not supported" " in current libvirt version.") # Record current net_state_dict net_backup = network_xml.NetworkXML.new_all_networks_dict() net_backup_state = virsh.net_state_dict() logging.debug("Backed up network(s): %s", net_backup_state) # Check the network name is not duplicated try: _ = net_backup[net_name] except (KeyError, AttributeError): pass else: raise exceptions.TestSkipError("Duplicated network name: '%s'" % net_name) # Default the network is persistent, active, autostart # Create a persistent/transient network. if set_persistent == "persistent": net_xml.define() logging.debug("Created persistent network") else: net_xml.create() logging.debug("Created transient network") # Prepare an active/inactive network # For the new defined network, it's inactive by default if set_status == "active" and set_persistent == "persistent": net_xml.start() # Prepare an autostart/no-autostart network # For the new create network, it's no-autostart by default if set_autostart == "autostart": net_xml.set_autostart(True) try: virsh_dargs = {'ignore_status': True, 'debug': True} if params.get('setup_libvirt_polkit') == 'yes': virsh_dargs['unprivileged_user'] = unprivileged_user virsh_dargs['uri'] = uri ret = virsh.net_list(option, extra, **virsh_dargs) output = ret.stdout.strip() # Check test results if status_error == "yes": # Check the results with error parameter if error_msg: libvirt.check_result(ret, error_msg) # Check the results with correct option but inconsistent network status else: libvirt.check_exit_status(ret) if re.search(net_name, output): raise exceptions.TestFail( "virsh net-list %s get wrong results" % option) # Check the results with correct option and consistent network status else: libvirt.check_exit_status(ret) if option == "--uuid": uuid = virsh.net_uuid(net_name).stdout.strip() if not re.search(uuid, output): raise exceptions.TestFail( "Failed to find network: '%s' with:" "virsh net-list '%s'." % (net_name, option)) else: if not re.search(net_name, output): raise exceptions.TestFail( "Failed to find network: '%s' with:" "virsh net-list '%s'." % (net_name, option)) finally: # Recover network try: if set_status == "active": net_xml.del_active() if set_persistent == "persistent": net_xml.del_defined() except Exception: virsh.net_undefine()
def run(test, params, env): """ Test command: virsh net-edit <network> 1) Define a temp virtual network 2) Execute virsh net-edit to modify it 3) Dump its xml then check it """ def edit_net_xml(): edit_cmd = r":%s /100.254/100.253" session = aexpect.ShellSession("sudo -s") try: logging.info("Execute virsh net-edit %s", net_name) session.sendline("virsh net-edit %s" % net_name) logging.info("Change the ip value of dhcp end") session.sendline(edit_cmd) session.send('\x1b') session.send('ZZ') remote.handle_prompts(session, None, None, r"[\#\$]\s*$") session.close() except (aexpect.ShellError, aexpect.ExpectError) as details: log = session.get_output() session.close() test.fail("Failed to do net-edit: %s\n%s" % (details, log)) # Gather test parameters net_name = params.get("net_edit_net_name", "editnet") test_create = "yes" == params.get("test_create", "no") virsh_dargs = {'debug': True, 'ignore_status': True} virsh_instance = virsh.VirshPersistent(**virsh_dargs) # Get all network instance nets = network_xml.NetworkXML.new_all_networks_dict(virsh_instance) # First check if a bridge of this name already exists # Increment suffix integer from 1 then append it to net_name # till there is no name conflict. if net_name in nets: net_name_fmt = net_name + "%d" suffix_num = 1 while ((net_name_fmt % suffix_num) in nets): suffix_num += 1 net_name = net_name_fmt % suffix_num virtual_net = """ <network> <name>%s</name> <forward mode='nat'/> <bridge name='%s' stp='on' delay='0' /> <mac address='52:54:00:03:78:6c'/> <ip address='192.168.100.1' netmask='255.255.255.0'> <dhcp> <range start='192.168.100.2' end='192.168.100.254' /> </dhcp> </ip> </network> """ % (net_name, net_name) try: test_xml = network_xml.NetworkXML(network_name=net_name) test_xml.xml = virtual_net if test_create: test_xml.create() else: test_xml.define() except xcepts.LibvirtXMLError as detail: test.cancel("Failed to define a test network.\n" "Detail: %s." % detail) # Run test case try: libvirtd = utils_libvirtd.Libvirtd() if test_create: # Restart libvirtd and check state libvirtd.restart() net_state = virsh.net_state_dict() if (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or net_state[net_name]['persistent']): test.fail("Found wrong network states" " after restarting libvirtd: %s" % net_state) else: libvirtd.restart() net_state = virsh.net_state_dict() if (net_state[net_name]['active'] or net_state[net_name]['autostart'] or not net_state[net_name]['persistent']): test.fail("Found wrong network states: %s" % net_state) virsh.net_start(net_name) edit_net_xml() if test_create: # Network become persistent after editing net_state = virsh.net_state_dict() if (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or not net_state[net_name]['persistent']): test.fail("Found wrong network states" " after editing: %s" % net_state) cmd_result = virsh.net_dumpxml(net_name, '--inactive', debug=True) if cmd_result.exit_status: test.fail("Failed to dump xml of virtual network %s" % net_name) # The xml should contain the match_string match_string = "100.253" xml = cmd_result.stdout.strip() if not re.search(match_string, xml): test.fail("The xml is not expected") # The active xml should not contain the match_string cmd_result = virsh.net_dumpxml(net_name, debug=True) if cmd_result.exit_status: test.fail("Failed to dump active xml of virtual network %s" % net_name) # The xml should contain the match_string match_string = "100.253" xml = cmd_result.stdout.strip() if re.search(match_string, xml): test.fail("The active xml should not change") finally: test_xml.orbital_nuclear_strike()
def vm_check(status_error): """ Checking the VM """ if status_error: return if output_mode == 'json' and not check_json_output(params): test.fail('check json output failed') if output_mode == 'local' and not check_local_output(params): test.fail('check local output failed') if output_mode in ['null', 'json', 'local']: return # vmchecker must be put before skip_vm_check in order to clean up # the VM. vmchecker = VMChecker(test, params, env) params['vmchecker'] = vmchecker if skip_vm_check == 'yes': logging.info('Skip checking vm after conversion: %s' % skip_reason) return if output_mode == 'rhev': if not utils_v2v.import_vm_to_ovirt( params, address_cache, timeout=v2v_timeout): test.fail('Import VM failed') elif output_mode == 'libvirt': virsh.start(vm_name, debug=True) # Check guest following the checkpoint document after conversion logging.info('Checking common checkpoints for v2v') if 'ogac' in checkpoint: # windows guests will reboot at any time after qemu-ga is # installed. The process cannot be controlled. In order to # don't break vmchecker.run() process, It's better to put # check_windows_ogac before vmchecker.run(). Because in # check_windows_ogac, it waits until rebooting completes. vmchecker.checker.create_session() if os_type == 'windows': services = ['qemu-ga'] if not utils_v2v.multiple_versions_compare( V2V_UNSUPPORT_RHEV_APT_VER): services.append('rhev-apt') if 'rhv-guest-tools' in os.getenv('VIRTIO_WIN'): services.append('spice-ga') for ser in services: check_windows_service(vmchecker.checker, ser) else: check_linux_ogac(vmchecker.checker) if 'mac_ip' in checkpoint: check_static_ip_conf(vmchecker.checker) ret = vmchecker.run() if len(ret) == 0: logging.info("All common checkpoints passed") # Check specific checkpoints if 'ogac' in checkpoint and 'signature' in checkpoint: if not utils_v2v.multiple_versions_compare( V2V_UNSUPPORT_RHEV_APT_VER): check_windows_signature(vmchecker.checker, r'c:\rhev-apt.exe') if 'cdrom' in checkpoint and "device='cdrom'" not in vmchecker.vmxml: test.fail('CDROM no longer exists') if 'vmtools' in checkpoint: check_vmtools(vmchecker.checker, checkpoint) if 'modprobe' in checkpoint: check_modprobe(vmchecker.checker) if 'device_map' in checkpoint: check_device_map(vmchecker.checker) if 'resume_swap' in checkpoint: check_resume_swap(vmchecker.checker) if 'rhev_file' in checkpoint: check_rhev_file_exist(vmchecker.checker) if 'file_architecture' in checkpoint: check_file_architecture(vmchecker.checker) if 'ubuntu_tools' in checkpoint: check_ubuntools(vmchecker.checker) if 'vmware_tools' in checkpoint: check_windows_vmware_tools(vmchecker.checker) if 'without_default_net' in checkpoint: if virsh.net_state_dict()[net_name]['active']: log_fail("Bridge virbr0 already started during conversion") if 'rhsrvany_checksum' in checkpoint: check_rhsrvany_checksums(vmchecker.checker) if 'block_dev' in checkpoint and not os.path.exists(blk_dev_link): test.fail("checkpoint '%s' failed" % checkpoint) # Merge 2 error lists error_list.extend(vmchecker.errors) # Virtio drivers will not be installed without virtio-win setup if 'virtio_win_unset' in checkpoint: missing_list = params.get('missing').split(',') expect_errors = ['Not find driver: ' + x for x in missing_list] logging.debug('Expect errors: %s' % expect_errors) logging.debug('Actual errors: %s' % error_list) if set(error_list) == set(expect_errors): error_list[:] = [] else: logging.error('Virtio drivers not meet expectation')
def run(test, params, env): """ Test command: virsh net-dumpxml. This command can output the network information as an XML dump to stdout. 1.Get all parameters from config file. 2.If test case's network status is inactive, destroy it. 3.Perform virsh net-dumpxml operation. 4.Recover test environment(network status). 5.Confirm the test result. """ status_error = params.get("status_error", "no") net_ref = params.get("net_dumpxml_net_ref") net_name = params.get("net_dumpxml_network", "default") net_status = params.get("net_dumpxml_network_status", "active") xml_flie = params.get("net_dumpxml_xml_file", "default.xml") extra = params.get("net_dumpxml_extra", "") network_xml = os.path.join(test.tmpdir, xml_flie) # Run test case if net_ref == "uuid": net_ref = virsh.net_uuid(net_name).stdout.strip() elif net_ref == "name": net_ref = net_name net_status_current = "active" if not virsh.net_state_dict()[net_name]['active']: net_status_current = "inactive" if not virsh.net_state_dict()[net_name]['persistent']: raise error.TestError("Network is transient!") try: if net_status == "inactive" and net_status_current == "active": status_destroy = virsh.net_destroy(net_name, ignore_status=True).exit_status if status_destroy != 0: raise error.TestError("Network destroied failed!") result = virsh.net_dumpxml(net_ref, extra, network_xml, ignore_status=True) status = result.exit_status err = result.stderr.strip() xml_validate_cmd = "virt-xml-validate %s network" % network_xml valid_s = utils.run(xml_validate_cmd, ignore_status=True).exit_status # Check option valid or not. if extra.find("--") != -1: options = extra.split("--") for option in options: if option.strip() == "": continue if not virsh.has_command_help_match("net-dumpxml", option.strip()): status_error = "yes" break finally: # Recover network if net_status == "inactive" and net_status_current == "active": status_start = virsh.net_start(net_name, ignore_status=True).exit_status if status_start != 0: raise error.TestError("Network started failed!") # Check status_error if status_error == "yes": if status == 0: raise error.TestFail("Run successfully with wrong command!") if err == "": raise error.TestFail("The wrong command has no error outputed!") elif status_error == "no": if status != 0: raise error.TestFail("Run failed with right command!") if valid_s != 0: raise error.TestFail("Command output is invalid!") else: raise error.TestError("The status_error must be 'yes' or 'no'!")
test_xml.xml = virtual_net if test_create: test_xml.create() else: test_xml.define() except xcepts.LibvirtXMLError, detail: raise error.TestNAError("Failed to define a test network.\n" "Detail: %s." % detail) # Run test case try: libvirtd = utils_libvirtd.Libvirtd() if test_create: # Restart libvirtd and check state libvirtd.restart() net_state = virsh.net_state_dict() if (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or net_state[net_name]['persistent']): raise error.TestFail("Found wrong network states" " after restarting libvirtd: %s" % net_state) edit_net_xml() if test_create: # Network become persistent after editing net_state = virsh.net_state_dict() if (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or not net_state[net_name]['persistent']): raise error.TestFail("Found wrong network states" " after editing: %s"
def run(test, params, env): """ Test command: virsh net-edit <network> 1) Define a temp virtual network 2) Execute virsh net-edit to modify it 3) Dump its xml then check it """ def edit_net_xml(edit_cmd, expect_error, **dargs): """ Edit net xml with virsh net-edit :params edit_cmd: The edit cmd to execute :params expect_error: Boolean, expect success or not :params **dargs: The virsh edit's option """ logging.debug("edit_cmd: %s", edit_cmd) readonly = dargs.get("readonly", False) session = aexpect.ShellSession("sudo -s") try: logging.info("Execute virsh net-edit %s", net_name) virsh_cmd = "virsh net-edit %s" % net_name if readonly: virsh_cmd = "virsh -r net-edit %s" % net_name logging.debug("virsh_cmd: %s", virsh_cmd) session.sendline(virsh_cmd) session.sendline(edit_cmd) session.send('\x1b') session.send('ZZ') remote.handle_prompts(session, None, None, r"[\#\$]\s*$") session.close() except (aexpect.ShellError, aexpect.ExpectError, remote.LoginTimeoutError) as details: log = session.get_output() session.close() if not expect_error: test.fail("Failed to do net-edit: %s\n%s" % (details, log)) logging.debug("Expected error: %s" % log) if readonly and "read only" not in log: test.fail("Not expected error") # Gather test parameters net_name = params.get("net_edit_net_name", "editnet") test_create = "yes" == params.get("test_create", "no") virsh_dargs = {'debug': True, 'ignore_status': True} virsh_instance = virsh.VirshPersistent(**virsh_dargs) change_attribute = params.get("attribute", None) old_value = params.get("old_value", None) new_value = params.get("new_value", None) edit_type = params.get("edit_type", "modify") status_error = (params.get("status_error", "no") == "yes") readonly = (params.get("net_edit_readonly", "no") == "yes") # Get all network instance nets = network_xml.NetworkXML.new_all_networks_dict(virsh_instance) # First check if a bridge of this name already exists # Increment suffix integer from 1 then append it to net_name # till there is no name conflict. if net_name in nets: net_name_fmt = net_name + "%d" suffix_num = 1 while ((net_name_fmt % suffix_num) in nets): suffix_num += 1 net_name = net_name_fmt % suffix_num virtual_net = """ <network> <name>%s</name> <forward mode='nat'/> <bridge name='%s' stp='on' delay='0' /> <mac address='52:54:00:03:78:6c'/> <ip address='192.168.100.1' netmask='255.255.255.0'> <dhcp> <range start='192.168.100.2' end='192.168.100.254' /> </dhcp> </ip> </network> """ % (net_name, net_name) try: test_xml = network_xml.NetworkXML(network_name=net_name) test_xml.xml = virtual_net if test_create: test_xml.create() else: test_xml.define() except xcepts.LibvirtXMLError as detail: test.cancel("Failed to define a test network.\n" "Detail: %s." % detail) # Run test case try: libvirtd = utils_libvirtd.Libvirtd() if change_attribute == "uuid": # if the attribute need to change is uuid, the old uuid should get # from current network, and new uuid can generate by uuidgen new_value = process.run("uuidgen", shell=True).stdout[:-1] old_value = virsh.net_uuid(net_name).stdout.strip() if test_create: # Restart libvirtd and check state libvirtd.restart() net_state = virsh.net_state_dict() if (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or net_state[net_name]['persistent']): test.fail("Found wrong network states" " after restarting libvirtd: %s" % net_state) else: libvirtd.restart() net_state = virsh.net_state_dict() if (net_state[net_name]['active'] or net_state[net_name]['autostart'] or not net_state[net_name]['persistent']): test.fail("Found wrong network states: %s" % net_state) result = virsh.net_start(net_name) logging.debug("start the persistent network return: %s", result) if edit_type == "modify": edit_cmd = r":%%s/%s=\'%s\'/%s=\'%s\'" % ( change_attribute, old_value, change_attribute, new_value) match_string = "%s=\'%s\'" % (change_attribute, new_value) if edit_type == "delete": match_string = "%s" % change_attribute # Pattern to be more accurate if old_value and change_attribute != 'uuid': match_string = "%s=\'%s\'" % (change_attribute, old_value) else: match_string = old_value edit_cmd = r":/%s/d" % match_string edit_net_xml(edit_cmd, status_error, readonly=readonly) net_state = virsh.net_state_dict() # transient Network become persistent after editing if not status_error and (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or not net_state[net_name]['persistent']): test.fail("Found wrong network states" " after editing: %s" % net_state) cmd_result = virsh.net_dumpxml(net_name, '--inactive', debug=True) if cmd_result.exit_status: test.fail("Failed to dump xml of virtual network %s" % net_name) # The inactive xml should contain the match string xml = cmd_result.stdout.strip() if edit_type == "modify": if not status_error and not re.search(match_string, xml): test.fail("The inactive xml should contain the change '%s'" % match_string) if status_error and re.search(match_string, xml): test.fail("Expect to modify failure but run success") if edit_type == "delete": if not status_error and re.search(match_string, xml): test.fail("The inactive xml should delete the change '%s'" % match_string) if status_error and not re.search(match_string, xml): test.fail("Expect to delete failure but run success") # The active xml should not contain the match string if net_state[net_name]['active']: if not status_error: cmd_result = virsh.net_dumpxml(net_name, debug=True) if cmd_result.exit_status: test.fail( "Failed to dump active xml of virtual network %s" % net_name) xml = cmd_result.stdout.strip() if edit_type == "modify" and re.search(match_string, xml): test.fail( "The active xml should not contain the change '%s'" % match_string) if edit_type == "delete" and not re.search(match_string, xml): test.fail( "The active xml should not delete the change '%s'" % match_string) finally: test_xml.orbital_nuclear_strike()
def vm_check(status_error): """ Checking the VM """ if status_error: return if output_mode == 'json' and not check_json_output(params): test.fail('check json output failed') if output_mode == 'local' and not check_local_output(params): test.fail('check local output failed') if output_mode in ['null', 'json', 'local']: return # vmchecker must be put before skip_vm_check in order to clean up # the VM. vmchecker = VMChecker(test, params, env) params['vmchecker'] = vmchecker if skip_vm_check == 'yes': logging.info('Skip checking vm after conversion: %s' % skip_reason) return if output_mode == 'rhev': if not utils_v2v.import_vm_to_ovirt( params, address_cache, timeout=v2v_timeout): test.fail('Import VM failed') elif output_mode == 'libvirt': virsh.start(vm_name, debug=True) # Check guest following the checkpoint document after convertion logging.info('Checking common checkpoints for v2v') if checkpoint == 'ogac': # windows guests will reboot at any time after qemu-ga is # installed. The process cannot be controled. In order to # don't break vmchecker.run() process, It's better to put # check_windows_ogac before vmchecker.run(). Because in # check_windows_ogac, it waits until rebooting completes. vmchecker.checker.create_session() if os_type == 'windows': check_windows_ogac(vmchecker.checker) else: check_linux_ogac(vmchecker.checker) ret = vmchecker.run() if len(ret) == 0: logging.info("All common checkpoints passed") # Check specific checkpoints if checkpoint == 'cdrom': virsh_session = utils_sasl.VirshSessionSASL(params) virsh_session_id = virsh_session.get_id() check_device_exist('cdrom', virsh_session_id) virsh_session.close() if checkpoint.startswith('vmtools'): check_vmtools(vmchecker.checker, checkpoint) if checkpoint == 'modprobe': check_modprobe(vmchecker.checker) if checkpoint == 'device_map': check_device_map(vmchecker.checker) if checkpoint == 'resume_swap': check_resume_swap(vmchecker.checker) if checkpoint == 'rhev_file': check_rhev_file_exist(vmchecker.checker) if checkpoint == 'file_architecture': check_file_architecture(vmchecker.checker) if checkpoint == 'ubuntu_tools': check_ubuntools(vmchecker.checker) if checkpoint == 'without_default_net': if virsh.net_state_dict()[net_name]['active']: log_fail("Bridge virbr0 already started during conversion") # Merge 2 error lists error_list.extend(vmchecker.errors)
def run(test, params, env): """ Test command: virsh net-edit <network> 1) Define a temp virtual network 2) Execute virsh net-edit to modify it 3) Dump its xml then check it """ def edit_net_xml(edit_cmd, expect_error, **dargs): """ Edit net xml with virsh net-edit :params edit_cmd: The edit cmd to execute :params expect_error: Boolen, expect success or not :params **dargs: The virsh edit's option """ logging.debug("edit_cmd: %s", edit_cmd) readonly = dargs.get("readonly", False) session = aexpect.ShellSession("sudo -s") try: logging.info("Execute virsh net-edit %s", net_name) virsh_cmd = "virsh net-edit %s" % net_name if readonly: virsh_cmd = "virsh -r net-edit %s" % net_name logging.debug("virsh_cmd: %s", virsh_cmd) session.sendline(virsh_cmd) session.sendline(edit_cmd) session.send('\x1b') session.send('ZZ') remote.handle_prompts(session, None, None, r"[\#\$]\s*$") session.close() except (aexpect.ShellError, aexpect.ExpectError, remote.LoginTimeoutError) as details: log = session.get_output() session.close() if not expect_error: test.fail("Failed to do net-edit: %s\n%s" % (details, log)) logging.debug("Expected error: %s" % log) if readonly and "read only" not in log: test.fail("Not expected error") # Gather test parameters net_name = params.get("net_edit_net_name", "editnet") test_create = "yes" == params.get("test_create", "no") virsh_dargs = {'debug': True, 'ignore_status': True} virsh_instance = virsh.VirshPersistent(**virsh_dargs) change_attribute = params.get("attribute", None) old_value = params.get("old_value", None) new_value = params.get("new_value", None) edit_type = params.get("edit_type", "modify") status_error = (params.get("status_error", "no") == "yes") readonly = (params.get("net_edit_readonly", "no") == "yes") # Get all network instance nets = network_xml.NetworkXML.new_all_networks_dict(virsh_instance) # First check if a bridge of this name already exists # Increment suffix integer from 1 then append it to net_name # till there is no name conflict. if net_name in nets: net_name_fmt = net_name + "%d" suffix_num = 1 while ((net_name_fmt % suffix_num) in nets): suffix_num += 1 net_name = net_name_fmt % suffix_num virtual_net = """ <network> <name>%s</name> <forward mode='nat'/> <bridge name='%s' stp='on' delay='0' /> <mac address='52:54:00:03:78:6c'/> <ip address='192.168.100.1' netmask='255.255.255.0'> <dhcp> <range start='192.168.100.2' end='192.168.100.254' /> </dhcp> </ip> </network> """ % (net_name, net_name) try: test_xml = network_xml.NetworkXML(network_name=net_name) test_xml.xml = virtual_net if test_create: test_xml.create() else: test_xml.define() except xcepts.LibvirtXMLError as detail: test.cancel("Failed to define a test network.\n" "Detail: %s." % detail) # Run test case try: libvirtd = utils_libvirtd.Libvirtd() if change_attribute == "uuid": # if the attribute need to change is uuid, the old uuid should get # from current network, and new uuid can generate by uuidgen new_value = process.run("uuidgen", shell=True).stdout[:-1] old_value = virsh.net_uuid(net_name).stdout.strip() if test_create: # Restart libvirtd and check state libvirtd.restart() net_state = virsh.net_state_dict() if (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or net_state[net_name]['persistent']): test.fail("Found wrong network states" " after restarting libvirtd: %s" % net_state) else: libvirtd.restart() net_state = virsh.net_state_dict() if (net_state[net_name]['active'] or net_state[net_name]['autostart'] or not net_state[net_name]['persistent']): test.fail("Found wrong network states: %s" % net_state) result = virsh.net_start(net_name) logging.debug("start the persistent network return: %s", result) if edit_type == "modify": edit_cmd = r":%%s/%s=\'%s\'/%s=\'%s\'" % (change_attribute, old_value, change_attribute, new_value) match_string = "%s=\'%s\'" % (change_attribute, new_value) if edit_type == "delete": match_string = "%s" % change_attribute # Pattern to be more accurate if old_value and change_attribute != 'uuid': match_string = "%s=\'%s\'" % (change_attribute, old_value) else: match_string = old_value edit_cmd = r":/%s/d" % match_string edit_net_xml(edit_cmd, status_error, readonly=readonly) net_state = virsh.net_state_dict() # transient Network become persistent after editing if not status_error and (not net_state[net_name]['active'] or net_state[net_name]['autostart'] or not net_state[net_name]['persistent']): test.fail("Found wrong network states" " after editing: %s" % net_state) cmd_result = virsh.net_dumpxml(net_name, '--inactive', debug=True) if cmd_result.exit_status: test.fail("Failed to dump xml of virtual network %s" % net_name) # The inactive xml should contain the match string xml = cmd_result.stdout.strip() if edit_type == "modify": if not status_error and not re.search(match_string, xml): test.fail("The inactive xml should contain the change '%s'" % match_string) if status_error and re.search(match_string, xml): test.fail("Expect to modify failure but run success") if edit_type == "delete": if not status_error and re.search(match_string, xml): test.fail("The inactive xml should delete the change '%s'" % match_string) if status_error and not re.search(match_string, xml): test.fail("Expect to delete failure but run success") # The active xml should not contain the match string if net_state[net_name]['active']: if not status_error: cmd_result = virsh.net_dumpxml(net_name, debug=True) if cmd_result.exit_status: test.fail("Failed to dump active xml of virtual network %s" % net_name) xml = cmd_result.stdout.strip() if edit_type == "modify" and re.search(match_string, xml): test.fail("The active xml should not contain the change '%s'" % match_string) if edit_type == "delete" and not re.search(match_string, xml): test.fail("The active xml should not delete the change '%s'" % match_string) finally: test_xml.orbital_nuclear_strike()