Exemplo n.º 1
0
    def flood_ping():
        """
        Do flood ping from host to guest

        """
        flood_minutes = int(params["flood_minutes"])
        test.log.info("Flood ping for %s minutes", flood_minutes)
        utils_net.ping(guest_ip, flood=True, timeout=flood_minutes * 60)
Exemplo n.º 2
0
 def ping_test():
     """
     ping test to increase the number of interrupts
     """
     error_context.context("Execute ping test", logging.info)
     utils_net.ping(guest_ip, 10, session=session)
     irq_info_after_ping = get_irq_info()
     analyze_interrupts(irq_info_before_test, irq_info_after_ping)
Exemplo n.º 3
0
    def flood_ping(session, host_ip, os_type="linux"):
        """
        Do flood ping from guest to host

        :param session: session to send flood ping
        :param host_ip: the IP of the host
        """
        flood_minutes = int(params["flood_minutes"])
        logging.info("Flood ping for %s minutes" % flood_minutes)
        # TODO: windows guest doesn't have proper flood ping like linux,
        # will consider how to implement it for windows later
        if os_type == "linux":
            utils_net.ping(host_ip, flood=True,
                           session=session, timeout=flood_minutes * 60)
Exemplo n.º 4
0
 def _ping_check(ip, session):
     status, output = utils_net.ping(ip,
                                     count=5,
                                     timeout=10,
                                     session=session,
                                     force_ipv4=True)
     return True if status == 0 else False
Exemplo n.º 5
0
    def check_vhostuser_guests(session1, session2):
        """
        Check the vhostuser interface in guests

        param session1: Session of original guest
        param session2: Session of original additional guest
        """
        logging.debug("iface details is %s" %
                      libvirt.get_interface_details(vm_name))
        vm1_mac = str(libvirt.get_interface_details(vm_name)[0]['mac'])
        vm2_mac = str(libvirt.get_interface_details(add_vm_name)[0]['mac'])

        utils_net.set_guest_ip_addr(session1, vm1_mac, guest1_ip)
        utils_net.set_guest_ip_addr(session2, vm2_mac, guest2_ip)
        ping_status, ping_output = utils_net.ping(dest=guest2_ip,
                                                  count='3',
                                                  timeout=5,
                                                  session=session1)
        logging.info("output:%s" % ping_output)
        if ping_status != 0:
            if ping_expect_fail:
                logging.info("Can not ping guest2 as expected")
            else:
                test.fail("Can not ping guest2 from guest1")
        else:
            if ping_expect_fail:
                test.fail("Ping guest2 successfully not expected")
            else:
                logging.info("Can ping guest2 from guest1")
Exemplo n.º 6
0
def _ping_with_params(test,
                      params,
                      dest,
                      interface=None,
                      packet_size=None,
                      interval=None,
                      count=0,
                      session=None,
                      flood=False):
    if flood:
        cmd = "ping " + dest + " -f -q"
        if interface:
            cmd += " -S %s" % interface
        flood_minutes = float(params.get("flood_minutes", 10))
        status, output = utils_net.raw_ping(cmd, flood_minutes * 60, session,
                                            logging.debug)
    else:
        timeout = float(count) * 1.5
        status, output = utils_net.ping(dest,
                                        count,
                                        interval,
                                        interface,
                                        packet_size,
                                        session=session,
                                        timeout=timeout)
    if status != 0:
        test.fail("Ping failed, status: %s," " output: %s" % (status, output))
    if params.get("strict_check", "no") == "yes":
        ratio = utils_test.get_loss_ratio(output)
        if ratio != 0:
            test.fail("Loss ratio is %s" % ratio)
Exemplo n.º 7
0
def run(test, params, env):
    """
    When "acpi-index=N" is enabled, NIC name should always be "ethN"

    1) Boot up guest with a single nic, add nic option "acpi-index=1"
    2) Remove "biosdevname=0" and "net.ifname=0" from kenrel command line
    3) Reboot guest
    4) Check the nic name, the guest nic name enoN == acpi-index=N

    :param test:   QEMU test object.
    :param params: Dictionary with the test parameters.
    :param env:    Dictionary with test environment.
    """
    login_timeout = int(params.get("login_timeout", 360))
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    session = vm.wait_for_serial_login(timeout=login_timeout)
    ifname = utils_net.get_linux_ifname(session,
                                        vm.get_mac_address())
    pattern = int(re.findall(r'\d+', ifname)[-1])
    nic_name_number = params.get_numeric("nic_name_number")
    if pattern == nic_name_number:
        logging.info("nic name match")
    else:
        test.fail("nic name doesn't match")
    host_ip = utils_net.get_host_ip_address(params)
    status, output = utils_net.ping(host_ip, 10, timeout=30)
    if status:
        test.fail("%s ping %s unexpected, output %s" % (vm.name, host_ip, output))
    if session:
        session.close()
Exemplo n.º 8
0
    def test_ping():
        """
        Ping test for nic option.
        """
        package_sizes = params.objects("ping_sizes")
        if params["os_type"] == "windows":
            ifname = utils_net.get_windows_nic_attribute(
                session=session,
                key="netenabled",
                value=True,
                target="netconnectionID")
        else:
            ifname = utils_net.get_linux_ifname(session,
                                                vm.get_mac_address())
        dest = utils_net.get_host_ip_address(params)

        for size in package_sizes:
            error_context.context("Test ping from '%s' to host '%s' on guest '%s'"
                                  " with package size %s. " %
                                  (ifname, dest, vm.name, size), logging.info)
            status, output = utils_net.ping(dest=dest, count=10, packetsize=size, session=session, timeout=30)
            if status:
                test.fail("%s ping %s unexpected, output %s" % (vm.name, dest,
                                                                output))
            if params["os_type"] == "windows":
                # windows guest get loss=0 when ping failed sometime,
                # need further check
                loss = utils_test.get_loss_ratio(output)
                if loss or "TTL" in output:
                    pass
                else:
                    test.fail("Guest ping test hit unexpected loss, "
                              "error_info: %s" % output)
Exemplo n.º 9
0
def run(test, params, env):
    """
    Boot a winodws guest add Vendor ID with name "KVMKVMKVM" to cpu model flag

    1) Boot a vm with 'e1000e + hv_vendor_id=KVMKVMKVM' on q35 machine
    2) Run the bcdedit command as administrator
    3) reboot guest by shell
    4) do ping test

    :param test: QEMU test object.
    :param params: Dictionary with the test parameters.
    :param env: Dictionary with test environment.
    """
    login_timeout = params.get_numeric("login_timeout", 360)
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    session_serial = vm.wait_for_serial_login(timeout=login_timeout)
    bcdedit_debug = params["bcdedit_debug"]
    bcdedit_cmd = params["bcdedit_cmd"]
    ext_host = params.get("ext_host")

    try:
        session_serial.cmd(bcdedit_debug)
        session_serial.cmd(bcdedit_cmd)
        vm.reboot(timeout=login_timeout)
        status, output = utils_net.ping(dest=ext_host,
                                        count=10,
                                        session=session_serial,
                                        timeout=30)
        if status:
            test.fail("ping is failed, output %s" % output)
    finally:
        session_serial.close()
 def test_flood_ping():
     # Test Flood Ping
     s_ping, o_ping = utils_net.ping(dest=server_ip, count=5,
                                     interface=net_ip, flood=True)
     logging.info(s_ping)
     logging.info(o_ping)
     if s_ping:
         test.fail("Flood ping test failed")
Exemplo n.º 11
0
 def test_flood_ping():
     # Test Flood Ping
     s_ping, o_ping = utils_net.ping(dest=server_ip, count=5,
                                     interface=net_ip, flood=True)
     logging.info(s_ping)
     logging.info(o_ping)
     if s_ping:
         test.fail("Flood ping test failed")
Exemplo n.º 12
0
 def ping_test():
     #Ping from guest1 to guest2 for 30 counts
     status, output = utils_net.ping(dest=addresses[1],
                                     count=30,
                                     timeout=60,
                                     session=sessions[0])
     if status:
         test.fail("ping %s unexpected, output %s" % (vms[1], output))
Exemplo n.º 13
0
    def flood_ping(session, host_ip, os_type="linux"):
        """
        Do flood ping from guest to host

        :param session: session to send flood ping
        :param host_ip: the IP of the host
        """
        flood_minutes = int(params["flood_minutes"])
        logging.info("Flood ping for %s minutes", flood_minutes)
        try:
            utils_net.ping(host_ip, flood=True,
                           session=session, timeout=flood_minutes * 60)
        except aexpect.ExpectProcessTerminatedError:
            if os_type == "windows":
                session.close()
                session = vm.wait_for_login(timeout=timeout)
                pass
        return session
Exemplo n.º 14
0
 def ping_test(dest_ip, ping_time, ping_lost_ratio):
     """
     ping guest from host,until change queues finished.
     """
     _, output = utils_net.ping(dest=dest_ip, timeout=ping_time)
     packets_lost = utils_test.get_loss_ratio(output)
     if packets_lost > ping_lost_ratio:
         err = " %s%% packages lost during ping. " % packets_lost
         err += "Ping command log:\n %s" % "\n".join(
             output.splitlines()[-3:])
         test.fail(err)
Exemplo n.º 15
0
    def check_ping(dest_ip, ping_count, timeout, src_ip=None, session=None,
                   expect_success=True):
        """
        Check if ping result meets expectation
        """
        status, output = utils_net.ping(dest=dest_ip, count=ping_count,
                                        interface=src_ip, timeout=timeout,
                                        session=session, force_ipv4=True)
        success = True if status == 0 else False

        if success != expect_success:
            test.fail('Ping result not met expectation, '
                      'actual result is {}'.format(success))
Exemplo n.º 16
0
    def ping_vm(self, vm, params, uri=None, ping_count=10, ping_timeout=60):
        """
        Method used to ping the VM before and after migration

        :param vm: VM object
        :param params: Test dict params
        :param uri: connect uri
        :param ping_count: count of icmp packet
        :param ping_timeout: Timeout for the ping command
        """
        vm_ip = params.get("vm_ip_dict", {})
        server_session = None
        func = exceptions.TestError
        if uri and uri != "qemu:///system":
            func = exceptions.TestFail
            src_uri = "qemu:///system"
            vm.connect_uri = uri
            server_session = test_setup.remote_session(params)
            # after migration VM would take some time to respond and to
            # avoid the race of framework querying IP address before VM
            # starts responding, provide timeout for 240 seconds to retry
            # and raise if VM fails to respond
            vm_ip[vm.name] = vm.get_address(session=server_session,
                                            timeout=240)
            logging.info("Check VM network connectivity after migrating")
        else:
            logging.info("Check VM network connectivity before migration")
            if not vm.is_alive():
                vm.start()
            vm.wait_for_login()
            vm_ip[vm.name] = vm.get_address()
            params["vm_ip_dict"] = vm_ip
        s_ping, o_ping = utils_net.ping(vm_ip[vm.name],
                                        count=ping_count,
                                        timeout=ping_timeout,
                                        output_func=logging.debug,
                                        session=server_session)
        logging.info(o_ping)
        if uri:
            vm.connect_uri = src_uri
            if server_session:
                server_session.close()
        if s_ping != 0:
            if uri:
                if "offline" in params.get("migrate_options"):
                    logging.info(
                        "Offline Migration: %s will not responded to "
                        "ping as expected", vm.name)
                    return
            func("%s did not respond after %d sec." % (vm.name, ping_timeout))
Exemplo n.º 17
0
def run(test, params, env):
    """
    boot guest with the same mac address test.

    1) Boot guest with the same mac address
    2) Check if the driver is installed and verified
    3) Check ip of guest
    4) Ping out

    :param test: kvm test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """
    timeout = int(params.get_numeric("timeout", 360))
    error_context.context("Boot guest with 2 virtio-net with the same mac",
                          logging.info)
    vm = env.get_vm(params["main_vm"])
    session = vm.wait_for_login(timeout=timeout)
    error_context.context("Check if the driver is installed and "
                          "verified", logging.info)
    driver_name = params.get("driver_name", "netkvm")
    session = utils_test.qemu.windrv_check_running_verifier(
        session, vm, test, driver_name, timeout)
    # wait for getting the 169.254.xx.xx, it gets slower than valid ip.
    time.sleep(60)
    error_context.context("Check the ip of guest", logging.info)
    mac = vm.virtnet[0].mac
    cmd = 'wmic nicconfig where macaddress="%s" get ipaddress' % mac
    status, output = session.cmd_status_output(cmd, timeout)
    if status:
        test.error("Check ip error, output=%s" % output)
    lines = [l.strip() for l in output.splitlines() if l.strip()]
    logging.info(lines)

    valid_count = 0
    for l in lines[1:]:
        ip = re.findall(r'(\d+.\d+.\d+.\d+)"', l)[0]
        if not ip.startswith("169.254"):
            valid_count += 1
    if valid_count != 1:
        test.error("%d valid ip found, should be 1" % valid_count)

    error_context.context("Ping out from guest", logging.info)
    host_ip = utils_net.get_host_ip_address(params)
    status, output = utils_net.ping(host_ip,
                                    count=10,
                                    timeout=60,
                                    session=session)
    if status:
        test.fail("Ping %s failed, output=%s" % (host_ip, output))
Exemplo n.º 18
0
    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)
        if status:
            test.fail("Fail to ping %s from %s" % (dest_ip, src_ip))
Exemplo n.º 19
0
    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)
        if status:
            test.fail("Fail to ping %s from %s" % (dest_ip, src_ip))
Exemplo n.º 20
0
    def check_vm_network_accessed(ping_dest, session=None):
        """
        The operations to the VM need to be done before or after
        migration happens

        :param ping_dest: The destination to be ping
        :param session: The session object to the host
        :raise: test.fail when ping fails
        """
        # Confirm local/remote VM can be accessed through network.
        logging.info("Check VM network connectivity")
        status, output = utils_net.ping(ping_dest,
                                        count=10,
                                        timeout=20,
                                        output_func=logging.debug,
                                        session=session)
        if status != 0:
            test.fail("Ping failed, status: %s, output: %s" % (status, output))
Exemplo n.º 21
0
    def test_ping():
        """
        Ping test for nic option.
        """
        package_sizes = params.objects("ping_sizes")
        guest_ip = vm.get_address()

        for size in package_sizes:
            error_context.context(
                "From host ping to '%s' with guest '%s'"
                " with package size %s. " % (vm.name, guest_ip, size),
                logging.info)
            status, output = utils_net.ping(guest_ip,
                                            count=10,
                                            packetsize=size,
                                            timeout=30)
            if status != 0:
                test.fail("host ping %s unexpected, output %s" %
                          (guest_ip, output))
 def test_ping():
     try:
         output = session.cmd_output("lspci -nn | grep %s" % device_name)
         nic_id = str(output).split(' ', 1)[0]
         nic_name = str(utils_misc.get_interface_from_pci_id(nic_id,
                                                             session))
         session.cmd("ip addr flush dev %s" % nic_name)
         session.cmd("ip addr add %s/%s dev %s"
                     % (net_ip, netmask, nic_name))
         session.cmd("ip link set %s up" % nic_name)
         s_ping, o_ping = utils_net.ping(dest=server_ip, count=5,
                                         interface=net_ip)
         logging.info(s_ping)
         logging.info(o_ping)
         if s_ping:
             test.fail("Ping test failed")
     except aexpect.ShellError, detail:
         test.error("Succeed to set ip on guest, but failed "
                    "to bring up interface.\n"
                    "Detail: %s." % detail)
Exemplo n.º 23
0
 def test_ping():
     try:
         output = session.cmd_output("lspci -nn | grep %s" % device_name)
         nic_id = str(output).split(' ', 1)[0]
         nic_name = str(utils_misc.get_interface_from_pci_id(nic_id,
                                                             session))
         session.cmd("ip addr flush dev %s" % nic_name)
         session.cmd("ip addr add %s/%s dev %s"
                     % (net_ip, netmask, nic_name))
         session.cmd("ip link set %s up" % nic_name)
         s_ping, o_ping = utils_net.ping(dest=server_ip, count=5,
                                         interface=net_ip)
         logging.info(s_ping)
         logging.info(o_ping)
         if s_ping:
             test.fail("Ping test failed")
     except aexpect.ShellError, detail:
         test.error("Succeed to set ip on guest, but failed "
                    "to bring up interface.\n"
                    "Detail: %s." % detail)
Exemplo n.º 24
0
def _ping_with_params(test, params, dest, interface=None,
                      packet_size=None, interval=None,
                      count=0, session=None, flood=False):
    if flood:
        cmd = "ping " + dest + " -f -q"
        if interface:
            cmd += " -S %s" % interface
        flood_minutes = float(params.get("flood_minutes", 10))
        status, output = utils_net.raw_ping(cmd, flood_minutes * 60,
                                            session, logging.debug)
    else:
        timeout = float(count) * 1.5
        status, output = utils_net.ping(dest, count, interval, interface,
                                        packet_size, session=session,
                                        timeout=timeout)
    if status != 0:
        test.fail("Ping failed, status: %s,"
                  " output: %s" % (status, output))
    if params.get("strict_check", "no") == "yes":
        ratio = utils_test.get_loss_ratio(output)
        if ratio != 0:
            test.fail("Loss ratio is %s" % ratio)
Exemplo n.º 25
0
 def is_ip_reachable(ipaddr):
     res, _ = ping(ipaddr, timeout=5)
     return res == 0
Exemplo n.º 26
0
def run(test, params, env):
    """
    MULTI_QUEUE enabled by default check test

    1) Boot up a VM, and login to the guest
    2) Check the queues according to the value set in qemu cmd line for
       smp and queues
    3) do ping test

    :param test: QEMU test object.
    :param params: Dictionary with the test parameters.
    :param env: Dictionary with test environment.
    """

    def get_queues_status(session, ifname, timeout=240):
        """
        Get queues status

        :param session: guest session
        :param ifname: interface name
        :param timeout: timeout of session.cmd_output

        :return: queues status list
        """
        mq_get_cmd = "ethtool -l %s" % ifname
        nic_mq_info = session.cmd_output(mq_get_cmd, timeout=timeout,
                                         safe=True)
        queues_reg = re.compile(r"Combined:\s+(\d)", re.I)
        queues_info = queues_reg.findall(" ".join(nic_mq_info.splitlines()))
        if len(queues_info) != 2:
            err_msg = "Oops, get guest queues info failed, "
            err_msg += "make sure your guest support MQ.\n"
            err_msg += "Check cmd is: '%s', " % mq_get_cmd
            err_msg += "Command output is: '%s'." % nic_mq_info
            test.cancel(err_msg)
        return [int(x) for x in queues_info]

    def chk_mq_enabled(vm, queues):
        """
        Check whether MQ value set in qemu cmd line fits the value in guest

        :param vm: guest vm
        :param queues: queues value in qemu cmd line
        """
        login_timeout = int(params.get("login_timeout", 360))
        session = vm.wait_for_login(timeout=login_timeout)

        mac = vm.get_mac_address(0)
        ifname = utils_net.get_linux_ifname(session, mac)
        queues_status_list = get_queues_status(session, ifname)

        session.close()
        if not queues_status_list[0] == queues or \
                not queues_status_list[1] == min(queues, int(vm.cpuinfo.smp)):
            txt = "Pre-set maximums Combined should equals to queues in qemu"
            txt += " cmd line.\n"
            txt += "Current hardware settings Combined should be the min of "
            txt += "queues and smp.\n"
            txt += "Pre-set maximum Combined is: %s, " % queues_status_list[0]
            txt += " queues in qemu cmd line is: %s.\n" % queues
            txt += "Current hardware settings Combined "
            txt += "is: %s, " % queues_status_list[1]
            txt += " smp in qemu cmd line is: %s." % int(vm.cpuinfo.smp)
            test.fail(txt)

    error_context.context("Init the guest and try to login", logging.info)
    queues_list = params["queues_list"].split()

    for queues in queues_list:
        params["queues"] = int(queues)
        params["start_vm"] = "yes"

        env_process.preprocess_vm(test, params, env, params["main_vm"])
        vm = env.get_vm(params["main_vm"])
        vm.verify_alive()

        chk_mq_enabled(vm, int(queues))
        guest_ip = vm.get_address()
        status, output = utils_net.ping(guest_ip, 10, session=None,
                                        timeout=20)
        if utils_test.get_loss_ratio(output) > 0:
            test.fail("Packet lost while doing ping test")

        vm.destroy(gracefully=True)
Exemplo n.º 27
0
def run(test, params, env):
    """
    Do network stress test when under memory stress
    1) Boot a guest with vhost=on
    2) swapoff in guest
    3) flood ping from guest to host
    4) do stress test

    :param test: QEMU test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """

    def flood_ping(session, host_ip, os_type="linux"):
        """
        Do flood ping from guest to host

        :param session: session to send flood ping
        :param host_ip: the IP of the host
        """
        flood_minutes = int(params["flood_minutes"])
        logging.info("Flood ping for %s minutes" % flood_minutes)
        # TODO: windows guest doesn't have proper flood ping like linux,
        # will consider how to implement it for windows later
        if os_type == "linux":
            utils_net.ping(host_ip, flood=True,
                           session=session, timeout=flood_minutes * 60)

    def load_stress():
        """
        Load background IO/CPU/Memory stress in guest

        """
        error_context.context("launch stress app in guest", logging.info)
        args = (test, params, env, params["stress_test"])
        bg_test = utils_test.BackgroundTest(
            utils_test.run_virt_sub_test, args)
        bg_test.start()
        if not utils_misc.wait_for(bg_test.is_alive, first=10,
                                   step=3, timeout=100):
            test.fail("background test start failed")

    def unload_stress(session):
        """
        Stop stress app

        :param session: guest session
        """
        error_context.context("stop stress app in guest", logging.info)
        cmd = params.get("stop_cmd")
        session.sendline(cmd)

    timeout = float(params.get("login_timeout", 240))
    vm = env.get_vm(params["main_vm"])
    host_ip = utils_net.get_host_ip_address(params)
    session = vm.wait_for_login(timeout=timeout)

    os_type = params["os_type"]
    if os_type == "linux":
        session.cmd("swapoff -a", timeout=300)

    error_context.context("Run memory heavy stress in guest", logging.info)
    if os_type == "linux":
        test_mem = params.get("memory", 256)
        stress_args = "--cpu 4 --io 4 --vm 2 --vm-bytes %sM" % int(test_mem)
        stress_test = utils_test.VMStress(vm, "stress", params, stress_args=stress_args)
        stress_test.load_stress_tool()
    else:
        load_stress()
    flood_ping(session, host_ip, os_type)
    if os_type == "linux":
        stress_test.unload_stress()
        stress_test.clean()
    else:
        unload_stress(session)

    error_context.context("Ping test after flood ping,"
                          " Check if the network is still alive",
                          logging.info)
    count = params["count"]
    timeout = float(count) * 1.5
    status, output = utils_net.ping(host_ip, count, session=session,
                                    timeout=timeout)
    if status != 0:
        test.fail("Ping failed, status: %s,"
                  " output: %s" % (status, output))

    session.close()
Exemplo n.º 28
0
def run(test, params, env):
    """
    Test start domain with nwfilter rules.

    1) Prepare parameters.
    2) Prepare nwfilter rule and update domain interface to apply.
    3) Start domain and check rule.
    4) Clean env
    """
    # Prepare parameters
    filter_name = params.get("filter_name", "testcase")
    exist_filter = params.get("exist_filter", "no-mac-spoofing")
    status_error = "yes" == params.get("status_error", "no")
    mount_noexec_tmp = "yes" == params.get("mount_noexec_tmp", "no")
    kill_libvirtd = "yes" == params.get("kill_libvirtd", "no")
    bug_url = params.get("bug_url", "")
    ipset_command = params.get("ipset_command")
    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    username = params.get("username")
    password = params.get("password")
    need_vm2 = "yes" == params.get("need_vm2", "no")
    add_vm_name = params.get("add_vm_name", "vm2")
    vms = [vm]
    dst_outside = params.get("dst_outside", "www.google.com")
    ping_timeout = int(params.get("ping_timeout", "10"))

    # Prepare vm filterref parameters dict list
    filter_param_list = []
    params_key = []
    for i in params.keys():
        if 'parameter_name_' in i:
            params_key.append(i)
    params_key.sort()
    for i in range(len(params_key)):
        params_dict = {}
        params_dict['name'] = params[params_key[i]]
        params_dict['value'] = params['parameter_value_%s' % i]
        if params_dict['value'] == "MAC_of_virbr0":
            virbr0_info = process.run("ip a | grep virbr0: -A1",
                                      shell=True).stdout_text.strip()
            virbr0_mac = re.search(
                r'link/ether\s+(\w{2}:\w{2}:\w{2}:\w{2}:\w{2}:\w{2})',
                virbr0_info, re.M | re.I).group(1)
            params_dict['value'] = virbr0_mac
            logging.debug("params_dict['value'] is %s " % params_dict['value'])
        filter_param_list.append(params_dict)
    filterref_dict = {}
    filterref_dict['name'] = filter_name
    filterref_dict['parameters'] = filter_param_list
    params['filter_uuid'] = process.run("uuidgen",
                                        ignore_status=True,
                                        shell=True).stdout_text.strip()

    # get all the check commands and corresponding expected results form config file and make a dictionary
    cmd_list_ = params.get('check_cmd', '')
    if cmd_list_:
        cmd_list = cmd_list_.split(',')
        expect_res = params.get('expect_match', '').split(',')
        logging.debug("cmd_list is %s" % cmd_list)
        logging.debug("expect_res is %s" % expect_res)
        cmd_result_dict = dict(zip(cmd_list, expect_res))
        logging.debug("the check dict is %s" % cmd_result_dict)
    # backup vm xml
    vmxml_backup = libvirt_xml.VMXML.new_from_inactive_dumpxml(vm_name)

    libvirtd = utils_libvirtd.Libvirtd("virtqemud")
    device_name = None

    def check_nwfilter_rules(check_cmd, expect_match):
        """"check the nwfilter corresponding rule is added by iptables commands"""
        ret = utils_misc.wait_for(lambda: not process.system(
            check_cmd, ignore_status=True, shell=True),
                                  timeout=30)
        if not ret:
            test.fail("Rum command '%s' failed" % check_cmd)
        # This change anchors nwfilter_vm_start.possitive_test.new_filter.variable_notation case
        # The matched destination could be ip address or hostname
        if "iptables -L" in check_cmd and expect_match and 'ACCEPT' in expect_match:
            # ip address that need to be replaced
            replace_param = params.get("parameter_value_2")
            # Get hostname by ip address.
            hostname_info = None
            try:
                hostname_info = socket.gethostbyaddr(replace_param)
            except socket.error as e:
                logging.info(
                    "Failed to get hostname from ip address with error: %s",
                    str(e))
            if hostname_info:
                # String is used to replace ip address
                replace_with = "%s|%s" % (replace_param, hostname_info[0])
                expect_match = r"%s" % expect_match.replace(
                    replace_param, replace_with)
                logging.debug("final iptables match string:%s", expect_match)
        out = astring.to_text(
            process.system_output(check_cmd, ignore_status=False, shell=True))
        if expect_match and not re.search(expect_match, out):
            test.fail("'%s' not found in output: %s" % (expect_match, out))

    def clean_up_dirty_nwfilter_binding():
        cmd_result = virsh.nwfilter_binding_list(debug=True)
        binding_list = cmd_result.stdout_text.strip().splitlines()
        binding_list = binding_list[2:]
        result = []
        # If binding list is not empty.
        if binding_list:
            for line in binding_list:
                # Split on whitespace, assume 1 column
                linesplit = line.split(None, 1)
                result.append(linesplit[0])
        logging.info("nwfilter binding list is: %s", result)
        for binding_uuid in result:
            try:
                virsh.nwfilter_binding_delete(binding_uuid)
            except Exception as e:
                logging.error(
                    "Exception thrown while undefining nwfilter-binding: %s",
                    str(e))
                raise

    try:
        # Clean up dirty nwfilter binding if there are.
        clean_up_dirty_nwfilter_binding()
        rule = params.get("rule")
        if rule:
            # Add pre-check whether nwfilter exists or not since
            # utlv.create_nwfilter_xml will fail if there is no any nwfilter exists
            nwfilter_list = libvirt_nwfilter.get_nwfilter_list()
            if not nwfilter_list:
                test.error("There is no any nwfilter existed on the host")
            # Create new filter xml
            filterxml = utlv.create_nwfilter_xml(params)
            # Define filter xml
            virsh.nwfilter_define(filterxml.xml, debug=True)

        # Update first vm interface with filter
        vmxml = libvirt_xml.VMXML.new_from_inactive_dumpxml(vm_name)
        iface_xml = vmxml.get_devices('interface')[0]
        vmxml.del_device(iface_xml)
        new_iface = interface.Interface('network')
        new_iface.xml = iface_xml.xml
        new_filterref = new_iface.new_filterref(**filterref_dict)
        new_iface.filterref = new_filterref
        logging.debug("new interface xml is: %s" % new_iface)
        vmxml.add_device(new_iface)
        vmxml.sync()

        if mount_noexec_tmp:
            device_name = utlv.setup_or_cleanup_iscsi(is_setup=True)
            utlv.mkfs(device_name, 'ext4')
            cmd = "mount %s /tmp -o noexec,nosuid" % device_name
            process.run(cmd, shell=True)

        if ipset_command:
            pkg = "ipset"
            if not utils_package.package_install(pkg):
                test.cancel("Can't install ipset on host")
            process.run(ipset_command, shell=True)

        # Run command
        try:
            vm.start()
            if not mount_noexec_tmp:
                vm.wait_for_serial_login(username=username, password=password)
            vmxml = libvirt_xml.VMXML.new_from_dumpxml(vm_name)
            iface_xml = vmxml.get_devices('interface')[0]
            iface_target = iface_xml.target['dev']
            iface_mac = iface_xml.mac_address
            logging.debug("iface target dev name is %s", iface_target)

            # Check iptables or ebtables on host
            if need_vm2:
                # Clone more vm for testing
                result = virsh.dom_list('--inactive').stdout_text
                if add_vm_name in result:
                    logging.debug("%s is already exists!" % add_vm_name)
                    vms.append(env.get_vm(add_vm_name))
                else:
                    vm.destroy()
                    ret_clone = utils_libguestfs.virt_clone_cmd(vm_name,
                                                                add_vm_name,
                                                                True,
                                                                timeout=360)
                    if ret_clone.exit_status:
                        test.fail("Error when clone a second vm!")
                    vms.append(vm.clone(add_vm_name))
                    vm.start()
                vm2 = vms[1]
                logging.debug("Now the vms is: %s", [dom.name for dom in vms])
                # update the vm2 interface with the nwfilter
                logging.debug("filter_params_list is %s" % filter_param_list)
                iface_dict = {
                    "filter": filter_name,
                    "filter_parameters": filter_param_list,
                    "del_mac": True
                }
                if vm2.is_alive():
                    vm2.destroy()
                utlv.modify_vm_iface(vm2.name, "update_iface", iface_dict)
                vmxml = libvirt_xml.VMXML.new_from_inactive_dumpxml(vm2.name)
                iface_xml = vmxml.get_devices('interface')[0]
                logging.debug("iface_xml for vm2 is %s" % iface_xml)
                vm2.start()
                vm2_session = vm2.wait_for_serial_login()
                vm2_mac = vm2.get_mac_address()
                vm2_ip = utils_net.get_guest_ip_addr(vm2_session, vm2_mac)
                vm.session = vm.wait_for_serial_login()
                # test network functions, the 2 vms can not access to each other
                gateway_ip = utils_net.get_ip_address_by_interface("virbr0")
                status1, output1 = utils_net.ping(dest=vm2_ip,
                                                  count='3',
                                                  timeout=ping_timeout,
                                                  session=vm.session,
                                                  force_ipv4=True)
                status2, output2 = utils_net.ping(dest=gateway_ip,
                                                  count='3',
                                                  timeout=ping_timeout,
                                                  session=vm.session,
                                                  force_ipv4=True)
                status3, output3 = utils_net.ping(dest=dst_outside,
                                                  count='3',
                                                  timeout=ping_timeout,
                                                  session=vm.session,
                                                  force_ipv4=True)
                if not status1:
                    test.fail(
                        "vm with clean-traffic-gateway ping succeed to %s %s, but it is not expected!"
                        % (vm2.name, vm2_ip))
                if status2 or status3:
                    test.fail("vm ping failed! check %s \n %s" %
                              (output2, output3))
            if cmd_list_:
                loop = 0
                for check_cmd_, expect_match_ in cmd_result_dict.items():
                    check_cmd = check_cmd_.strip()
                    expect_match = expect_match_.strip()
                    if "DEVNAME" in check_cmd:
                        check_cmd = check_cmd.replace("DEVNAME", iface_target)
                    if "VMMAC" in expect_match:
                        expect_match = expect_match.replace("VMMAC", iface_mac)
                    logging.debug(
                        "the check_cmd is %s, and expected result is %s" %
                        (check_cmd, expect_match))
                    check_nwfilter_rules(check_cmd, expect_match)
                    loop += 1
        except virt_vm.VMStartError as e:
            # Starting VM failed.
            if not status_error:
                test.fail("Test failed in positive case.\n error:"
                          " %s\n%s" % (e, bug_url))

        if kill_libvirtd:
            daemon_name = libvirtd.service_name
            pid = process.run('pidof %s' % daemon_name,
                              shell=True).stdout_text.strip()
            cmd = "kill -s TERM %s" % pid
            process.run(cmd, shell=True)
            ret = utils_misc.wait_for(lambda: not libvirtd.is_running(),
                                      timeout=30)
            # After libvirt 5.6.0, libvirtd is using systemd socket activation by default
            if not ret and not libvirt_version.version_compare(5, 6, 0):
                test.fail("Failed to kill libvirtd. %s" % bug_url)

    finally:
        if kill_libvirtd:
            libvirtd.restart()
        # Clean env
        if vm.is_alive():
            vm.destroy(gracefully=False)
        # Recover xml of vm.
        vmxml_backup.sync()
        # Undefine created filter except clean-traffic as it is built-in nwfilter
        if filter_name != exist_filter and filter_name != 'clean-traffic':
            virsh.nwfilter_undefine(filter_name, debug=True)
        if mount_noexec_tmp:
            if device_name:
                process.run("umount -l %s" % device_name,
                            ignore_status=True,
                            shell=True)
            utlv.setup_or_cleanup_iscsi(is_setup=False)
        if ipset_command:
            process.run("ipset destroy blacklist", shell=True)
        # Remove additional vms
        if need_vm2:
            result = virsh.dom_list("--all").stdout_text
            if add_vm_name in result:
                virsh.remove_domain(add_vm_name, "--remove-all-storage")
Exemplo n.º 29
0
 def ping_test():
     host_ip = utils_net.get_host_ip_address(params)
     status, output = utils_net.ping(host_ip, 10, timeout=30)
     if status:
         test.fail("%s ping %s unexpected, output %s" %
                   (vm.name, host_ip, output))
Exemplo n.º 30
0
def run(test, params, env):
    """
    Test basic QinQ - 10 * 4096 with bridge backend

    1) Create a private bridge
    2) Boot a VM over private bridge
    3) Create interfaces in guest with qinq.sh
    4) Set IP on guest L1 interface and bring this interface on
    5) Create 802.1ad interface on host with the private bridge
    6) Start tcpdump on host
    7) Do ping test
    8) Check tcpdump result with vlan tag and ethertype
    9) Set IP on guest L2 interface and bring this interface on
    10) Create 802.1q interface on host with the 802.1ad interface
    11) Start tcpdump on host
    12) Do ping test
    13) Check tcpdump result with vlan tag and ethertype
    14) SCP file transfer between host and guest

    :param test: KVM test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """
    def copy_qinq_file(vm, guest_qinq_dir):
        """
        Copy qinq file from host to guest

        :param vm: guest vm
        :param guest_qinq_dir: qing script dir in guest

        """
        error_context.context("Copy qinq script to guest", logging.info)
        host_qinq_dir = os.path.join(data_dir.get_deps_dir(),
                                     params.get("copy_qinq_script"))
        vm.copy_files_to(host_qinq_dir, guest_qinq_dir)

    def check_tcpdump_result(session,
                             iface_name,
                             ethertype,
                             ethertype2=None,
                             vlan_tag=None,
                             vlan_tag2=None,
                             enable_logging=False):
        """
        Check tcpdump result.

        :param session: guest session
        :param iface_name: the tcpdump file of the interface
        :param ethertype: ethertype value need to be matched
        :param ethertype2: ethertype value 2 needed to be matched if not None
        :param vlan_tag: vlan tag value needed to be matched if not None
        :param vlan_tag2: vlan tag value 2 needed to be matched if not None
        :param enable_logging: whether to dump tcpdump results during test
        """
        get_tcpdump_log_cmd = params["get_tcpdump_log_cmd"] % iface_name
        tcpdump_content = session.cmd_output(get_tcpdump_log_cmd,
                                             timeout=300).strip()
        lines = tcpdump_content.splitlines()
        sum = 0
        for i in range(len(lines)):
            if enable_logging:
                logging.info("line %s: %s", i, lines[i])
            if not ethertype2:
                if "ICMP echo re" in lines[i] and \
                        ethertype in lines[i-1]:
                    sum += 1
                    if vlan_tag and vlan_tag not in lines[i - 1]:
                        if "too much work for irq" in lines[i - 1]:
                            continue
                        else:
                            test.fail(
                                "in %s tcpdump log, there should be vlan "
                                "tag %s" % (iface_name, vlan_tag))
                    elif not vlan_tag:
                        if "vlan" in lines[i - 1]:
                            test.fail("in %s tcpdump log, there should not be "
                                      "vlan tag" % iface_name)
            else:
                if "ICMP echo re" in lines[i] and \
                        ethertype in lines[i-1] and \
                        ethertype2 in lines[i-1]:
                    sum += 1
                    if vlan_tag not in lines[i-1] or \
                            vlan_tag2 not in lines[i-1]:
                        if "too much work for irq" in lines[i - 1]:
                            continue
                        else:
                            test.fail(
                                "in %s tcpdump log, there should be vlan "
                                "tag %s" % (iface_name, vlan_tag))
        if sum == 0:
            test.fail("in %s tcpdump log, ethertype is not %s" %
                      (iface_name, ethertype))

    def compare_host_guest_md5sum():
        """
        Compare md5 value of file on host and guest

        :param name: file name

        """
        logging.info("Comparing md5sum on guest and host")
        host_result = crypto.hash_file(host_path, algorithm="md5")
        try:
            output = session.cmd_output("md5sum %s" % guest_path,
                                        120).split()[0]
            guest_result = re.findall(r"\w+", output)[0]
        except IndexError:
            logging.error("Could not get file md5sum in guest")
            return False
        logging.debug("md5sum: guest(%s), host(%s)", guest_result, host_result)
        return guest_result == host_result

    if params["netdst"] not in utils_net.Bridge().list_br():
        test.cancel("Only support Linux bridge")

    login_timeout = int(params.get("login_timeout", "600"))
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    session = vm.wait_for_login(timeout=login_timeout)
    guest_qinq_dir = params["guest_qinq_dir"]
    copy_qinq_file(vm, guest_qinq_dir)
    session.close()
    vm.destroy(gracefully=True)

    brname = params.get("private_bridge", "tmpbr")
    host_bridges = utils_net.Bridge()
    if brname in host_bridges.list_br():
        utils_net.Interface(brname).down()
        host_bridges.del_bridge(brname)

    set_ip_cmd = params["set_ip_cmd"]
    logging.debug("Create private bridge %s", brname)
    host_bridges.add_bridge(brname)
    host_bridge_iface = utils_net.Interface(brname)
    logging.debug("Bring up %s", brname)
    process.system(set_ip_cmd % ("192.168.1.1", brname))
    host_bridge_iface.up()

    try:
        login_timeout = int(params.get("login_timeout", "600"))
        params['netdst'] = brname
        params["start_vm"] = "yes"
        params["image_snapshot"] = "yes"
        env_process.preprocess_vm(test, params, env, params["main_vm"])
        vm = env.get_vm(params["main_vm"])
        vm.verify_alive()

        session = vm.wait_for_serial_login(timeout=login_timeout)
        stop_NM_cmd = params.get("stop_NM_cmd")
        session.cmd(stop_NM_cmd, ignore_all_errors=True)
        mac = vm.get_mac_address()
        nic_name = utils_net.get_linux_ifname(session, mac)

        # Set first_nic IP in guest
        ip = params["ip_vm"]
        session.cmd_output(set_ip_cmd % (ip, nic_name))

        # Create vlans via script qinq.sh
        output = session.cmd_output("sh %sqinq.sh %s" %
                                    (guest_qinq_dir, nic_name),
                                    timeout=300)
        logging.info("%s", output)

        # Set interface v1v10 IP in guest
        L1tag_iface = params["L1tag_iface"]
        L1tag_iface_ip = params["L1tag_iface_ip"]
        session.cmd_output(set_ip_cmd % (L1tag_iface_ip, L1tag_iface))
        session.cmd("ip link set %s up" % L1tag_iface)
        output = session.cmd_output("ip addr show %s" % L1tag_iface,
                                    timeout=120)
        logging.info(output)

        # Start tcpdump on L1tag interface and first_nic in guest
        error_context.context("Start tcpdump in %s" % params["main_vm"],
                              logging.info)
        L1tag_tcpdump_log = params.get("tcpdump_log") % L1tag_iface
        L1tag_tcpdump_cmd = params.get("tcpdump_cmd") % (L1tag_iface,
                                                         L1tag_tcpdump_log)
        first_nic_tcpdump_log = params.get("tcpdump_log") % nic_name
        first_nic_tcpdump_cmd = params.get("tcpdump_cmd") % (
            nic_name, first_nic_tcpdump_log)
        session.sendline(L1tag_tcpdump_cmd)
        time.sleep(2)
        session.sendline(first_nic_tcpdump_cmd)
        time.sleep(5)

        # Create 802.1ad vlan via bridge in host
        error_context.context("Create 802.1ad vlan via bridge %s" % brname,
                              logging.info)
        advlan_ifname = params["advlan_name"]
        add_advlan_cmd = params["add_advlan_cmd"]
        process.system_output(add_advlan_cmd)
        advlan_iface = utils_net.Interface(advlan_ifname)
        advlan_iface.set_mac(params["advlan_mac"])
        process.system(set_ip_cmd % (params["advlan_ip"], advlan_ifname))
        advlan_iface.up()
        output = process.getoutput("ip addr show %s" % advlan_ifname)
        logging.info(output)

        # Ping guest from host via 802.1ad vlan interface
        error_context.context(
            "Start ping test from host to %s via %s" %
            (L1tag_iface_ip, advlan_ifname), logging.info)
        ping_count = int(params.get("ping_count"))
        status, output = utils_net.ping(L1tag_iface_ip,
                                        ping_count,
                                        interface=advlan_ifname,
                                        timeout=float(ping_count) * 1.5)
        if status != 0:
            test.fail("Ping returns non-zero value %s" % output)
        package_lost = utils_test.get_loss_ratio(output)
        if package_lost != 0:
            test.fail("%s packeage lost when ping guest ip %s " %
                      (package_lost, L1tag_iface_ip))

        # Stop tcpdump and check result
        session.cmd_output_safe("pkill tcpdump")
        check_tcpdump_result(session, L1tag_iface, "ethertype IPv4 (0x0800)")
        check_tcpdump_result(session,
                             nic_name,
                             "ethertype 802.1Q-QinQ (0x88a8)",
                             vlan_tag="vlan 10,")

        # Set IP on L2 tag on the guest interface with vid 20
        L2tag_iface = params["L2tag_iface"]
        L2tag_iface_ip = params["L2tag_iface_ip"]
        session.cmd_output(set_ip_cmd % (L2tag_iface_ip, L2tag_iface))
        session.cmd("ip link set %s up" % L2tag_iface)
        output = session.cmd_output("ip addr show %s" % L2tag_iface,
                                    timeout=120)
        logging.info(output)

        # Start tcpdump on L1tag and L2tag interfaces and first_nic in guest
        error_context.context("Start tcpdump in %s" % params["main_vm"],
                              logging.info)
        L2tag_tcpdump_log = params.get("tcpdump_log") % L2tag_iface
        L2tag_tcpdump_cmd = params.get("tcpdump_cmd") % (L2tag_iface,
                                                         L2tag_tcpdump_log)
        session.sendline(L1tag_tcpdump_cmd)
        time.sleep(2)
        session.sendline(L2tag_tcpdump_cmd)
        time.sleep(2)
        session.sendline(first_nic_tcpdump_cmd)
        time.sleep(5)

        # Create 802.1q vlan via 802.1ad vlan in host
        error_context.context(
            "Create 802.1q vlan via 802.1ad vlan %s" % advlan_ifname,
            logging.info)
        qvlan_ifname = params["qvlan_name"]
        add_qvlan_cmd = params["add_qvlan_cmd"]
        process.system_output(add_qvlan_cmd)
        qvlan_iface = utils_net.Interface(qvlan_ifname)
        process.system(set_ip_cmd % (params["qvlan_ip"], qvlan_ifname))
        qvlan_iface.up()
        output = process.getoutput("ip addr show %s" % qvlan_ifname)
        logging.info(output)

        # Ping guest from host via 802.1q vlan interface
        error_context.context(
            "Start ping test from host to %s via %s" %
            (L2tag_iface_ip, qvlan_ifname), logging.info)
        status, output = utils_net.ping(L2tag_iface_ip,
                                        ping_count,
                                        interface=qvlan_ifname,
                                        timeout=float(ping_count) * 1.5)
        if status != 0:
            test.fail("Ping returns non-zero value %s" % output)
        package_lost = utils_test.get_loss_ratio(output)
        if package_lost >= 5:
            test.fail("%s packeage lost when ping guest ip %s " %
                      (package_lost, L2tag_iface_ip))

        # Stop tcpdump and check result
        session.cmd_output_safe("pkill tcpdump")
        check_tcpdump_result(session,
                             L1tag_iface,
                             "ethertype 802.1Q (0x8100)",
                             vlan_tag="vlan 20,")
        check_tcpdump_result(session, L2tag_iface, "ethertype IPv4 (0x0800)")
        check_tcpdump_result(session,
                             nic_name,
                             ethertype="ethertype 802.1Q-QinQ (0x88a8)",
                             ethertype2="ethertype 802.1Q",
                             vlan_tag="vlan 10,",
                             vlan_tag2="vlan 20,")

        # scp file to guest with L2 vlan tag
        file_size = int(params.get("file_size", "4096"))
        host_path = os.path.join(test.tmpdir, "transferred_file")
        guest_path = params.get("guest_path", "/var/tmp/transferred_file")
        transfer_timeout = int(params.get("transfer_timeout", 1000))
        cmd = "dd if=/dev/zero of=%s bs=1M count=%d" % (host_path, file_size)
        error_context.context("Creating %dMB file on host" % file_size,
                              logging.info)
        process.run(cmd)
        error_context.context(
            "Transferring file host -> guest, "
            "timeout: %ss" % transfer_timeout, logging.info)
        shell_port = int(params.get("shell_port", 22))
        password = params["password"]
        username = params["username"]
        remote.scp_to_remote(L2tag_iface_ip, shell_port, username, password,
                             host_path, guest_path)
        if not compare_host_guest_md5sum():
            test.fail("md5sum mismatch on guest and host")
    finally:
        session.cmd("rm -rf %s" % guest_path)
        session.close()
        vm.destroy(gracefully=True)
        host_bridge_iface.down()
        host_bridges.del_bridge(brname)
Exemplo n.º 31
0
def run(test, params, env):
    """
    Bind netkvm protocol to netkvm adapter, and enabled manually without VF

    1) Boot a windows guest
    2) Enable driver verifier
    3) Install VIOPROT protocol
    4) Bind netkvm protocol to netkvm adapter
    5) Ping out

    :param test: QEMU test object.
    :param params: Dictionary with the test parameters.
    :param env: Dictionary with test environment.
    """

    timeout = params.get_numeric("timeout", 360)
    vm = env.get_vm(params["main_vm"])
    session = vm.wait_for_login(timeout=timeout)
    error_context.context("Check if the driver is installed and "
                          "verified", logging.info)
    driver_name = params.get("driver_name", "netkvm")
    session = utils_test.qemu.windrv_check_running_verifier(session, vm,
                                                            test,
                                                            driver_name,
                                                            timeout)
    error_context.context("Install VIOPROT protocol", logging.info)
    media_type = params["virtio_win_media_type"]
    try:
        get_drive_letter = getattr(virtio_win, "drive_letter_%s" % media_type)
        get_product_dirname = getattr(virtio_win,
                                      "product_dirname_%s" % media_type)
        get_arch_dirname = getattr(virtio_win, "arch_dirname_%s" % media_type)
    except AttributeError:
        test.error("Not supported virtio win media type '%s'", media_type)
    viowin_ltr = get_drive_letter(session)
    if not viowin_ltr:
        test.error("Could not find virtio-win drive in guest")
    guest_name = get_product_dirname(session)
    if not guest_name:
        test.error("Could not get product dirname of the vm")
    guest_arch = get_arch_dirname(session)
    if not guest_arch:
        test.error("Could not get architecture dirname of the vm")

    inf_middle_path = ("{name}\\{arch}" if media_type == "iso"
                       else "{arch}\\{name}").format(name=guest_name,
                                                     arch=guest_arch)
    inf_find_cmd = 'dir /b /s %s\\vioprot.inf | findstr "\\%s\\\\"'
    inf_find_cmd %= (viowin_ltr, inf_middle_path)
    inf_path = session.cmd(inf_find_cmd, timeout=timeout).strip()

    logging.info("Will install inf file found at '%s'", inf_path)
    install_cmd = params["install_cmd"] % inf_path
    status, output = session.cmd_status_output(install_cmd, timeout=timeout)
    if status:
        test.error("Install inf file failed, output=%s" % output)

    error_context.context("Bind netkvm protocol to netkvm adapter")
    nic_mac = vm.get_mac_address(0)
    connection_id = utils_net.get_windows_nic_attribute(
        session, "macaddress", nic_mac, "netconnectionid", timeout=timeout)
    bind_cmd = params["bind_cmd"] % connection_id
    status, output = session.cmd_status_output(bind_cmd, timeout=timeout)
    if status:
        test.error("Bind netkvm protocol failed, output=%s" % output)

    error_context.context("Ping out from guest", logging.info)
    host_ip = utils_net.get_host_ip_address(params)
    status, output = utils_net.ping(host_ip, count=10, timeout=60,
                                    session=session)
    if status:
        test.fail("Ping %s failed, output=%s" % (host_ip, output))
Exemplo n.º 32
0
def run(test, params, env):
    """
    Do network stress test when under memory stress
    1) Boot a guest with vhost=on
    2) swapoff in guest
    3) flood ping from guest to host
    4) do stress test

    :param test: QEMU test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """

    def flood_ping(session, host_ip, os_type="linux"):
        """
        Do flood ping from guest to host

        :param session: session to send flood ping
        :param host_ip: the IP of the host
        """
        flood_minutes = int(params["flood_minutes"])
        logging.info("Flood ping for %s minutes", flood_minutes)
        try:
            utils_net.ping(host_ip, flood=True,
                           session=session, timeout=flood_minutes * 60)
        except aexpect.ExpectProcessTerminatedError:
            if os_type == "windows":
                session.close()
                session = vm.wait_for_login(timeout=timeout)
                pass
        return session

    def load_stress():
        """
        Load background IO/CPU/Memory stress in guest

        """
        error_context.context("launch stress app in guest", logging.info)
        args = (test, params, env, params["stress_test"])
        bg_test = utils_test.BackgroundTest(
            utils_test.run_virt_sub_test, args)
        bg_test.start()
        if not utils_misc.wait_for(bg_test.is_alive, first=10,
                                   step=3, timeout=100):
            test.fail("background test start failed")

    def unload_stress(session):
        """
        Stop stress app

        :param session: guest session
        """
        error_context.context("stop stress app in guest", logging.info)
        cmd = params.get("stop_cmd")
        session.sendline(cmd)

    timeout = float(params.get("login_timeout", 240))
    vm = env.get_vm(params["main_vm"])
    host_ip = utils_net.get_host_ip_address(params)
    session = vm.wait_for_login(timeout=timeout)

    os_type = params["os_type"]
    if os_type == "linux":
        session.cmd("swapoff -a", timeout=300)

    error_context.context("Run memory heavy stress in guest", logging.info)
    if os_type == "linux":
        test_mem = params.get("memory", 256)
        stress_args = "--cpu 4 --io 4 --vm 2 --vm-bytes %sM" % int(test_mem)
        stress_test = utils_test.VMStress(vm, "stress", params, stress_args=stress_args)
        stress_test.load_stress_tool()
    else:
        load_stress()
    session = flood_ping(session, host_ip, os_type)
    if os_type == "linux":
        stress_test.unload_stress()
        stress_test.clean()
    else:
        unload_stress(session)

    error_context.context("Ping test after flood ping,"
                          " Check if the network is still alive",
                          logging.info)
    count = params["count"]
    timeout = float(count) * 2
    status, output = utils_net.ping(host_ip, count, session=session,
                                    timeout=timeout)
    if status != 0:
        test.fail("Ping failed, status: %s,"
                  " output: %s" % (status, output))

    session.close()