Example #1
0
    def do_test(test, params, env):
        """
        Do ping test, check msi support and do file transfer

        :param session: guest session
        :param vm: guest vm
        """
        login_timeout = int(params.get("login_timeout", 360))
        env_process.preprocess(test, params, env)
        vm = env.get_vm(params["main_vm"])
        vm.verify_alive()
        session = vm.wait_for_login(timeout=login_timeout)
        guest_ip = vm.get_address()
        ping_count = int(params.get("ping_count", 0))
        if not ping_count == 0:
            status, output = utils_test.ping(guest_ip,
                                             ping_count,
                                             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 server" % package_lost)

        check_msi_support(session)

        if params.get("do_file_transfer", "no") == "yes":
            utils_test.run_file_transfer(test, params, env)

        session.close()
        vm.destroy(gracefully=True)
Example #2
0
 def set_condn(action, recover=False):
     """
     Set/reset guest state/action
     :param action: Guest state change/action
     :param recover: whether to recover given state default: False
     """
     if not recover:
         if action == "pin_vcpu":
             for i in range(cur_vcpu):
                 virsh.vcpupin(vm_name, i, hmi_cpu, "--live",
                               ignore_status=False, debug=True)
                 virsh.emulatorpin(vm_name,  hmi_cpu, "live",
                                   ignore_status=False, debug=True)
         elif action == "filetrans":
             utils_test.run_file_transfer(test, params, env)
         elif action == "save":
             save_file = os.path.join(data_dir.get_tmp_dir(),
                                      vm_name + ".save")
             result = virsh.save(vm_name, save_file, ignore_status=True,
                                 debug=True)
             utils_test.libvirt.check_exit_status(result)
             time.sleep(10)
             if os.path.exists(save_file):
                 result = virsh.restore(save_file, ignore_status=True,
                                        debug=True)
                 utils_test.libvirt.check_exit_status(result)
                 os.remove(save_file)
         elif action == "suspend":
             result = virsh.suspend(vm_name, ignore_status=True, debug=True)
             utils_test.libvirt.check_exit_status(result)
             time.sleep(10)
             result = virsh.resume(vm_name, ignore_status=True, debug=True)
             utils_test.libvirt.check_exit_status(result)
     return
Example #3
0
def run_set_link(test, params, env):
    """
    KVM guest link test:
    1) Boot up guest with one nic
    2) Disable guest link by set_link
    3) Ping guest from host
    4) Re-enable guest link by set_link
    5) Ping guest from host
    6) Call utils_test.run_file_transfer function to test file transfer.
       It will do following steps:
       6.1) Create a large file by dd on host.
       6.2) Copy this file from host to guest.
       6.3) Copy this file from guest to host.
       6.4) Check if file transfers ended good.

    @param test: kvm test object
    @param params: Dictionary with the test parameters
    @param env: Dictionary with test environment.
    """
    vm = utils_test.get_living_vm(env, params.get("main_vm"))
    timeout = float(params.get("login_timeout", 360))
    # Waiting for guest boot up.
    session = vm.wait_for_login(timeout=timeout)
    session.close()

    def set_link_test(linkid):
        """
        Issue set_link commands and test its function

        @param linkid: id of netdev or devices to be tested
        """
        ip = vm.get_address(0)
        error.context("Disable guest link by set_link", logging.info)
        vm.set_link(linkid, up=False)
        error.context("Ping guest from host", logging.info)
        s, o = utils_test.ping(ip, count=10, timeout=20)
        if utils_test.get_loss_ratio(o) != 100:
            raise error.TestFail("Still can ping the %s after down %s" % (ip, linkid))

        error.context("Re-enable guest link by set_link", logging.info)
        vm.set_link(linkid, up=True)
        # Waiting for guest network up again.
        session = vm.wait_for_login(timeout=timeout)
        session.close()
        error.context("Ping guest from host", logging.info)
        s, o = utils_test.ping(ip, count=10, timeout=20)
        # we use 100% here as the notification of link status changed may be
        # delayed in guest driver
        if utils_test.get_loss_ratio(o) == 100:
            raise error.TestFail("Packet loss during ping %s after up %s" % (ip, linkid))

    netdev_id = vm.virtnet[0].netdev_id
    device_id = vm.virtnet[0].device_id
    logging.info("Issue set_link commands for netdevs")
    set_link_test(netdev_id)
    logging.info("Issue set_link commands for network devics")
    set_link_test(device_id)

    utils_test.run_file_transfer(test, params, env)
Example #4
0
    def _get_traffic_log(packet_filter):
        """
        Use wireshark to log the file transfer network traffic,
        and return the packets dump output.

        param packet_filter: the filter to apply when dump packets
        return: the output of the parse result
        """
        _start_wireshark_session()
        error_context.context("Start file transfer", logging.info)
        utils_test.run_file_transfer(test, params, env)
        time.sleep(30)
        _stop_wireshark_session()
        return _parse_log_file(packet_filter)
Example #5
0
    def start_test(checksum_config="tcp"):
        """
        Start tx/tx offload checksum test. First set tx/rx offload checksum
        value to the driver, the restart the nic and run file transfertest,

        param config: the setting config for checksum, tcp or disable
        """
        error_context.context(
            "Start set tx/rx checksum offload to %s" % checksum_config,
            logging.info)
        set_offload_checksum_windows(vm, True, checksum_config)
        set_offload_checksum_windows(vm, False, checksum_config)

        error_context.context("Start file transfer test", logging.info)
        utils_test.run_file_transfer(test, params, env)
Example #6
0
def run_set_link(test, params, env):
    """
    KVM guest link test:
    1) Boot up guest with one nic
    2) Ping guest from host
    3) Disable guest link and ping guest from host
    4) Re-enable guest link and ping guest from host
    5) Do file transfer test

    @param test: kvm test object
    @param params: Dictionary with the test parameters
    @param env: Dictionary with test environment.
    """
    vm = utils_test.get_living_vm(env, params.get("main_vm"))
    timeout = float(params.get("login_timeout", 360))
    session = utils_test.wait_for_login(vm, 0, timeout, 0, 2)

    def set_link_test(linkid):
        """
        Issue set_link commands and test its function

        @param linkid: id of netdev or devices to be tested
        """
        ip = vm.get_address(0)

        vm.set_link(linkid, up=False)
        _, o = utils_test.ping(ip, count=10, timeout=20)
        if utils_test.get_loss_ratio(o) != 100:
            raise error.TestFail("Still can ping the %s after down %s" %
                                 (ip, linkid))

        vm.set_link(linkid, up=True)
        _, o = utils_test.ping(ip, count=10, timeout=20)
        # we use 100% here as the notification of link status changed may be
        # delayed in guest driver
        if utils_test.get_loss_ratio(o) == 100:
            raise error.TestFail("Packet loss during ping %s after up %s" %
                                 (ip, linkid))

    netdev_id = vm.netdev_id[0]
    device_id = vm.get_peer(netdev_id)
    logging.info("Issue set_link commands for netdevs")
    set_link_test(netdev_id)
    logging.info("Issue set_link commands for network devics")
    set_link_test(device_id)

    utils_test.run_file_transfer(test, params, env)
    session.close()
Example #7
0
def run(test, params, env):
    """
    KVM guest link test:
    1) Boot up guest with one nic
    2) Disable guest link by set_link
    3) Check guest nic operstate and ping host from guest,
       will change queues number at the same time, when using mq
    4) Reboot the guest, then check guest nic operstate and do ping test
    5) Re-enable guest link by set_link
    6) Check guest nic operstate and ping host from guest,
       will change queues number at the same time, when using mq
    7) Reboot the guest, then check guest nic operstate and do ping test
    8) Call utils_test.run_file_transfer function to test file transfer.
       It will do following steps:
       8.1) Create a large file by dd on host.
       8.2) Copy this file from host to guest.
       8.3) Copy this file from guest to host.
       8.4) Check if file transfers ended good.

    :param test: kvm test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """
    def change_queues_number(session, ifname, q_number):
        """
        Change queues number, only used for mq test
        """
        mq_set_cmd = "ethtool -L %s combined %s" % (ifname, q_number)
        try:
            session.cmd_output_safe(mq_set_cmd)
        except aexpect.ShellError as err:
            err_msg = "Change queues number failed"
            err_msg += "Error info: '%s'" % err
            test.fail(err_msg)

    def change_queues_number_repeatly(guest_ifname):
        """
        Change queues repeatedly, only for mq test
        """
        session = vm.wait_for_serial_login()
        try:
            queues = params.get("queues", 1)
            change_list = range(1, int(queues) + 1)
            env["run_change_queues"] = True
            change_queues_number(session, guest_ifname, queues)
            while env["run_change_queues"]:
                for q_number in change_list:
                    change_queues_number(session, guest_ifname, q_number)
        finally:
            if "run_change_queues" in env:
                del env["run_change_queues"]
            session.close()

    def guest_reboot(reboot_method, link_up):
        """
        Reboot guest by different method (shell/system_reset)
        """
        try:
            vm.reboot(method=reboot_method, serial=True, timeout=120)
        except (remote.LoginError, virt_vm.VMAddressError):
            if not link_up:
                logging.info("Login error is expected when net link is down")

    def guest_netwok_connecting_check(guest_ip, link_up, change_queues=False):
        """
        Check whether guest network is connective by ping
        """
        if change_queues:
            env["run_change_queues"] = False
            bg_thread = utils_misc.InterruptedThread(
                change_queues_number_repeatly, (guest_ifname,))
            bg_thread.start()

            utils_misc.wait_for(lambda: env["run_change_queues"], 30, 0, 2,
                                "wait queues change start")
        time.sleep(0.5)
        output = utils_test.ping(guest_ip, 10, interface=host_interface,
                                 timeout=20, session=None)[1]
        if not link_up and utils_test.get_loss_ratio(output) < 80:
            err_msg = "guest network still connecting after down the link"
            test.fail(err_msg)
        elif link_up and utils_test.get_loss_ratio(output) > 20:
            err_msg = "All packets lost during ping guest ip after link up"
            test.fail(err_msg)

        if change_queues:
            env["run_change_queues"] = False
            bg_thread.join()

    def operstate_check(session, expect_status, guest_ifname=""):
        """
        Check Guest interface operstate
        """
        if params.get("os_type") == "linux":
            if_operstate = utils_net.get_net_if_operstate(guest_ifname,
                                                          session.cmd_output_safe)
        else:
            if_operstate = utils_net.get_windows_nic_attribute(session,
                                                               "macaddress",
                                                               vm.get_mac_address(),
                                                               "netconnectionstatus")

        if if_operstate != expect_status:
            err_msg = "Guest interface %s status error, " % guest_ifname
            err_msg = "currently interface status is '%s', " % if_operstate
            err_msg += "but expect status is '%s'" % expect_status
            test.fail(err_msg)
        logging.info("Guest interface operstate '%s' is exactly as expected" %
                     if_operstate)

    def guest_interface_operstate_check(expect_status, guest_ifname="",
                                        change_queues=False):
        """
        Check guest interface operstate, support mq
        """
        session = vm.wait_for_serial_login()
        try:
            if change_queues:
                queues = params.get("queues", 1)
                change_list = range(1, int(queues) + 1)
                for q_number in change_list:
                    change_queues_number(session, guest_ifname, q_number)
                    operstate_check(session, expect_status, guest_ifname)
            else:
                operstate_check(session, expect_status, guest_ifname)
        finally:
            session.close()

    def check_interface_ip_routine(session, mac_addr):
        """
        The routine to check the ip of interface.

        :param session: a session to send check commands
        :param mac_addr: the interface mac address
        """
        ip_addr = utils_net.get_net_if_addrs_win(session, mac_addr)
        guest_ipv4 = ip_addr["ipv4"]
        for ip in guest_ipv4:
            logging.debug("Check address: %s" % ip)
            if len(ip) != 0 and not ip.startswith("169.254"):
                return True
        return False

    def check_interface_ip(timeout=600):
        """
        Check whether the vm has got the available ip address.

        The check will be performed repeatedly until a correct ip address
        is detected or after the specified time is expired.

        :param timeout: total checking time allowed
        """
        error_context.context("Start checking guest ip", logging.info)
        session = vm.wait_for_serial_login()
        mac_addr = vm.get_mac_address()
        try:
            if not utils_misc.wait_for(
                    lambda: check_interface_ip_routine(session, mac_addr),
                    timeout,
                    step=5.0):
                err_msg = "Can't get valid ip in %s seconds" % timeout
                test.fail(err_msg)
        finally:
            session.close()

    def set_link_test(linkid, link_up, expect_status, change_queues=False,
                      operstate_always_up=False):
        """
        Issue set_link commands and test its function

        :param linkid: id of netdev or devices to be tested
        :param link_up: flag linkid is up or down
        :param expect_status : expect guest operstate status"
        :param operstate_always_up: when linkid is netdev id, guest interface
                                    operstate will never change,
                                    need set it to True.
        :param change_queues: whether run change mq queues, only effect on
                              linux guest with mq nic.

        """
        vm.set_link(linkid, up=link_up)
        time.sleep(1)
        error_context.context("Check guest interface operstate", logging.info)
        if operstate_always_up:
            if expect_status == "down":
                expect_status = "up"
            if expect_status == win_media_disconnected:
                expect_status = win_media_connected
        guest_interface_operstate_check(expect_status, guest_ifname,
                                        change_queues)
        if params.get("os_type") == "windows" and expect_status == win_media_connected:
            check_interface_ip()

        error_context.context("Check if guest network connective",
                              logging.info)
        guest_netwok_connecting_check(guest_ip, link_up, change_queues)

        reboot_method = params.get("reboot_method", "shell")

        error_context.context("Reboot guest by '%s' and recheck interface "
                              "operstate" % reboot_method, logging.info)
        guest_reboot(reboot_method, link_up)
        guest_interface_operstate_check(expect_status, guest_ifname,
                                        change_queues)

        error_context.context("Check guest network connecting after reboot "
                              "by '%s'" % reboot_method, logging.info)
        guest_netwok_connecting_check(guest_ip, link_up, change_queues)

    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    netdev_id = vm.virtnet[0].netdev_id
    device_id = vm.virtnet[0].device_id
    device_mac = vm.virtnet[0].mac
    host_interface = None
    if vm.virtnet[0].netdst:
        host_interface = vm.virtnet[0].netdst
    os_type = params.get("os_type", "linux")
    login_timeout = float(params.get("login_timeout", 360))
    session = vm.wait_for_login(timeout=login_timeout)

    change_queues = False
    guest_ifname = ""
    guest_ip = utils_net.get_guest_ip_addr(session, device_mac, os_type)
    # Win guest '2' represent 'Connected', '7' represent 'Media disconnected'
    win_media_connected = params.get("win_media_connected", "2")
    win_media_disconnected = params.get("win_media_disconnected", "7")

    if os_type == "linux":
        guest_ifname = utils_net.get_linux_ifname(session,
                                                  vm.get_mac_address())
        queues = int(params.get("queues", 1))
        if queues != 1 and vm.virtnet[0].nic_model == "virtio":
            change_queues = True

    session.close()

    expect_down_status = params.get("down-status", "down")
    expect_up_status = params.get("up-status", "up")
    operstate_always_up = params.get("operstate_always_up", "no") == "yes"

    error_context.context("Disable guest netdev link '%s' by set_link"
                          % netdev_id, logging.info)
    set_link_test(netdev_id, False, expect_down_status, change_queues,
                  operstate_always_up)

    error_context.context("Re-enable guest netdev link '%s' by set_link"
                          % netdev_id, logging.info)
    set_link_test(netdev_id, True, expect_up_status, change_queues,
                  operstate_always_up)

    error_context.context("Disable guest nic device '%s' by set_link"
                          % device_id, logging.info)
    set_link_test(device_id, False, expect_down_status, change_queues)

    error_context.context("Re-enable guest nic device '%s' by set_link"
                          % device_id, logging.info)
    set_link_test(device_id, True, expect_up_status, change_queues)

    error_context.context("Do file transfer after setlink on and off",
                          logging.info)
    utils_test.run_file_transfer(test, params, env)
Example #8
0
def run(test, params, env):
    """
    Test Steps:

    1. boot up guest with sndbuf=1048576 or other value.
    2. Transfer file between host and guest.
    3. Run netperf between host and guest.
    4. During netperf testing, from an external host ping the host whitch
       booting the guest.

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

    dst_ses = None
    try:
        error.context("Transfer file between host and guest", logging.info)
        utils_test.run_file_transfer(test, params, env)

        dsthost = params.get("dsthost")
        login_timeout = int(params.get("login_timeout", 360))
        if dsthost:
            params_host = params.object_params("dsthost")
            dst_ses = remote.wait_for_login(params_host.get("shell_client"),
                                            dsthost,
                                            params_host.get("shell_port"),
                                            params_host.get("username"),
                                            params_host.get("password"),
                                            params_host.get("shell_prompt"),
                                            timeout=login_timeout)
        else:
            vm = env.get_vm(params["main_vm"])
            vm.verify_alive()
            dst_ses = vm.wait_for_login(timeout=login_timeout)
            dsthost = vm.get_address()

        bg_stress_test = params.get("background_stress_test", 'netperf_stress')
        error.context("Run subtest %s between host and guest." % bg_stress_test,
                      logging.info)
        s_thread = ""
        wait_time = float(params.get("wait_bg_time", 60))
        bg_stress_run_flag = params.get("bg_stress_run_flag")
        env[bg_stress_run_flag] = False
        stress_thread = utils.InterruptedThread(
            utils_test.run_virt_sub_test, (test, params, env),
            {"sub_type": bg_stress_test})
        stress_thread.start()
        if not utils_misc.wait_for(lambda: env.get(bg_stress_run_flag),
                                   wait_time, 0, 1,
                                   "Wait %s test start" % bg_stress_test):
            err = "Fail to start netperf test between guest and host"
            raise error.TestError(err)

        ping_timeout = int(params.get("ping_timeout", 60))
        host_ip = utils_net.get_host_ip_address(params)
        txt = "Ping %s from %s during netperf testing" % (host_ip, dsthost)
        error.context(txt, logging.info)
        status, output = utils_test.ping(host_ip, session=dst_ses,
                                         timeout=ping_timeout)
        if status != 0:
            raise error.TestFail("Ping returns non-zero value %s" % output)

        package_lost = utils_test.get_loss_ratio(output)
        package_lost_ratio = float(params.get("package_lost_ratio", 5))
        txt = "%s%% packeage lost when ping %s from %s." % (package_lost,
                                                            host_ip,
                                                            dsthost)
        if package_lost > package_lost_ratio:
            raise error.TestFail(txt)
        logging.info(txt)

    finally:
        try:
            stress_thread.join(60)
        except Exception:
            pass
        if dst_ses:
            dst_ses.close()
Example #9
0
def run(test, params, env):
    """
    Different cpu compat mode scenario tests

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

    def check_feature(vm, feature="", vcpu=0):
        """
        Checks the given feature is present
        :param vm: VM Name
        :param feature: feature to be verified
        :param vcpu: vcpu number to pin guest test
        :return: true on success, test fail on failure
        """
        session = vm.wait_for_login()
        if 'power8' in feature:
            cmd = 'lscpu|grep -i "Model name:.*power8"'
        elif 'xive' in feature:
            # remove -v once guest xive support is available
            # right now power9 guest supports only xics
            cmd = "grep -v xive /sys/firmware/devicetree/base/interrupt-*/compatible"
        elif 'xics' in feature:
            cmd = "grep -v xive /sys/firmware/devicetree/base/interrupt-*/compatible"
        elif 'power9' in feature:
            cmd = 'lscpu|grep -i "Model name:.*power9"'
        elif 'hpt' in feature:
            cmd = 'grep "MMU.*: Hash" /proc/cpuinfo'
        elif 'rpt' in feature:
            cmd = 'grep "MMU.*: Radix" /proc/cpuinfo'
        elif 'isa' in feature:
            utils_package.package_install('gcc', session)
            cmd = "echo 'int main(){asm volatile (\".long 0x7c0005e6\");"
            cmd += "return 0;}' > ~/a.c;cc ~/a.c;taskset -c %s ./a.out" % vcpu
        status, output = session.cmd_status_output(cmd)
        logging.debug(output)
        session.close()
        if feature != "isa2.7":
            if status != 0:
                test.fail("Feature: %s check failed inside "
                          "%s guest on %s host" % (feature,
                                                   guest_version,
                                                   host_version))
        else:
            if status == 0:
                test.fail("isa3.0 instruction succeeds in "
                          "%s guest on %s host" % (guest_version,
                                                   host_version))
        return True

    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    pin_vcpu = 0
    host_version = params.get("host_version")
    guest_version = params.get("guest_version")
    max_vcpu = params.get("cpucompat_vcpu_max", "")
    cur_vcpu = int(params.get("cpucompat_vcpu_cur", "1"))
    cores = int(params.get("topology_cores", '1'))
    sockets = int(params.get("topology_sockets", '1'))
    threads = int(params.get("topology_threads", '1'))
    status_error = "yes" == params.get("status_error", "no")
    condn = params.get("condn", "")
    guest_features = params.get("guest_features", "")
    if guest_features:
        guest_features = guest_features.split(',')
        if guest_version:
            guest_features.append(guest_version)
    if host_version not in cpu.get_cpu_arch():
        test.cancel("Unsupported Host cpu version")

    vmxml = libvirt_xml.VMXML.new_from_inactive_dumpxml(vm_name)
    org_xml = vmxml.copy()
    # Destroy the vm
    vm.destroy()
    try:
        # Set cpu model
        if max_vcpu:
            pin_vcpu = int(max_vcpu) - 1
            libvirt_xml.VMXML.set_vm_vcpus(vm_name, int(max_vcpu), cur_vcpu,
                                           sockets=sockets, cores=cores,
                                           threads=threads, add_topology=True)
        libvirt_xml.VMXML.set_cpu_mode(vm_name, model=guest_version)
        logging.debug(virsh.dumpxml(vm_name))
        try:
            vm.start()
        except virt_vm.VMStartError as detail:
            if not status_error:
                test.fail("%s" % detail)
            else:
                pass
        if max_vcpu:
            virsh.setvcpus(vm_name, int(max_vcpu), "--live",
                           ignore_status=False, debug=True)
            if not cpu.check_if_vm_vcpu_match(int(max_vcpu), vm):
                test.fail("Vcpu hotplug failed")
        if not status_error:
            for feature in guest_features:
                check_feature(vm, feature, vcpu=pin_vcpu)
        if condn == "filetrans":
            utils_test.run_file_transfer(test, params, env)
        elif condn == "stress":
            bt = utils_test.run_avocado_bg(vm, params, test)
            if not bt:
                test.cancel("guest stress failed to start")
        elif condn == "save":
            save_file = os.path.join(data_dir.get_tmp_dir(), vm_name + ".save")
            result = virsh.save(vm_name, save_file, ignore_status=True,
                                debug=True)
            utils_test.libvirt.check_exit_status(result)
            # Just sleep few secs before guest recovery
            time.sleep(2)
            if os.path.exists(save_file):
                result = virsh.restore(save_file, ignore_status=True,
                                       debug=True)
                utils_test.libvirt.check_exit_status(result)
                os.remove(save_file)
        elif condn == "suspend":
            result = virsh.suspend(vm_name, ignore_status=True, debug=True)
            utils_test.libvirt.check_exit_status(result)
            # Just sleep few secs before guest recovery
            time.sleep(2)
            result = virsh.resume(vm_name, ignore_status=True, debug=True)
            utils_test.libvirt.check_exit_status(result)
        else:
            pass
    finally:
        org_xml.sync()
Example #10
0
def run(test, params, env):
    """
    Nic bonding test in guest.

    1) Start guest with four nic devices.
    2) Setup bond0 in guest.
    3) Execute file transfer test between guest and host.
    4) Repeatedly put down/up interfaces by 'ip link'
    5) Execute file transfer test between guest and host.

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

    timeout = int(params.get("login_timeout", 1200))
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    session_serial = vm.wait_for_serial_login(timeout=timeout)
    ifnames = utils_net.get_linux_ifname(session_serial)

    ssh_login_cmd = (
        "echo LoginGraceTime 5m  >> /etc/ssh/sshd_config &&"
        " systemctl restart sshd.service || service sshd restart")
    session_serial.cmd_output_safe(ssh_login_cmd)

    # get params of bonding
    nm_stop_cmd = "service NetworkManager stop; true"
    session_serial.cmd_output_safe(nm_stop_cmd)
    modprobe_cmd = "modprobe bonding"
    bonding_params = params.get("bonding_params")
    if bonding_params:
        modprobe_cmd += " %s" % bonding_params
    session_serial.cmd_output_safe(modprobe_cmd)
    session_serial.cmd_output_safe("ifconfig bond0 up")
    setup_cmd = "ifenslave bond0 " + " ".join(ifnames)
    session_serial.cmd_output_safe(setup_cmd)
    # do a pgrep to check if dhclient has already been running
    pgrep_cmd = "pgrep dhclient"
    try:
        session_serial.cmd_output_safe(pgrep_cmd)
    # if dhclient is there, killl it
    except aexpect.ShellCmdError:
        logging.info("it's safe to run dhclient now")
    else:
        logging.info("dhclient is already running, kill it")
        session_serial.cmd_output_safe("killall -9 dhclient")
        time.sleep(1)

    session_serial.cmd_output_safe("dhclient bond0")

    # get_bonding_nic_mac and ip
    try:
        link_set_cmd = "ip link set dev %s %s"
        logging.info("Test file transferring:")
        utils_test.run_file_transfer(test, params, env)

        logging.info("Failover test with file transfer")
        transfer_thread = utils_misc.InterruptedThread(
            utils_test.run_file_transfer, (test, params, env))
        transfer_thread.start()
        try:
            while transfer_thread.isAlive():
                for ifname in ifnames:
                    session_serial.cmd(link_set_cmd % (ifname, "down"))
                    time.sleep(random.randint(1, 30))
                    session_serial.cmd(link_set_cmd % (ifname, "up"))
                    time.sleep(random.randint(1, 30))

        except Exception:
            transfer_thread.join(suppress_exception=True)
            raise
        else:
            transfer_thread.join()

        logging.info("Failover test 2 with file transfer")
        transfer_thread = utils_misc.InterruptedThread(
            utils_test.run_file_transfer, (test, params, env))
        transfer_thread.start()
        try:
            nic_num = len(ifnames)
            up_index = 0
            while transfer_thread.isAlive():
                up_index = up_index % nic_num
                for num in range(nic_num):
                    if num == up_index:
                        session_serial.cmd(link_set_cmd % (ifnames[num], "up"))
                    else:
                        session_serial.cmd(link_set_cmd % (ifnames[num], "down"))
                time.sleep(random.randint(1, 5))
                up_index += 1
        except Exception:
            transfer_thread.join(suppress_exception=True)
            raise
        else:
            transfer_thread.join()
    finally:
        session_serial.sendline("ifenslave -d bond0 " + " ".join(ifnames))
        session_serial.sendline("kill -9 `pgrep dhclient`")
        session_serial.sendline("sed -i '$ d' /etc/ssh/sshd_config")
Example #11
0
def run(test, params, env):
    """
    Nic bonding test in guest.

    1) Start guest with four nic models.
    2) Setup bond0 in guest by script nic_bonding_guest.py.
    3) Execute file transfer test between guest and host.
    4) Repeatedly put down/up interfaces by set_link
    5) Execute file transfer test between guest and host.

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

    timeout = int(params.get("login_timeout", 1200))
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    session_serial = vm.wait_for_serial_login(timeout=timeout)
    ifnames = [utils_net.get_linux_ifname(session_serial,
                                          vm.get_mac_address(vlan))
               for vlan, nic in enumerate(vm.virtnet)]

    # get params of bonding
    nm_stop_cmd = "pidof NetworkManager && service NetworkManager stop; true"
    session_serial.cmd_output_safe(nm_stop_cmd)
    modprobe_cmd = "modprobe bonding"
    bonding_params = params.get("bonding_params")
    if bonding_params:
        modprobe_cmd += " %s" % bonding_params
    session_serial.cmd_output_safe(modprobe_cmd)
    session_serial.cmd_output_safe("ifconfig bond0 up")
    setup_cmd = "ifenslave bond0 " + " ".join(ifnames)
    session_serial.cmd_output_safe(setup_cmd)
    # do a pgrep to check if dhclient has already been running
    pgrep_cmd = "pgrep dhclient"
    try:
        session_serial.cmd_output_safe(pgrep_cmd)
    # if dhclient is there, killl it
    except aexpect.ShellCmdError:
        logging.info("it's safe to run dhclient now")
    else:
        logging.info("dhclient already is running,kill it")
        session_serial.cmd_output_safe("killall -9 dhclient")
        time.sleep(1)

    session_serial.cmd_output_safe("dhclient bond0")

    #get_bonding_nic_mac and ip
    try:
        logging.info("Test file transferring:")
        utils_test.run_file_transfer(test, params, env)

        logging.info("Failover test with file transfer")
        transfer_thread = utils.InterruptedThread(utils_test.run_file_transfer,
                                                  (test, params, env))
        transfer_thread.start()
        try:
            while transfer_thread.isAlive():
                for vlan, nic in enumerate(vm.virtnet):
                    device_id = nic.device_id
                    if not device_id:
                        raise error.TestError("Could not find peer device for"
                                              " nic device %s" % nic)
                    vm.set_link(device_id, up=False)
                    time.sleep(random.randint(1, 30))
                    vm.set_link(device_id, up=True)
                    time.sleep(random.randint(1, 30))
        except Exception:
            transfer_thread.join(suppress_exception=True)
            raise
        else:
            transfer_thread.join()
    finally:
        session_serial.sendline("ifenslave -d bond0 " + " ".join(ifnames))
        session_serial.sendline("kill -9 `pgrep dhclient`")
Example #12
0
def run(test, params, env):
    """
    Different cpu compat mode scenario tests

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

    def check_feature(vm, feature="", vcpu=0):
        """
        Checks the given feature is present
        :param vm: VM Name
        :param feature: feature to be verified
        :param vcpu: vcpu number to pin guest test
        :return: true on success, test fail on failure
        """
        session = vm.wait_for_login()
        if 'power8' in feature:
            cmd = 'lscpu|grep -i "Model name:.*power8"'
        elif 'xive' in feature:
            # remove -v once guest xive support is available
            # right now power9 guest supports only xics
            cmd = "grep -v xive /sys/firmware/devicetree/base/interrupt-*/compatible"
        elif 'xics' in feature:
            cmd = "grep -v xive /sys/firmware/devicetree/base/interrupt-*/compatible"
        elif 'power9' in feature:
            cmd = 'lscpu|grep -i "Model name:.*power9"'
        elif 'hpt' in feature:
            cmd = 'grep "MMU.*: Hash" /proc/cpuinfo'
        elif 'rpt' in feature:
            cmd = 'grep "MMU.*: Radix" /proc/cpuinfo'
        elif 'isa' in feature:
            utils_package.package_install('gcc', session)
            cmd = "echo 'int main(){asm volatile (\".long 0x7c0005e6\");"
            cmd += "return 0;}' > ~/a.c;cc ~/a.c;taskset -c %s ./a.out" % vcpu
        status, output = session.cmd_status_output(cmd)
        logging.debug(output)
        session.close()
        if feature != "isa2.7":
            if status != 0:
                test.fail("Feature: %s check failed inside "
                          "%s guest on %s host" % (feature,
                                                   guest_version,
                                                   host_version))
        else:
            if status == 0:
                test.fail("isa3.0 instruction succeeds in "
                          "%s guest on %s host" % (guest_version,
                                                   host_version))
        return True

    vm_name = params.get("main_vm")
    vm = env.get_vm(vm_name)
    pin_vcpu = 0
    host_version = params.get("host_version")
    guest_version = params.get("guest_version")
    max_vcpu = params.get("cpucompat_vcpu_max", "")
    cur_vcpu = int(params.get("cpucompat_vcpu_cur", "1"))
    cores = int(params.get("topology_cores", '1'))
    sockets = int(params.get("topology_sockets", '1'))
    threads = int(params.get("topology_threads", '1'))
    status_error = "yes" == params.get("status_error", "no")
    condn = params.get("condn", "")
    guest_features = params.get("guest_features", "")
    if guest_features:
        guest_features = guest_features.split(',')
        if guest_version:
            guest_features.append(guest_version)
    if host_version not in cpu.get_cpu_arch():
        test.cancel("Unsupported Host cpu version")

    vmxml = libvirt_xml.VMXML.new_from_inactive_dumpxml(vm_name)
    org_xml = vmxml.copy()
    # Destroy the vm
    vm.destroy()
    try:
        # Set cpu model
        if max_vcpu:
            pin_vcpu = int(max_vcpu) - 1
            libvirt_xml.VMXML.set_vm_vcpus(vm_name, int(max_vcpu), cur_vcpu,
                                           sockets=sockets, cores=cores,
                                           threads=threads, add_topology=True)
        libvirt_xml.VMXML.set_cpu_mode(vm_name, model=guest_version)
        logging.debug(virsh.dumpxml(vm_name))
        try:
            vm.start()
        except virt_vm.VMStartError as detail:
            if not status_error:
                test.fail("%s" % detail)
            else:
                pass
        if max_vcpu:
            virsh.setvcpus(vm_name, int(max_vcpu), "--live",
                           ignore_status=False, debug=True)
            if not utils_misc.check_if_vm_vcpu_match(int(max_vcpu), vm):
                test.fail("Vcpu hotplug failed")
        if not status_error:
            for feature in guest_features:
                check_feature(vm, feature, vcpu=pin_vcpu)
        if condn == "filetrans":
            utils_test.run_file_transfer(test, params, env)
        elif condn == "stress":
            bt = utils_test.run_avocado_bg(vm, params, test)
            if not bt:
                test.cancel("guest stress failed to start")
        elif condn == "save":
            save_file = os.path.join(data_dir.get_tmp_dir(), vm_name + ".save")
            result = virsh.save(vm_name, save_file, ignore_status=True,
                                debug=True)
            utils_test.libvirt.check_exit_status(result)
            # Just sleep few secs before guest recovery
            time.sleep(2)
            if os.path.exists(save_file):
                result = virsh.restore(save_file, ignore_status=True,
                                       debug=True)
                utils_test.libvirt.check_exit_status(result)
                os.remove(save_file)
        elif condn == "suspend":
            result = virsh.suspend(vm_name, ignore_status=True, debug=True)
            utils_test.libvirt.check_exit_status(result)
            # Just sleep few secs before guest recovery
            time.sleep(2)
            result = virsh.resume(vm_name, ignore_status=True, debug=True)
            utils_test.libvirt.check_exit_status(result)
        else:
            pass
    finally:
        org_xml.sync()
def run(test, params, env):
    """
    QEMU flow caches stress test test

    1) Make sure nf_conntrack is disabled in host and guest.
       If nf_conntrack is enabled in host, skip this case.
    2) Boot guest with vhost=on/off.
    3) Enable multi queues support in guest (optional).
    4) After installation of netperf, run netserver in host.
    5) Run netperf TCP_CRR protocal test in guest.
    6) Transfer file between guest and host.
    7) Check the md5 of copied file.

    This is a sample QEMU test, so people can get used to some of the test APIs.

    :param test: QEMU test object.
    :param params: Dictionary with the test parameters.
    :param env: Dictionary with test environment.
    """
    msg = "Make sure nf_conntrack is disabled in host and guest."
    error_context.context(msg, logging.info)
    if "nf_conntrack" in process.system_output("lsmod"):
        err = "nf_conntrack load in host, skip this case"
        test.cancel(err)

    params["start_vm"] = "yes"
    error_context.context("Boot up guest", logging.info)
    env_process.preprocess_vm(test, params, env, params["main_vm"])
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()

    timeout = int(params.get("login_timeout", 360))
    session = vm.wait_for_login(timeout=timeout)
    if "nf_conntrack" in session.cmd_output("lsmod"):
        msg = "Unload nf_conntrack module in guest."
        error_context.context(msg, logging.info)
        black_str = "#disable nf_conntrack\\nblacklist nf_conntrack\\n" \
                    "blacklist nf_conntrack_ipv6\\nblacklist xt_conntrack\\n" \
                    "blacklist nf_conntrack_ftp\\nblacklist xt_state\\n" \
                    "blacklist iptable_nat\\nblacklist ipt_REDIRECT\\n" \
                    "blacklist nf_nat\\nblacklist nf_conntrack_ipv4"
        cmd = "echo -e '%s' >> /etc/modprobe.d/blacklist.conf" % black_str
        session.cmd(cmd)
        session = vm.reboot(session, timeout=timeout)
        if "nf_conntrack" in session.cmd_output("lsmod"):
            err = "Fail to unload nf_conntrack module in guest."
            test.error(err)

    netperf_link = utils_misc.get_path(data_dir.get_deps_dir("netperf"),
                                       params["netperf_link"])
    md5sum = params.get("pkg_md5sum")
    win_netperf_link = params.get("win_netperf_link")
    if win_netperf_link:
        win_netperf_link = utils_misc.get_path(
            data_dir.get_deps_dir("netperf"), win_netperf_link)
    win_netperf_md5sum = params.get("win_netperf_md5sum")
    server_path = params.get("server_path", "/var/tmp/")
    client_path = params.get("client_path", "/var/tmp/")
    win_netperf_path = params.get("win_netperf_path", "c:\\")
    client_num = params.get("netperf_client_num", 520)
    netperf_timeout = int(params.get("netperf_timeout", 600))
    netperf_client_ip = vm.get_address()
    host_ip = utils_net.get_host_ip_address(params)
    netperf_server_ip = params.get("netperf_server_ip", host_ip)

    username = params.get("username", "root")
    password = params.get("password", "123456")
    passwd = params.get("hostpasswd", "123456")
    client = params.get("shell_client", "ssh")
    port = params.get("shell_port", "22")
    prompt = params.get("shell_prompt", r"^root@.*[\#\$]\s*$|#")
    linesep = params.get("shell_linesep",
                         "\n").encode().decode('unicode_escape')
    status_test_command = params.get("status_test_command", "echo $?")

    compile_option_client = params.get("compile_option_client", "")
    compile_option_server = params.get("compile_option_server", "")

    if int(params.get("queues", 1)) > 1 and params.get("os_type") == "linux":
        error_context.context("Enable multi queues support in guest.",
                              logging.info)
        guest_mac = vm.get_mac_address()
        ifname = utils_net.get_linux_ifname(session, guest_mac)
        cmd = "ethtool -L %s combined  %s" % (ifname, params.get("queues"))
        status, out = session.cmd_status_output(cmd)
        msg = "Fail to enable multi queues support in guest."
        msg += "Command %s fail output: %s" % (cmd, out)
        test.error(msg)

    if params.get("os_type") == "linux":
        session.cmd("iptables -F", ignore_all_errors=True)
        g_client_link = netperf_link
        g_client_path = client_path
        g_md5sum = md5sum
    elif params.get("os_type") == "windows":
        g_client_link = win_netperf_link
        g_client_path = win_netperf_path
        g_md5sum = win_netperf_md5sum

    error_context.context("Setup netperf in guest and host", logging.info)
    netperf_client = utils_netperf.NetperfClient(
        netperf_client_ip,
        g_client_path,
        g_md5sum,
        g_client_link,
        username=username,
        password=password,
        prompt=prompt,
        linesep=linesep,
        status_test_command=status_test_command,
        compile_option=compile_option_client)

    netperf_server = utils_netperf.NetperfServer(
        netperf_server_ip,
        server_path,
        md5sum,
        netperf_link,
        client,
        port,
        password=passwd,
        prompt=prompt,
        linesep=linesep,
        status_test_command=status_test_command,
        compile_option=compile_option_server)
    try:
        error_context.base_context("Run netperf test between host and guest.")
        error_context.context("Start netserver in host.", logging.info)
        netperf_server.start()

        error_context.context(
            "Start Netperf in guest for %ss." % netperf_timeout, logging.info)
        test_option = "-t TCP_CRR -l %s -- -b 10 -D" % netperf_timeout
        netperf_client.bg_start(netperf_server_ip, test_option, client_num)

        utils_misc.wait_for(lambda: not netperf_client.is_netperf_running(),
                            timeout=netperf_timeout,
                            first=590,
                            step=2)

        utils_test.run_file_transfer(test, params, env)
    finally:
        netperf_server.stop()
        netperf_client.package.env_cleanup(True)
        if session:
            session.close()
def run(test, params, env):
    """
    QEMU flow caches stress test test

    1) Make sure nf_conntrack is disabled in host and guest.
       If nf_conntrack is enabled in host, skip this case.
    2) Boot guest with vhost=on/off.
    3) Enable multi queues support in guest (optional).
    4) After installation of netperf, run netserver in host.
    5) Run netperf TCP_CRR protocal test in guest.
    6) Transfer file between guest and host.
    7) Check the md5 of copied file.

    This is a sample QEMU test, so people can get used to some of the test APIs.

    :param test: QEMU test object.
    :param params: Dictionary with the test parameters.
    :param env: Dictionary with test environment.
    """
    msg = "Make sure nf_conntrack is disabled in host and guest."
    error_context.context(msg, logging.info)
    if "nf_conntrack" in process.system_output("lsmod"):
        err = "nf_conntrack load in host, skip this case"
        test.cancel(err)

    params["start_vm"] = "yes"
    error_context.context("Boot up guest", logging.info)
    env_process.preprocess_vm(test, params, env, params["main_vm"])
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()

    timeout = int(params.get("login_timeout", 360))
    session = vm.wait_for_login(timeout=timeout)
    if "nf_conntrack" in session.cmd_output("lsmod"):
        msg = "Unload nf_conntrack module in guest."
        error_context.context(msg, logging.info)
        black_str = "#disable nf_conntrack\\nblacklist nf_conntrack\\n" \
                    "blacklist nf_conntrack_ipv6\\nblacklist xt_conntrack\\n" \
                    "blacklist nf_conntrack_ftp\\nblacklist xt_state\\n" \
                    "blacklist iptable_nat\\nblacklist ipt_REDIRECT\\n" \
                    "blacklist nf_nat\\nblacklist nf_conntrack_ipv4"
        cmd = "echo -e '%s' >> /etc/modprobe.d/blacklist.conf" % black_str
        session.cmd(cmd)
        session = vm.reboot(session, timeout=timeout)
        if "nf_conntrack" in session.cmd_output("lsmod"):
            err = "Fail to unload nf_conntrack module in guest."
            test.error(err)

    netperf_link = utils_misc.get_path(data_dir.get_deps_dir("netperf"),
                                       params["netperf_link"])
    md5sum = params.get("pkg_md5sum")
    win_netperf_link = params.get("win_netperf_link")
    if win_netperf_link:
        win_netperf_link = utils_misc.get_path(data_dir.get_deps_dir("netperf"),
                                               win_netperf_link)
    win_netperf_md5sum = params.get("win_netperf_md5sum")
    server_path = params.get("server_path", "/var/tmp/")
    client_path = params.get("client_path", "/var/tmp/")
    win_netperf_path = params.get("win_netperf_path", "c:\\")
    client_num = params.get("netperf_client_num", 520)
    netperf_timeout = int(params.get("netperf_timeout", 600))
    netperf_client_ip = vm.get_address()
    host_ip = utils_net.get_host_ip_address(params)
    netperf_server_ip = params.get("netperf_server_ip", host_ip)

    username = params.get("username", "root")
    password = params.get("password", "123456")
    passwd = params.get("hostpasswd", "123456")
    client = params.get("shell_client", "ssh")
    port = params.get("shell_port", "22")
    prompt = params.get("shell_prompt", r"^root@.*[\#\$]\s*$|#")
    linesep = params.get(
        "shell_linesep", "\n").encode().decode('unicode_escape')
    status_test_command = params.get("status_test_command", "echo $?")

    compile_option_client = params.get("compile_option_client", "")
    compile_option_server = params.get("compile_option_server", "")

    if int(params.get("queues", 1)) > 1 and params.get("os_type") == "linux":
        error_context.context("Enable multi queues support in guest.",
                              logging.info)
        guest_mac = vm.get_mac_address()
        ifname = utils_net.get_linux_ifname(session, guest_mac)
        cmd = "ethtool -L %s combined  %s" % (ifname, params.get("queues"))
        status, out = session.cmd_status_output(cmd)
        msg = "Fail to enable multi queues support in guest."
        msg += "Command %s fail output: %s" % (cmd, out)
        test.error(msg)

    if params.get("os_type") == "linux":
        session.cmd("iptables -F", ignore_all_errors=True)
        g_client_link = netperf_link
        g_client_path = client_path
        g_md5sum = md5sum
    elif params.get("os_type") == "windows":
        g_client_link = win_netperf_link
        g_client_path = win_netperf_path
        g_md5sum = win_netperf_md5sum

    error_context.context("Setup netperf in guest and host", logging.info)
    netperf_client = utils_netperf.NetperfClient(netperf_client_ip,
                                                 g_client_path,
                                                 g_md5sum, g_client_link,
                                                 username=username,
                                                 password=password,
                                                 prompt=prompt,
                                                 linesep=linesep,
                                                 status_test_command=status_test_command,
                                                 compile_option=compile_option_client)

    netperf_server = utils_netperf.NetperfServer(netperf_server_ip,
                                                 server_path,
                                                 md5sum,
                                                 netperf_link,
                                                 client, port,
                                                 password=passwd,
                                                 prompt=prompt,
                                                 linesep=linesep,
                                                 status_test_command=status_test_command,
                                                 compile_option=compile_option_server)
    try:
        error_context.base_context("Run netperf test between host and guest.")
        error_context.context("Start netserver in host.", logging.info)
        netperf_server.start()

        error_context.context("Start Netperf in guest for %ss."
                              % netperf_timeout, logging.info)
        test_option = "-t TCP_CRR -l %s -- -b 10 -D" % netperf_timeout
        netperf_client.bg_start(netperf_server_ip, test_option, client_num)

        utils_misc.wait_for(lambda: not netperf_client.is_netperf_running(),
                            timeout=netperf_timeout, first=590, step=2)

        utils_test.run_file_transfer(test, params, env)
    finally:
        netperf_server.stop()
        netperf_client.package.env_cleanup(True)
        if session:
            session.close()
Example #15
0
 def scp_test(self):
     utils_test.run_file_transfer(self.test, self.params, self.env)
Example #16
0
def run_set_link(test, params, env):
    """
    KVM guest link test:
    1) Boot up guest with one nic
    2) Disable guest link by set_link
    3) Ping guest from host
    4) Re-enable guest link by set_link
    5) Ping guest from host
    6) Call utils_test.run_file_transfer function to test file transfer.
       It will do following steps:
       6.1) Create a large file by dd on host.
       6.2) Copy this file from host to guest.
       6.3) Copy this file from guest to host.
       6.4) Check if file transfers ended good.

    @param test: kvm test object
    @param params: Dictionary with the test parameters
    @param env: Dictionary with test environment.
    """
    vm = utils_test.get_living_vm(env, params.get("main_vm"))
    timeout = float(params.get("login_timeout", 360))
    # Waiting for guest boot up.
    session = vm.wait_for_login(timeout=timeout)
    session.close()

    def set_link_test(linkid):
        """
        Issue set_link commands and test its function

        @param linkid: id of netdev or devices to be tested
        """
        ip = vm.get_address(0)
        error.context("Disable guest link by set_link", logging.info)
        vm.set_link(linkid, up=False)
        error.context("Ping guest from host", logging.info)
        s, o = utils_test.ping(ip, count=10, timeout=20)
        if utils_test.get_loss_ratio(o) != 100:
            raise error.TestFail("Still can ping the %s after down %s" %
                                 (ip, linkid))

        error.context("Re-enable guest link by set_link", logging.info)
        vm.set_link(linkid, up=True)
        # Waiting for guest network up again.
        session = vm.wait_for_login(timeout=timeout)
        session.close()
        error.context("Ping guest from host", logging.info)
        s, o = utils_test.ping(ip, count=10, timeout=20)
        # we use 100% here as the notification of link status changed may be
        # delayed in guest driver
        if utils_test.get_loss_ratio(o) == 100:
            raise error.TestFail("Packet loss during ping %s after up %s" %
                                 (ip, linkid))

    netdev_id = vm.virtnet[0].netdev_id
    device_id = vm.virtnet[0].device_id
    logging.info("Issue set_link commands for netdevs")
    set_link_test(netdev_id)
    logging.info("Issue set_link commands for network devics")
    set_link_test(device_id)

    utils_test.run_file_transfer(test, params, env)
Example #17
0
def run(test, params, env):
    """
    Nic bonding test in guest.

    1) Start guest with four nic models.
    2) Setup bond0 in guest by script nic_bonding_guest.py.
    3) Execute file transfer test between guest and host.
    4) Repeatedly put down/up interfaces by set_link
    5) Execute file transfer test between guest and host.

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

    timeout = int(params.get("login_timeout", 1200))
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    session_serial = vm.wait_for_serial_login(timeout=timeout)
    ifnames = [utils_net.get_linux_ifname(session_serial,
                                          vm.get_mac_address(vlan))
               for vlan, nic in enumerate(vm.virtnet)]

    ssh_login_cmd = (
        "echo LoginGraceTime 5m  >> /etc/ssh/sshd_config &&"
        " systemctl restart sshd.service || service sshd restart")
    session_serial.cmd_output_safe(ssh_login_cmd)

    # get params of bonding
    nm_stop_cmd = "pidof NetworkManager && service NetworkManager stop; true"
    session_serial.cmd_output_safe(nm_stop_cmd)
    modprobe_cmd = "modprobe bonding"
    bonding_params = params.get("bonding_params")
    if bonding_params:
        modprobe_cmd += " %s" % bonding_params
    session_serial.cmd_output_safe(modprobe_cmd)
    session_serial.cmd_output_safe("ifconfig bond0 up")
    setup_cmd = "ifenslave bond0 " + " ".join(ifnames)
    session_serial.cmd_output_safe(setup_cmd)
    # do a pgrep to check if dhclient has already been running
    pgrep_cmd = "pgrep dhclient"
    try:
        session_serial.cmd_output_safe(pgrep_cmd)
    # if dhclient is there, killl it
    except aexpect.ShellCmdError:
        logging.info("it's safe to run dhclient now")
    else:
        logging.info("dhclient is already running, kill it")
        session_serial.cmd_output_safe("killall -9 dhclient")
        time.sleep(1)

    session_serial.cmd_output_safe("dhclient bond0")

    # get_bonding_nic_mac and ip
    try:
        logging.info("Test file transferring:")
        utils_test.run_file_transfer(test, params, env)

        logging.info("Failover test with file transfer")
        transfer_thread = utils_misc.InterruptedThread(
            utils_test.run_file_transfer, (test, params, env))
        transfer_thread.start()
        try:
            while transfer_thread.isAlive():
                for vlan, nic in enumerate(vm.virtnet):
                    device_id = nic.device_id
                    if not device_id:
                        test.error("Could not find peer device for"
                                   " nic device %s" % nic)
                    vm.set_link(device_id, up=False)
                    time.sleep(random.randint(1, 30))
                    vm.set_link(device_id, up=True)
                    time.sleep(random.randint(1, 30))
        except Exception:
            transfer_thread.join(suppress_exception=True)
            raise
        else:
            transfer_thread.join()

        logging.info("Failover test 2 with file transfer")
        transfer_thread = utils_misc.InterruptedThread(
            utils_test.run_file_transfer, (test, params, env))
        transfer_thread.start()
        try:
            nic_num = len(vm.virtnet)
            up_index = 0
            while transfer_thread.isAlive():
                up_index = up_index % nic_num
                for num in range(nic_num):
                    device_id = vm.virtnet[num].device_id
                    if not device_id:
                        test.error("Could not find peer device for"
                                   " nic device %s" % nic)
                    if num == up_index:
                        vm.set_link(device_id, up=True)
                    else:
                        vm.set_link(device_id, up=False)
                time.sleep(random.randint(1, 5))
                up_index += 1
        except Exception:
            transfer_thread.join(suppress_exception=True)
            raise
        else:
            transfer_thread.join()
    finally:
        session_serial.sendline("ifenslave -d bond0 " + " ".join(ifnames))
        session_serial.sendline("kill -9 `pgrep dhclient`")
        session_serial.sendline("sed -i '$ d' /etc/ssh/sshd_config")
Example #18
0
def run_nic_bonding(test, params, env):
    """
    Nic bonding test in guest.

    1) Start guest with four nic models.
    2) Setup bond0 in guest by script nic_bonding_guest.py.
    3) Execute file transfer test between guest and host.
    4) Repeatedly put down/up interfaces by set_link
    5) Execute file transfer test between guest and host.

    :param test: Kvm test object.
    :param params: Dictionary with the test parameters.
    :param env: Dictionary with test environment.
    """
    def send_cmd_safe(session, cmd, timeout=60):
        logging.debug("Sending command: %s", cmd)
        session.sendline(cmd)
        output = ""
        start_time = time.time()
        # Wait for shell prompt until timeout.
        while (time.time() - start_time) < timeout:
            session.sendline()
            try:
                output += session.read_up_to_prompt(0.5)
                break
            except aexpect.ExpectTimeoutError:
                pass
        return output

    timeout = int(params.get("login_timeout", 1200))
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    session_serial = vm.wait_for_serial_login(timeout=timeout)
    ifnames = [utils_net.get_linux_ifname(session_serial,
                                          vm.get_mac_address(vlan))
               for vlan, nic in enumerate(vm.virtnet)]

    # get params of bonding
    nm_stop_cmd = "pidof NetworkManager && service NetworkManager stop; true"
    send_cmd_safe(session_serial, nm_stop_cmd)
    modprobe_cmd = "modprobe bonding"
    bonding_params = params.get("bonding_params")
    if bonding_params:
        modprobe_cmd += " %s" % bonding_params
    send_cmd_safe(session_serial, modprobe_cmd)
    send_cmd_safe(session_serial, "ifconfig bond0 up")
    setup_cmd = "ifenslave bond0 " + " ".join(ifnames)
    send_cmd_safe(session_serial, setup_cmd)
    # do a pgrep to check if dhclient has already been running
    pgrep_cmd = "pgrep dhclient"
    try:
        send_cmd_safe(session_serial, pgrep_cmd)
    # if dhclient is there, killl it
    except aexpect.ShellCmdError:
        logging.info("it's safe to run dhclient now")
    else:
        logging.info("dhclient already is running,kill it")
        send_cmd_safe(session_serial, "killall -9 dhclient")
        time.sleep(1)

    send_cmd_safe(session_serial, "dhclient bond0")

    #get_bonding_nic_mac and ip
    try:
        logging.info("Test file transferring:")
        utils_test.run_file_transfer(test, params, env)

        logging.info("Failover test with file transfer")
        transfer_thread = utils.InterruptedThread(utils_test.run_file_transfer,
                                                  (test, params, env))
        transfer_thread.start()
        try:
            while transfer_thread.isAlive():
                for vlan, nic in enumerate(vm.virtnet):
                    device_id = nic.device_id
                    if not device_id:
                        raise error.TestError("Could not find peer device for"
                                              " nic device %s" % nic)
                    vm.set_link(device_id, up=False)
                    time.sleep(random.randint(1, 30))
                    vm.set_link(device_id, up=True)
                    time.sleep(random.randint(1, 30))
        except Exception:
            transfer_thread.join(suppress_exception=True)
            raise
        else:
            transfer_thread.join()
    finally:
        session_serial.sendline("ifenslave -d bond0 " + " ".join(ifnames))
        session_serial.sendline("kill -9 `pgrep dhclient`")
Example #19
0
def run_nic_bonding(test, params, env):
    """
    Nic bonding test in guest.

    1) Start guest with four nic models.
    2) Setup bond0 in guest by script nic_bonding_guest.py.
    3) Execute file transfer test between guest and host.
    4) Repeatedly put down/up interfaces by set_link
    5) Execute file transfer test between guest and host.

    @param test: Kvm test object.
    @param params: Dictionary with the test parameters.
    @param env: Dictionary with test environment.
    """
    timeout = int(params.get("login_timeout", 1200))
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    session_serial = vm.wait_for_serial_login(timeout=timeout)

    # get params of bonding
    modprobe_cmd = "modprobe bonding"
    bonding_params = params.get("bonding_params")
    if bonding_params:
        modprobe_cmd += " %s" % bonding_params
    session_serial.cmd(modprobe_cmd)

    session_serial.cmd("ifconfig bond0 up")
    ifnames = [
        utils_net.get_linux_ifname(session_serial, vm.get_mac_address(vlan))
        for vlan, nic in enumerate(vm.virtnet)
    ]
    setup_cmd = "ifenslave bond0 " + " ".join(ifnames)
    session_serial.cmd(setup_cmd)
    #do a pgrep to check if dhclient has already been running
    pgrep_cmd = "pgrep dhclient"
    try:
        session_serial.cmd(pgrep_cmd)
    #if dhclient is there, killl it
    except aexpect.ShellCmdError:
        logging.info("it's safe to run dhclient now")
    else:
        logging.info("dhclient already is running,kill it")
        session_serial.cmd("killall -9 dhclient")
        time.sleep(1)
    session_serial.cmd("dhclient bond0")

    try:
        logging.info("Test file transfering:")
        utils_test.run_file_transfer(test, params, env)

        logging.info("Failover test with file transfer")
        transfer_thread = utils.InterruptedThread(utils_test.run_file_transfer,
                                                  (test, params, env))
        try:
            transfer_thread.start()
            while transfer_thread.isAlive():
                for vlan, nic in enumerate(vm.virtnet):
                    device_id = nic.device_id
                    if not device_id:
                        raise error.TestError("Could not find peer device for"
                                              " nic device %s" % nic)
                    vm.set_link(device_id, up=False)
                    time.sleep(1)
                    vm.set_link(device_id, up=True)
        except Exception:
            transfer_thread.join(suppress_exception=True)
            raise
        else:
            transfer_thread.join()
    finally:
        session_serial.sendline("ifenslave -d bond0 " + " ".join(ifnames))
        session_serial.sendline("kill -9 `pgrep dhclient`")
Example #20
0
def run(test, params, env):
    """
    KVM guest link test:
    1) Boot up guest with one nic
    2) Disable guest link by set_link
    3) Check guest nic operstate and ping host from guest,
       will change queues number at the same time, when using mq
    4) Reboot the guest, then check guest nic operstate and do ping test
    5) Re-enable guest link by set_link
    6) Check guest nic operstate and ping host from guest,
       will change queues number at the same time, when using mq
    7) Reboot the guest, then check guest nic operstate and do ping test
    8) Call utils_test.run_file_transfer function to test file transfer.
       It will do following steps:
       8.1) Create a large file by dd on host.
       8.2) Copy this file from host to guest.
       8.3) Copy this file from guest to host.
       8.4) Check if file transfers ended good.

    :param test: kvm test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """
    def change_queues_number(session, ifname, q_number):
        """
        Change queues number, only used for mq test
        """
        mq_set_cmd = "ethtool -L %s combined %s" % (ifname, q_number)
        try:
            session.cmd_output_safe(mq_set_cmd)
        except aexpect.ShellError as err:
            err_msg = "Change queues number failed"
            err_msg += "Error info: '%s'" % err
            test.fail(err_msg)

    def change_queues_number_repeatly(guest_ifname):
        """
        Change queues repeatedly, only for mq test
        """
        session = vm.wait_for_serial_login()
        try:
            queues = params.get("queues", 1)
            change_list = range(1, int(queues) + 1)
            env["run_change_queues"] = True
            change_queues_number(session, guest_ifname, queues)
            while env["run_change_queues"]:
                for q_number in change_list:
                    change_queues_number(session, guest_ifname, q_number)
        finally:
            if "run_change_queues" in env:
                del env["run_change_queues"]
            session.close()

    def guest_reboot(reboot_method, link_up):
        """
        Reboot guest by different method (shell/system_reset)
        """
        try:
            vm.reboot(method=reboot_method, serial=True, timeout=120)
        except (remote.LoginError, virt_vm.VMAddressError):
            if not link_up:
                logging.info("Login error is expected when net link is down")

    def guest_netwok_connecting_check(guest_ip, link_up, change_queues=False):
        """
        Check whether guest network is connective by ping
        """
        if change_queues:
            env["run_change_queues"] = False
            bg_thread = utils_misc.InterruptedThread(
                change_queues_number_repeatly, (guest_ifname, ))
            bg_thread.start()

            utils_misc.wait_for(lambda: env["run_change_queues"], 30, 0, 2,
                                "wait queues change start")
        time.sleep(0.5)
        output = utils_test.ping(guest_ip,
                                 10,
                                 interface=host_interface,
                                 timeout=20,
                                 session=None)[1]
        if not link_up and utils_test.get_loss_ratio(output) < 80:
            err_msg = "guest network still connecting after down the link"
            test.fail(err_msg)
        elif link_up and utils_test.get_loss_ratio(output) > 20:
            err_msg = "All packets lost during ping guest ip after link up"
            test.fail(err_msg)

        if change_queues:
            env["run_change_queues"] = False
            bg_thread.join()

    def operstate_check(session, expect_status, guest_ifname=""):
        """
        Check Guest interface operstate
        """
        if params.get("os_type") == "linux":
            if_operstate = utils_net.get_net_if_operstate(
                guest_ifname, session.cmd_output_safe)
        else:
            if_operstate = utils_net.get_windows_nic_attribute(
                session, "macaddress", vm.get_mac_address(),
                "netconnectionstatus")

        if if_operstate != expect_status:
            err_msg = "Guest interface %s status error, " % guest_ifname
            err_msg = "currently interface status is '%s', " % if_operstate
            err_msg += "but expect status is '%s'" % expect_status
            test.fail(err_msg)
        logging.info("Guest interface operstate '%s' is exactly as expected" %
                     if_operstate)

    def guest_interface_operstate_check(expect_status,
                                        guest_ifname="",
                                        change_queues=False):
        """
        Check guest interface operstate, support mq
        """
        session = vm.wait_for_serial_login()
        try:
            if change_queues:
                queues = params.get("queues", 1)
                change_list = range(1, int(queues) + 1)
                for q_number in change_list:
                    change_queues_number(session, guest_ifname, q_number)
                    operstate_check(session, expect_status, guest_ifname)
            else:
                operstate_check(session, expect_status, guest_ifname)
        finally:
            session.close()

    def check_interface_ip_routine(session, mac_addr):
        """
        The routine to check the ip of interface.

        :param session: a session to send check commands
        :param mac_addr: the interface mac address
        """
        ip_addr = utils_net.get_net_if_addrs_win(session, mac_addr)
        guest_ipv4 = ip_addr["ipv4"]
        for ip in guest_ipv4:
            logging.debug("Check address: %s" % ip)
            if len(ip) != 0 and not ip.startswith("169.254"):
                return True
        return False

    def check_interface_ip(timeout=600):
        """
        Check whether the vm has got the available ip address.

        The check will be performed repeatedly until a correct ip address
        is detected or after the specified time is expired.

        :param timeout: total checking time allowed
        """
        error_context.context("Start checking guest ip", logging.info)
        session = vm.wait_for_serial_login()
        mac_addr = vm.get_mac_address()
        try:
            if not utils_misc.wait_for(
                    lambda: check_interface_ip_routine(session, mac_addr),
                    timeout,
                    step=5.0):
                err_msg = "Can't get valid ip in %s seconds" % timeout
                test.fail(err_msg)
        finally:
            session.close()

    def set_link_test(linkid,
                      link_up,
                      expect_status,
                      change_queues=False,
                      operstate_always_up=False):
        """
        Issue set_link commands and test its function

        :param linkid: id of netdev or devices to be tested
        :param link_up: flag linkid is up or down
        :param expect_status : expect guest operstate status"
        :param operstate_always_up: when linkid is netdev id, guest interface
                                    operstate will never change,
                                    need set it to True.
        :param change_queues: whether run change mq queues, only effect on
                              linux guest with mq nic.

        """
        vm.set_link(linkid, up=link_up)
        time.sleep(1)
        error_context.context("Check guest interface operstate", logging.info)
        if operstate_always_up:
            if expect_status == "down":
                expect_status = "up"
            if expect_status == win_media_disconnected:
                expect_status = win_media_connected
        guest_interface_operstate_check(expect_status, guest_ifname,
                                        change_queues)
        if params.get("os_type"
                      ) == "windows" and expect_status == win_media_connected:
            check_interface_ip()

        error_context.context("Check if guest network connective",
                              logging.info)
        guest_netwok_connecting_check(guest_ip, link_up, change_queues)

        reboot_method = params.get("reboot_method", "shell")

        error_context.context(
            "Reboot guest by '%s' and recheck interface "
            "operstate" % reboot_method, logging.info)
        guest_reboot(reboot_method, link_up)
        guest_interface_operstate_check(expect_status, guest_ifname,
                                        change_queues)

        error_context.context(
            "Check guest network connecting after reboot "
            "by '%s'" % reboot_method, logging.info)
        guest_netwok_connecting_check(guest_ip, link_up, change_queues)

    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    netdev_id = vm.virtnet[0].netdev_id
    device_id = vm.virtnet[0].device_id
    device_mac = vm.virtnet[0].mac
    host_interface = None
    if vm.virtnet[0].netdst:
        host_interface = vm.virtnet[0].netdst
    os_type = params.get("os_type", "linux")
    login_timeout = float(params.get("login_timeout", 360))
    session = vm.wait_for_login(timeout=login_timeout)

    change_queues = False
    guest_ifname = ""
    guest_ip = utils_net.get_guest_ip_addr(session, device_mac, os_type)
    # Win guest '2' represent 'Connected', '7' represent 'Media disconnected'
    win_media_connected = params.get("win_media_connected", "2")
    win_media_disconnected = params.get("win_media_disconnected", "7")

    if os_type == "linux":
        guest_ifname = utils_net.get_linux_ifname(session,
                                                  vm.get_mac_address())
        queues = int(params.get("queues", 1))
        if queues != 1 and vm.virtnet[0].nic_model == "virtio":
            change_queues = True

    session.close()

    expect_down_status = params.get("down-status", "down")
    expect_up_status = params.get("up-status", "up")
    operstate_always_up = params.get("operstate_always_up", "no") == "yes"

    error_context.context(
        "Disable guest netdev link '%s' by set_link" % netdev_id, logging.info)
    set_link_test(netdev_id, False, expect_down_status, change_queues,
                  operstate_always_up)

    error_context.context(
        "Re-enable guest netdev link '%s' by set_link" % netdev_id,
        logging.info)
    set_link_test(netdev_id, True, expect_up_status, change_queues,
                  operstate_always_up)

    error_context.context(
        "Disable guest nic device '%s' by set_link" % device_id, logging.info)
    set_link_test(device_id, False, expect_down_status, change_queues)

    error_context.context(
        "Re-enable guest nic device '%s' by set_link" % device_id,
        logging.info)
    set_link_test(device_id, True, expect_up_status, change_queues)

    error_context.context("Do file transfer after setlink on and off",
                          logging.info)
    utils_test.run_file_transfer(test, params, env)
Example #21
0
            change_queues = True

    session.close()

    netdev_id = vm.virtnet[0].netdev_id
    device_id = vm.virtnet[0].device_id
    expect_down_status = params.get("down-status", "down")
    expect_up_status = params.get("up-status", "up")
    operstate_always_up = params.get("operstate_always_up", "no") == "yes"

    error.context("Disable guest netdev link '%s' by set_link" % netdev_id,
                  logging.info)
    set_link_test(netdev_id, False, expect_down_status, operstate_always_up,
                  change_queues)

    error.context("Re-enable guest netdev link '%s' by set_link" % netdev_id,
                  logging.info)
    set_link_test(netdev_id, True, expect_up_status, operstate_always_up,
                  change_queues)

    error.context("Disable guest nic device '%s' by set_link" % device_id,
                  logging.info)
    set_link_test(device_id, False, expect_down_status, False, change_queues)

    error.context("Re-enable guest nic device '%s' by set_link" % device_id,
                  logging.info)
    set_link_test(device_id, True, expect_up_status, False, change_queues)

    error.context("Do file transfer after setlink on and off", logging.info)
    utils_test.run_file_transfer(test, params, env)
Example #22
0
def run(test, params, env):
    """
    Change MAC address of guest.

    1) Get a new mac from pool, and the old mac addr of guest.
    2) Check guest mac by qmp command.
    3) Set new mac in guest and regain new IP.
    4) Check guest new mac by qmp command.
    5) Re-log into guest with new MAC. (nettype != macvtap)
    6) Reboot guest and check the the mac address by monitor(optional).
    7) File transfer between host and guest. optional

    :param test: QEMU test object.
    :param params: Dictionary with the test parameters.
    :param env: Dictionary with test environment.
    """
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    timeout = int(params.get("login_timeout", 360))
    session_serial = vm.wait_for_serial_login(timeout=timeout)
    # This session will be used to assess whether the IP change worked
    if params.get("nettype") != "macvtap":
        session = vm.wait_for_login(timeout=timeout)
    old_mac = vm.get_mac_address(0)
    while True:
        vm.virtnet.free_mac_address(0)
        new_mac = vm.virtnet.generate_mac_address(0)
        if old_mac != new_mac:
            break

    os_type = params.get("os_type")
    os_variant = params.get("os_variant")
    change_cmd_pattern = params.get("change_cmd")
    logging.info("The initial MAC address is %s", old_mac)
    check_guest_mac(old_mac, vm)
    if os_type == "linux":
        interface = utils_net.get_linux_ifname(session_serial, old_mac)
        if params.get("shutdown_int", "yes") == "yes":
            int_shutdown_cmd = params.get("int_shutdown_cmd",
                                          "ifconfig %s down")
            session_serial.cmd(int_shutdown_cmd % interface)
    else:

        connection_id = utils_net.get_windows_nic_attribute(session_serial,
                                                            "macaddress",
                                                            old_mac,
                                                            "netconnectionid")
        nic_index = utils_net.get_windows_nic_attribute(session_serial,
                                                        "netconnectionid",
                                                        connection_id,
                                                        "index")
        if os_variant == "winxp":
            pnpdevice_id = utils_net.get_windows_nic_attribute(session,
                                                               "netconnectionid",
                                                               connection_id,
                                                               "pnpdeviceid")
            cd_drive = utils_misc.get_winutils_vol(session)
            copy_cmd = r"xcopy %s:\devcon\wxp_x86\devcon.exe c:\ " % cd_drive
            session.cmd(copy_cmd)

    # Start change MAC address
    error.context("Changing MAC address to %s" % new_mac, logging.info)
    if os_type == "linux":
        change_cmd = change_cmd_pattern % (interface, new_mac)
    else:
        change_cmd = change_cmd_pattern % (int(nic_index),
                                           "".join(new_mac.split(":")))
    try:
        session_serial.cmd(change_cmd)

        # Verify whether MAC address was changed to the new one
        error.context("Verify the new mac address, and restart the network",
                      logging.info)
        if os_type == "linux":
            if params.get("shutdown_int", "yes") == "yes":
                int_activate_cmd = params.get("int_activate_cmd",
                                              "ifconfig %s up")
                session_serial.cmd(int_activate_cmd % interface)
            session_serial.cmd("ifconfig | grep -i %s" % new_mac)
            logging.info("Mac address change successfully, net restart...")
            dhclient_cmd = "dhclient -r && dhclient %s" % interface
            session_serial.sendline(dhclient_cmd)
        else:
            mode = "netsh"
            if os_variant == "winxp":
                connection_id = pnpdevice_id.split("&")[-1]
                mode = "devcon"
            utils_net.restart_windows_guest_network(session_serial,
                                                    connection_id,
                                                    mode=mode)

            o = session_serial.cmd("ipconfig /all")
            if not re.findall("%s" % "-".join(new_mac.split(":")), o, re.I):
                raise error.TestFail("Guest mac change failed")
            logging.info("Guest mac have been modified successfully")

        if params.get("nettype") != "macvtap":
            # Re-log into the guest after changing mac address
            if utils_misc.wait_for(session.is_responsive, 120, 20, 3):
                # Just warning when failed to see the session become dead,
                # because there is a little chance the ip does not change.
                msg = "The session is still responsive, settings may fail."
                logging.warn(msg)
            session.close()

            # Re-log into guest and check if session is responsive
            error.context("Re-log into the guest", logging.info)
            session = vm.wait_for_login(timeout=timeout)
            if not session.is_responsive():
                raise error.TestFail("The new session is not responsive.")
            if params.get("reboot_vm_after_mac_changed") == "yes":
                error.context("Reboot guest and check the the mac address by "
                              "monitor", logging.info)
                mac_check = new_mac
                if os_type == "linux":
                    nic = vm.virtnet[0]
                    nic.mac = old_mac
                    vm.virtnet.update_db()
                    mac_check = old_mac

                session_serial = vm.reboot(session_serial, serial=True)
                check_guest_mac(mac_check, vm)
            if params.get("file_transfer", "no") == "yes":
                error.context("File transfer between host and guest.",
                              logging.info)
                utils_test.run_file_transfer(test, params, env)
        else:
            check_guest_mac(new_mac, vm)
    finally:
        if os_type == "windows":
            clean_cmd_pattern = params.get("clean_cmd")
            clean_cmd = clean_cmd_pattern % int(nic_index)
            session_serial.cmd(clean_cmd)
            utils_net.restart_windows_guest_network(session_serial,
                                                    connection_id,
                                                    mode=mode)
            nic = vm.virtnet[0]
            nic.mac = old_mac
            vm.virtnet.update_db()
Example #23
0
                                                  vm.get_mac_address())
        queues = int(params.get("queues", 1))
        if queues != 1 and vm.virtnet[0].nic_model == "virtio":
            change_queues = True

    session.close()

    netdev_id = vm.virtnet[0].netdev_id
    device_id = vm.virtnet[0].device_id
    expect_down_status = params.get("down-status", "down")
    expect_up_status = params.get("up-status", "up")

    error.context("Disable guest netdev link '%s' by set_link" % netdev_id,
                  logging.info)
    set_link_test(netdev_id, False, expect_down_status, True, change_queues)

    error.context("Re-enable guest netdev link '%s' by set_link" % netdev_id,
                  logging.info)
    set_link_test(netdev_id, True, expect_up_status, True, change_queues)

    error.context("Disable guest nic device '%s' by set_link" % device_id,
                  logging.info)
    set_link_test(device_id, False, expect_down_status, False, change_queues)

    error.context("Re-enable guest nic device '%s' by set_link" % device_id,
                  logging.info)
    set_link_test(device_id, True, expect_up_status, False, change_queues)

    error.context("Do file transfer after setlink on and off", logging.info)
    utils_test.run_file_transfer(test, params, env)
Example #24
0
def run(test, params, env):
    """
    Change MAC address of guest.

    1) Get a new mac from pool, and the old mac addr of guest.
    2) Set new mac in guest and regain new IP.
    3) Re-log into guest with new MAC.
    4) File transfer between host and guest. optional

    :param test: QEMU test object.
    :param params: Dictionary with the test parameters.
    :param env: Dictionary with test environment.
    """
    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    timeout = int(params.get("login_timeout", 360))
    session_serial = vm.wait_for_serial_login(timeout=timeout)
    # This session will be used to assess whether the IP change worked
    session = vm.wait_for_login(timeout=timeout)
    old_mac = vm.get_mac_address(0)
    while True:
        vm.virtnet.free_mac_address(0)
        new_mac = vm.virtnet.generate_mac_address(0)
        if old_mac != new_mac:
            break

    os_type = params.get("os_type")
    os_variant = params.get("os_variant")
    change_cmd_pattern = params.get("change_cmd")

    logging.info("The initial MAC address is %s", old_mac)
    if os_type == "linux":
        interface = utils_net.get_linux_ifname(session_serial, old_mac)
        if params.get("shutdown_int", "yes") == "yes":
            int_shutdown_cmd = params.get("int_shutdown_cmd",
                                          "ifconfig %s down")
            session_serial.cmd(int_shutdown_cmd % interface)
    else:

        connection_id = utils_net.get_windows_nic_attribute(
            session, "macaddress", old_mac, "netconnectionid")
        nic_index = utils_net.get_windows_nic_attribute(
            session, "netconnectionid", connection_id, "index")
        if os_variant == "winxp":
            pnpdevice_id = utils_net.get_windows_nic_attribute(
                session, "netconnectionid", connection_id, "pnpdeviceid")
            cd_drive = utils_misc.get_winutils_vol(session)
            copy_cmd = r"xcopy %s:\devcon\wxp_x86\devcon.exe c:\ " % cd_drive
            session.cmd(copy_cmd)

    # Start change MAC address
    error.context("Changing MAC address to %s" % new_mac, logging.info)
    if os_type == "linux":
        change_cmd = change_cmd_pattern % (interface, new_mac)
    else:
        change_cmd = change_cmd_pattern % (int(nic_index), "".join(
            new_mac.split(":")))
    try:
        session_serial.cmd(change_cmd)

        # Verify whether MAC address was changed to the new one
        error.context("Verify the new mac address, and restart the network",
                      logging.info)
        if os_type == "linux":
            if params.get("shutdown_int", "yes") == "yes":
                int_activate_cmd = params.get("int_activate_cmd",
                                              "ifconfig %s up")
                session_serial.cmd(int_activate_cmd % interface)
            session_serial.cmd("ifconfig | grep -i %s" % new_mac)
            logging.info("Mac address change successfully, net restart...")
            dhclient_cmd = "dhclient -r && dhclient %s" % interface
            session_serial.sendline(dhclient_cmd)
        else:
            mode = "netsh"
            if os_variant == "winxp":
                connection_id = pnpdevice_id.split("&")[-1]
                mode = "devcon"
            utils_net.restart_windows_guest_network(session_serial,
                                                    connection_id,
                                                    mode=mode)

            o = session_serial.cmd("ipconfig /all")
            if not re.findall("%s" % "-".join(new_mac.split(":")), o, re.I):
                raise error.TestFail("Guest mac change failed")
            logging.info("Guest mac have been modified successfully")

        # Re-log into the guest after changing mac address
        if utils_misc.wait_for(session.is_responsive, 120, 20, 3):
            # Just warning when failed to see the session become dead,
            # because there is a little chance the ip does not change.
            logging.warn("The session is still responsive, settings may fail.")
        session.close()

        # Re-log into guest and check if session is responsive
        error.context("Re-log into the guest", logging.info)
        session = vm.wait_for_login(timeout=timeout)
        if not session.is_responsive():
            raise error.TestFail("The new session is not responsive.")
        if params.get("file_transfer", "no") == "yes":
            error.context("File transfer between host and guest.",
                          logging.info)
            utils_test.run_file_transfer(test, params, env)
    finally:
        if os_type == "windows":
            clean_cmd_pattern = params.get("clean_cmd")
            clean_cmd = clean_cmd_pattern % int(nic_index)
            session_serial.cmd(clean_cmd)
            utils_net.restart_windows_guest_network(session_serial,
                                                    connection_id,
                                                    mode=mode)
            nic = vm.virtnet[0]
            nic.mac = old_mac
            vm.virtnet.update_db()
        session.close()
Example #25
0
def run(test, params, env):
    """
    Boot guest with different vectors, then do file transfer tests.

    1) Boot up VM with certain vectors.
    2) Check guest msi & queues info
    3) Start 10 scp file transfer tests

    :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))
    cmd_timeout = int(params.get("cmd_timeout", 240))

    # boot the vm with the queues
    queues = int(params["queues"])
    error_context.context("Boot the guest with queues = %s" % queues,
                          logging.info)

    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    session = vm.wait_for_login(timeout=login_timeout)

    # enable multi-queues for linux guest
    if params["os_type"] == "linux":
        nic = vm.virtnet[0]
        ifname = utils_net.get_linux_ifname(session, nic.mac)
        set_queue_cmd = "ethtool -L %s combined %s" % (ifname, queues)
        status, output = session.cmd_status_output(set_queue_cmd,
                                                   timeout=cmd_timeout,
                                                   safe=True)
        if status:
            err = "Failed to set queues to %s with status = %s and output= %s"
            err %= (queues, status, output)
            test.fail(err)
        check_queue_cmd = "ethtool -l %s" % ifname
        output = session.cmd_output(check_queue_cmd, timeout=cmd_timeout)
        if len(re.findall(r"Combined:\s+%d\s" % queues, output)) != 2:
            test.fail("Fail to set queues to %s on %s" %
                      (queues, nic.nic_name))

        # check the msi for linux guest
        error_context.context("Check the msi number in guest", logging.info)
        devices = session.cmd_output("lspci | grep Ethernet",
                                     timeout=cmd_timeout, safe=True).strip()
        for device in devices.split("\n"):
            if not device:
                continue
            d_id = device.split()[0]
            msi_check_cmd = params["msi_check_cmd"] % d_id
            status, output = session.cmd_status_output(msi_check_cmd,
                                                       timeout=cmd_timeout,
                                                       safe=True)
            find_result = re.search(r"MSI-X: Enable\+\s+Count=(\d+)", output)
            if not find_result:
                test.fail("No MSI info in output: %s" % output)
            msis = int(find_result.group(1))
            if msis != 2 * queues + 2:
                test.fail("MSI not correct with output: %s" % output)
    else:
        # verify driver
        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,
                                                                cmd_timeout)
        # check the msi for windows guest with trace view
        error_context.context("Check the msi number in guest", logging.info)
        msis, cur_queues = utils_net.get_msis_and_queues_windows(params,
                                                                 vm)
        if cur_queues != queues or msis != 2 * queues + 2:
            test.fail("queues not correct with %s, expect %s" %
                      (cur_queues, queues))

    # start scp test
    error_context.context("Start scp file transfer test", logging.info)
    scp_count = int(params.get("scp_count", 10))
    for i in range(scp_count):
        utils_test.run_file_transfer(test, params, env)
    if session:
        session.close()
Example #26
0
def run_set_link(test, params, env):
    """
    KVM guest link test:
    1) Boot up guest with one nic
    2) Disable guest link by set_link
    3) Check guest nic operstate, and ping guest from host
    4) Reboot the guest, then check guest nic operstate and do ping test
    5) Re-enable guest link by set_link
    6) Check guest nic operstate and ping guest from host
    7) Reboot the guest, then check guest nic operstate and do ping test
    8) Call utils_test.run_file_transfer function to test file transfer.
       It will do following steps:
       8.1) Create a large file by dd on host.
       8.2) Copy this file from host to guest.
       8.3) Copy this file from guest to host.
       8.4) Check if file transfers ended good.

    :param test: kvm test object
    :param params: Dictionary with the test parameters
    :param env: Dictionary with test environment.
    """
    vm = env.get_vm(params["main_vm"])
    timeout = float(params.get("login_timeout", 360))
    # Waiting for guest boot up.
    session = vm.wait_for_login(timeout=timeout)
    os_type = params.get("os_type")
    if os_type == "linux":
        guest_ifname = utils_net.get_linux_ifname(session,
                                                  vm.get_mac_address())
    else:
        guest_ifname = ""

    guest_ip = vm.get_address()
    session.close()

    # Windows guest '2' represent 'Connected',
    # '7' represent 'Media disconnected'
    win_media_connected = params.get("win_media_connected", "2")
    win_media_disconnected = params.get("win_media_disconnected", "7")

    def guest_reboot(reboot_method, link_up):
        """
        Reboot guest by different method (shell/system_reset)
        """
        try:
            vm.reboot(method=reboot_method, timeout=120)
        except remote.LoginError:
            if not link_up:
                logging.info("Login error is expected when net link is down")

    def guest_netwok_connecting_check(guest_ip, link_up):
        """
        Check whether guest network is connective by ping
        """
        if link_up:
            vm.wait_for_login()
            guest_ip = vm.get_address()
        s, o = utils_test.ping(guest_ip, count=10, timeout=20)
        if not link_up and utils_test.get_loss_ratio(o) != 100:
            err_msg = "guest network still connecting after down the link"
            raise error.TestFail(err_msg)
        elif link_up and utils_test.get_loss_ratio(o) == 100:
            err_msg = "All packets lost during ping guest ip after link up"
            raise error.TestFail(err_msg)
        else:
            logging.info("Guest network connecting is exactly as expected")

    def guest_interface_operstate_check(expect_status, guest_ifname=""):
        """
        Check Guest interface operstate
        """
        session = vm.wait_for_serial_login()

        os_type = params.get("os_type")
        if os_type == "linux":
            if_operstate = utils_net.get_net_if_operstate(guest_ifname,
                                                          session.cmd)
        else:
            if_operstate = utils_net.get_windows_nic_attribute(session,
                                                               "macaddress", vm.get_mac_address(), "netconnectionstatus")
        session.close()

        if if_operstate != expect_status:
            err_msg = "Guest interface %s status error, " % guest_ifname
            err_msg = "currently interface status is '%s', " % if_operstate
            err_msg += "but expect status is '%s'" % expect_status
            raise error.TestError(err_msg)
        logging.info("Guest interface operstate '%s' is exactly as expected" %
                     if_operstate)

    def set_link_test(linkid, link_up, expect_status,
                      operstate_always_up=False):
        """
        Issue set_link commands and test its function

        :param linkid: id of netdev or devices to be tested
        :param link_up: flag linkid is up or down
        :param expect_status : expect guest operstate status"
        :param operstate_always_up: when linkid is netdev id, guest interface
                                    operstate will never change,
                                    need set it to True.

        """
        vm.set_link(linkid, up=link_up)
        error.context("Check guest interface operstate", logging.info)
        if operstate_always_up:
            if expect_status == "down":
                expect_status = "up"
            if expect_status == win_media_disconnected:
                expect_status = win_media_connected
        guest_interface_operstate_check(expect_status, guest_ifname)

        error.context("Check if guest network connective", logging.info)
        guest_netwok_connecting_check(guest_ip, link_up)

        reboot_method = params.get("reboot_method", "shell")
        error.context("Reboot guest by '%s' and recheck interface operstate" %
                      reboot_method, logging.info)
        guest_reboot(reboot_method, link_up)
        guest_interface_operstate_check(expect_status, guest_ifname)

        error.context("Check guest network connecting after reboot by '%s'" %
                      reboot_method, logging.info)
        guest_netwok_connecting_check(guest_ip, link_up)

    netdev_id = vm.virtnet[0].netdev_id
    device_id = vm.virtnet[0].device_id
    expect_down_status = params.get("down-status", "down")
    expect_up_status = params.get("up-status", "up")

    error.context("Disable guest netdev link '%s' by set_link" % netdev_id,
                  logging.info)
    set_link_test(netdev_id, False, expect_down_status, True)

    error.context("Re-enable guest netdev link '%s' by set_link" % netdev_id,
                  logging.info)
    set_link_test(netdev_id, True, expect_up_status, True)

    error.context("Disable guest nic device '%s' by set_link" % device_id,
                  logging.info)
    set_link_test(device_id, False, expect_down_status)

    error.context("Re-enable guest nic device '%s' by set_link" % device_id,
                  logging.info)
    set_link_test(device_id, True, expect_up_status)

    error.context("Do file transfer after setlink on and off", logging.info)
    utils_test.run_file_transfer(test, params, env)