当前位置: 首页>>代码示例>>Python>>正文


Python utils_net.get_ip_address_by_interface函数代码示例

本文整理汇总了Python中virttest.utils_net.get_ip_address_by_interface函数的典型用法代码示例。如果您正苦于以下问题:Python get_ip_address_by_interface函数的具体用法?Python get_ip_address_by_interface怎么用?Python get_ip_address_by_interface使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get_ip_address_by_interface函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run_multi_vms_nics


#.........这里部分代码省略.........
            if status != 0:
                raise error.TestFail("Ping returns non-zero value %s" %
                                     output)

    def file_transfer(session, src, dst):
        username = params.get("username", "")
        password = params.get("password", "")
        src_path = "/tmp/1"
        dst_path = "/tmp/2"
        port = int(params["file_transfer_port"])

        cmd = "dd if=/dev/urandom of=%s bs=100M count=1" % src_path
        cmd = params.get("file_create_cmd", cmd)

        error.context("Create file by dd command, cmd: %s" % cmd, logging.info)
        session.cmd(cmd)

        transfer_timeout = int(params.get("transfer_timeout"))
        log_filename = "scp-from-%s-to-%s.log" % (src, dst)
        error.context("Transfer file from %s to %s" % (src, dst), logging.info)
        remote.scp_between_remotes(src, dst, port, password, password,
                                   username, username, src_path, dst_path,
                                   log_filename=log_filename,
                                   timeout=transfer_timeout)
        src_path = dst_path
        dst_path = "/tmp/3"
        log_filename = "scp-from-%s-to-%s.log" % (dst, src)
        error.context("Transfer file from %s to %s" % (dst, src), logging.info)
        remote.scp_between_remotes(dst, src, port, password, password,
                                   username, username, src_path, dst_path,
                                   log_filename=log_filename,
                                   timeout=transfer_timeout)
        error.context("Compare original file and transferred file",
                      logging.info)

        cmd1 = "md5sum /tmp/1"
        cmd2 = "md5sum /tmp/3"
        md5sum1 = session.cmd(cmd1).split()[0]
        md5sum2 = session.cmd(cmd2).split()[0]
        if md5sum1 != md5sum2:
            raise error.TestError("File changed after transfer")

    vm_list = []
    session_list = []
    vms = params["vms"].split()
    timeout = float(params.get("login_timeout", 360))
    mac_ip_filter = params["mac_ip_filter"]
    strict_check = params.get("strick_check", "no")
    host_ip = utils_net.get_ip_address_by_interface(params.get("netdst"))
    host_ip = params.get("srchost", host_ip)
    flood_minutes = float(params["flood_minutes"])
    for vm_name in vms:
        vm = env.get_vm(vm_name)
        vm_list.append(vm)
        session_list.append(vm.wait_for_login(timeout=timeout))

    ip_list = []

    error.context("Check all the nics available or not", logging.info)
    count_nics = len(params.get("nics").split())
    for i in session_list:
        ips = []
        cmd = params.get("net_check_cmd")
        end_time = time.time() + timeout
        while time.time() < end_time:
            status, output = i.get_command_status_output(cmd)
            if status:
                err_msg = "Can not get ip from guest."
                err_msg += " Cmd '%s' fail with output: %s" % (cmd, output)
                logging.error(err_msg)
            ips = re.findall(mac_ip_filter, output, re.S)
            if count_nics == len(ips):
                break
            time.sleep(2)
        else:
            err_log = "Not all nics get ip.  Set '%s' nics." % count_nics
            err_log += " Guest only get '%s' ip(s). " % len(ips)
            err_log += " Command '%s' output in guest:\n%s" % (cmd, output)
            raise error.TestFail(err_log)
        for ip in ips:
            ip_list.append(ip + (i,))
    ip_list_len = len(ip_list)
    # ping and file transfer test
    for src_ip_index in range(ip_list_len):
        error.context("Ping test from guest to host", logging.info)
        src_ip_info = ip_list[src_ip_index]
        ping(src_ip_info[3], src_ip_info[0], host_ip, strict_check,
             flood_minutes)
        error.context("File transfer test between guest and host",
                      logging.info)
        file_transfer(src_ip_info[3], src_ip_info[2], host_ip)
        for dst_ip in ip_list[src_ip_index:]:
            txt = "Ping test between %s and %s" % (src_ip_info[2], dst_ip[2])
            error.context(txt, logging.info)
            ping(src_ip_info[3], src_ip_info[0], dst_ip[2], strict_check,
                 flood_minutes)
            txt = "File transfer test between %s " % src_ip_info[2]
            txt += "and %s" % dst_ip[2]
            error.context(txt, logging.info)
            file_transfer(src_ip_info[3], src_ip_info[2], dst_ip[2])
开发者ID:Antique,项目名称:virt-test,代码行数:101,代码来源:multi_vms_nics.py

示例2: __init__

    def __init__(self, test, params, vm):
        """
        Sets class attributes from test parameters.

        :param test: QEMU test object.
        :param params: Dictionary with test parameters.
        """
        root_dir = data_dir.get_data_dir()
        self.deps_dir = os.path.join(test.virtdir, 'deps')
        self.unattended_dir = os.path.join(test.virtdir, 'unattended')
        self.results_dir = test.debugdir
        self.params = params

        self.attributes = ['kernel_args', 'finish_program', 'cdrom_cd1',
                           'unattended_file', 'medium', 'url', 'kernel',
                           'initrd', 'nfs_server', 'nfs_dir', 'install_virtio',
                           'floppy_name', 'cdrom_unattended', 'boot_path',
                           'kernel_params', 'extra_params', 'qemu_img_binary',
                           'cdkey', 'finish_program', 'vm_type',
                           'process_check', 'vfd_size', 'cdrom_mount_point',
                           'floppy_mount_point', 'cdrom_virtio',
                           'virtio_floppy', 're_driver_match',
                           're_hardware_id', 'driver_in_floppy']

        for a in self.attributes:
            setattr(self, a, params.get(a, ''))

        # Will setup the virtio attributes
        v_attributes = ['virtio_floppy', 'virtio_scsi_path', 'virtio_storage_path',
                        'virtio_network_path', 'virtio_oemsetup_id',
                        'virtio_network_installer_path',
                        'virtio_balloon_installer_path',
                        'virtio_qxl_installer_path']

        for va in v_attributes:
            setattr(self, va, params.get(va, ''))

        self.tmpdir = test.tmpdir
        self.qemu_img_binary = utils_misc.get_qemu_img_binary(params)

        if getattr(self, 'unattended_file'):
            self.unattended_file = os.path.join(test.virtdir,
                                                self.unattended_file)

        if getattr(self, 'finish_program'):
            self.finish_program = os.path.join(test.virtdir,
                                               self.finish_program)

        if getattr(self, 'cdrom_cd1'):
            self.cdrom_cd1 = os.path.join(root_dir, self.cdrom_cd1)
        self.cdrom_cd1_mount = tempfile.mkdtemp(prefix='cdrom_cd1_',
                                                dir=self.tmpdir)
        if getattr(self, 'cdrom_unattended'):
            self.cdrom_unattended = os.path.join(root_dir,
                                                 self.cdrom_unattended)

        if getattr(self, 'virtio_floppy'):
            self.virtio_floppy = os.path.join(root_dir, self.virtio_floppy)

        if getattr(self, 'cdrom_virtio'):
            self.cdrom_virtio = os.path.join(root_dir, self.cdrom_virtio)

        if getattr(self, 'kernel'):
            self.kernel = os.path.join(root_dir, self.kernel)
        if getattr(self, 'initrd'):
            self.initrd = os.path.join(root_dir, self.initrd)

        if self.medium == 'nfs':
            self.nfs_mount = tempfile.mkdtemp(prefix='nfs_',
                                              dir=self.tmpdir)

        setattr(self, 'floppy', self.floppy_name)
        if getattr(self, 'floppy'):
            self.floppy = os.path.join(root_dir, self.floppy)
            if not os.path.isdir(os.path.dirname(self.floppy)):
                os.makedirs(os.path.dirname(self.floppy))

        self.image_path = os.path.dirname(self.kernel)

        # Content server params
        # lookup host ip address for first nic by interface name
        try:
            auto_ip = utils_net.get_ip_address_by_interface(
                vm.virtnet[0].netdst)
        except utils_net.NetError:
            auto_ip = None

        self.url_auto_content_ip = params.get('url_auto_ip', auto_ip)
        self.url_auto_content_port = None

        # Kickstart server params
        # use the same IP as url_auto_content_ip, but a different port
        self.unattended_server_port = None

        # Embedded Syslog Server
        self.syslog_server_enabled = params.get('syslog_server_enabled', 'no')
        self.syslog_server_ip = params.get('syslog_server_ip', auto_ip)
        self.syslog_server_port = int(params.get('syslog_server_port', 5140))
        self.syslog_server_tcp = params.get('syslog_server_proto',
                                            'tcp') == 'tcp'
#.........这里部分代码省略.........
开发者ID:aginies,项目名称:virt-test,代码行数:101,代码来源:unattended_install.py

示例3: run

def run(test, params, env):
    """
    Test virsh iface-bridge and iface-unbridge commands.

    (1) Bridge an existing network device(iface-bridge).
    (2) Unbridge a network device(iface-unbridge).
    """

    iface_name = params.get("iface_name")
    bridge_name = params.get("bridge_name")
    ping_ip = params.get("ping_ip", "")
    ping_count = int(params.get("ping_count", "3"))
    ping_timeout = int(params.get("ping_timeout", "5"))
    bridge_option = params.get("bridge_option")
    unbridge_option = params.get("unbridge_option")
    bridge_delay = "yes" == params.get("bridge_delay", "no")
    delay_num = params.get("delay_num", "0")
    create_bridge = "yes" == params.get("create_bridge", "yes")
    bridge_status_error = "yes" == params.get("bridge_status_error", "no")
    unbridge_status_error = "yes" == params.get("unbridge_status_error", "no")
    iface_script = NETWORK_SCRIPT + iface_name
    iface_script_bk = os.path.join(test.tmpdir, "iface-%s.bk" % iface_name)
    check_iface = "yes" == params.get("check_iface", "yes")
    if check_iface:
        # Make sure the interface exists
        if not libvirt.check_iface(iface_name, "exists", "--all"):
            raise error.TestNAError("Interface '%s' not exists" % iface_name)

        net_iface = utils_net.Interface(name=iface_name)
        iface_is_up = net_iface.is_up()
        iface_ip = net_iface.get_ip()

        # Back up the interface script
        utils.run("cp %s %s" % (iface_script, iface_script_bk))

    # Make sure the bridge name not exists
    net_bridge = utils_net.Bridge()
    if bridge_name in net_bridge.list_br():
        raise error.TestNAError("Bridge '%s' already exists" % bridge_name)

    # Stop NetworkManager service
    try:
        NM = utils_path.find_command("NetworkManager")
    except utils_path.CmdNotFoundError:
        logging.debug("No NetworkManager service.")
        NM = None
    NM_is_running = False
    if NM is not None:
        NM_service = service.Factory.create_service("NetworkManager")
        NM_is_running = NM_service.status()
        if NM_is_running:
            NM_service.stop()

    def unbridge_check():
        """
        Check the result after do unbridge.
        """
        list_option = "--all"
        if libvirt.check_iface(bridge_name, "exists", list_option):
            raise error.TestFail("%s is still present." % bridge_name)
        if "no-start" in unbridge_option:
            list_option = "--inactive"
        if not libvirt.check_iface(iface_name, "exists", list_option):
            raise error.TestFail("%s is not present." % iface_name)

    if bridge_delay:
        bridge_option += " --delay %s" % delay_num
    # Run test
    try:
        if create_bridge:
            # Create bridge
            result = virsh.iface_bridge(iface_name, bridge_name, bridge_option)
            libvirt.check_exit_status(result, bridge_status_error)
            if not bridge_status_error:
                # Get the new create bridge IP address
                try:
                    br_ip = utils_net.get_ip_address_by_interface(bridge_name)
                except:
                    br_ip = ""
                # check IP of new bridge
                if check_iface and br_ip and br_ip != iface_ip:
                    raise error.Testfail("bridge IP(%s) isn't the same as iface IP(%s)."
                                         % (br_ip, iface_ip))
                # check the status of STP feature
                if "no-start" not in bridge_option:
                    if "no-stp" not in bridge_option:
                        if "yes" != net_bridge.get_stp_status(bridge_name):
                            raise error.Testfail("Fail to enable STP.")
                # Do ping test only bridge has IP address and ping_ip not empty
                if br_ip and ping_ip:
                    if not libvirt.check_iface(bridge_name, "ping", ping_ip,
                                               count=ping_count, timeout=ping_timeout):
                        raise error.TestFail("Fail to ping %s from %s."
                                             % (ping_ip, bridge_name))
                else:
                    # Skip ping test
                    logging.debug("Skip ping test as %s has no IP address",
                                  bridge_name)
                list_option = ""
                if "no-start" in bridge_option:
#.........这里部分代码省略.........
开发者ID:CongLi,项目名称:tp-libvirt,代码行数:101,代码来源:virsh_iface_bridge.py

示例4: kdump_enable

def kdump_enable(vm, vm_name, crash_kernel_prob_cmd,
                 kernel_param_cmd, kdump_enable_cmd, timeout):
    """
    Check, configure and enable the kdump in guest.

    :param vm_name: vm name
    :param crash_kernel_prob_cmd: check kdume loaded
    :param kernel_param_cmd: the param add into kernel line for kdump
    :param kdump_enable_cmd: enable kdump command
    :param timeout: Timeout in seconds
    """
    kdump_cfg_path = vm.params.get("kdump_cfg_path", "/etc/kdump.conf")
    kdump_config = vm.params.get("kdump_config")
    vmcore_path = vm.params.get("vmcore_path", "/var/crash")
    kdump_method = vm.params.get("kdump_method", "basic")
    kdump_propagate_cmd = vm.params.get("kdump_propagate_cmd")

    error.context("Try to log into guest '%s'." % vm_name, logging.info)
    session = vm.wait_for_login(timeout=timeout)

    error.context("Checking the existence of crash kernel in %s" %
                  vm_name, logging.info)
    try:
        session.cmd(crash_kernel_prob_cmd)
    except Exception:
        error.context("Crash kernel is not loaded. Trying to load it",
                      logging.info)
        session.cmd(kernel_param_cmd)
        session = vm.reboot(session, timeout=timeout)

    if kdump_config:
        if kdump_method == "ssh":
            host_ip = utils_net.get_ip_address_by_interface(vm.params.get('netdst'))
            kdump_config = kdump_config % (host_ip, vmcore_path)

        error.context("Configuring the Core Collector...", logging.info)

        session.cmd("cat /dev/null > %s" % kdump_cfg_path)
        for config_line in kdump_config.split(";"):
            config_cmd = "echo -e '%s' >> %s "
            config_con = config_line.strip()
            session.cmd(config_cmd % (config_con, kdump_cfg_path))

    if kdump_method == "ssh":
        host_pwd = vm.params.get("host_pwd", "redhat")
        guest_pwd = vm.params.get("guest_pwd", "redhat")
        guest_ip = vm.get_address()

        error.context("Setup ssh login without password...", logging.info)
        session.cmd("rm -rf /root/.ssh/*")

        ssh_connection = utils_conn.SSHConnection(server_ip=host_ip,
                                                  server_pwd=host_pwd,
                                                  client_ip=guest_ip,
                                                  client_pwd=guest_pwd)
        try:
            ssh_connection.conn_check()
        except utils_conn.ConnectionError:
            ssh_connection.conn_setup()
            ssh_connection.conn_check()

        logging.info("Trying to propagate with command '%s'" %
                     kdump_propagate_cmd)
        session.cmd(kdump_propagate_cmd, timeout=120)

    error.context("Enabling kdump service...", logging.info)
    # the initrd may be rebuilt here so we need to wait a little more
    session.cmd(kdump_enable_cmd, timeout=120)

    return session
开发者ID:arges,项目名称:tp-qemu,代码行数:70,代码来源:kdump.py

示例5: run


#.........这里部分代码省略.........
            ethname_dict.append(ethname)
            # TODO:cleanup of the network scripts
            try:
                utils_net.create_network_script(ethname, mac, "dhcp",
                                                "255.255.255.0", on_boot="yes")
            except Exception as info:
                test.error("Network script creation failed - %s" % info)

        msg = "Check whether VFs could get ip in host."
        error_context.context(msg, logging.info)
        for ethname in ethname_dict:
            utils_net.bring_down_ifname(ethname)
            _ip = check_network_interface_ip(ethname)
            if not _ip:
                msg = "Interface '%s' could not get IP." % ethname
                logging.error(msg)
            else:
                ips[ethname] = _ip
                logging.info("Interface '%s' get IP '%s'", ethname, _ip)

    for i in range(repeat_time):
        msg = "Bind/unbind device from host. Repeat %s/%s" % (i + 1,
                                                              repeat_time)
        error_context.context(msg, logging.info)
        bind_device_num = random.randint(1, device_num)
        pci_assignable.request_devs(devices[:bind_device_num])
        logging.info("Sleep 3s before releasing vf to host.")
        time.sleep(3)
        pci_assignable.release_devs()
        logging.info("Sleep 3s after releasing vf to host.")
        time.sleep(3)
        if device_type == "vf":
            post_device_num = pci_assignable.get_vfs_count()
        else:
            post_device_num = len(pci_assignable.get_pf_vf_info())
        if post_device_num != device_num:
            msg = "lspci cannot report the correct PF/VF number."
            msg += " Correct number is '%s'" % device_num
            msg += " lspci report '%s'" % post_device_num
            test.fail(msg)
    dmesg = process.system_output("dmesg")
    file_name = "host_dmesg_after_unbind_device.txt"
    logging.info("Log dmesg after bind/unbing device to '%s'.", file_name)
    if configure_on_host:
        msg = "Check whether VFs still get ip in host."
        error_context.context(msg, logging.info)
        for ethname in ips:
            utils_net.bring_up_ifname(ethname, action="up")
            _ip = utils_net.get_ip_address_by_interface(ethname, ip_ver="ipv4")
            if not _ip:
                msg = "Interface '%s' could not get IP." % ethname
                msg += "Before bind/unbind it have IP '%s'." % ips[ethname]
                logging.error(msg)
            else:
                logging.info("Interface '%s' get IP '%s'", ethname, _ip)

    msg = "Try to boot up guest(s) with VF(s)."
    error_context.context(msg, logging.info)
    regain_ip_cmd = params.get("regain_ip_cmd", None)
    timeout = int(params.get("login_timeout", 30))

    for vm_name in params["vms"].split(" "):
        params["start_vm"] = "yes"
        vm = env.get_vm(vm_name)
        # User can opt for dhcp IP or a static IP configuration for probed
        # interfaces inside guest. Added option for static IP configuration
        # below
        if static_ip:
            if 'IP_addr_VF' not in locals():
                IP_addr_VF = netaddr.IPAddress(params.get("start_addr_VF"))
                net_mask = params.get("net_mask")
            if not IP_addr_VF:
                test.fail("No IP address found, please"
                          "populate starting IP address in "
                          "configuration file")
            session = vm.wait_for_serial_login(
                timeout=int(params.get("login_timeout", 720)))
            rc, output = session.cmd_status_output(
                "ip li| grep -i 'BROADCAST'|awk '{print $2}'| sed 's/://'")
            if not rc:
                iface_probed = output.splitlines()
                logging.info("probed VF Interface(s) in guest: %s",
                             iface_probed)
                for iface in iface_probed:
                    mac = utils_net.get_linux_mac(session, iface)
                    utils_net.set_guest_ip_addr(session, mac, IP_addr_VF)
                    rc, output = utils_test.ping(
                        str(IP_addr_VF), 30, timeout=60)
                    if rc != 0:
                        test.fail("New nic failed ping test"
                                  "with output:\n %s" % output)
                    IP_addr_VF = IP_addr_VF + 1
            else:
                test.fail("Fail to locate probed interfaces"
                          "for VFs, please check on respective"
                          "drivers in guest image")
        else:
            # User has opted for DHCP IP inside guest
            vm.verify_alive()
            vm.wait_for_login(timeout=int(params.get("login_timeout", 360)))
开发者ID:bssrikanth,项目名称:tp-qemu,代码行数:101,代码来源:sr_iov_sanity.py

示例6: run


#.........这里部分代码省略.........
        error.context("Flood ping test", logging.info)
        utils_test.ping(dst_ip, None, interface=nic, flood=True,
                        output_func=None, timeout=flood_minutes * 60,
                        session=session)
        error.context("Final ping test", logging.info)
        counts = params.get("ping_counts", 100)
        status, output = utils_test.ping(dst_ip, counts, interface=nic,
                                         timeout=float(counts) * 1.5,
                                         session=session)
        if strick_check == "yes":
            ratio = utils_test.get_loss_ratio(output)
            if ratio != 0:
                raise error.TestFail("Packet loss ratio is %s after flood"
                                     % ratio)
        else:
            if status != 0:
                raise error.TestFail("Ping returns non-zero value %s" %
                                     output)

    def file_transfer(session, src, dst):
        username = params.get("username", "")
        password = params.get("password", "")
        src_path = "/tmp/1"
        dst_path = "/tmp/2"
        port = int(params["file_transfer_port"])

        cmd = "dd if=/dev/urandom of=%s bs=100M count=1" % src_path
        cmd = params.get("file_create_cmd", cmd)

        error.context("Create file by dd command, cmd: %s" % cmd, logging.info)
        session.cmd(cmd)

        transfer_timeout = int(params.get("transfer_timeout"))
        log_filename = "scp-from-%s-to-%s.log" % (src, dst)
        error.context("Transfer file from %s to %s" % (src, dst), logging.info)
        remote.scp_between_remotes(src, dst, port, password, password,
                                   username, username, src_path, dst_path,
                                   log_filename=log_filename,
                                   timeout=transfer_timeout)
        src_path = dst_path
        dst_path = "/tmp/3"
        log_filename = "scp-from-%s-to-%s.log" % (dst, src)
        error.context("Transfer file from %s to %s" % (dst, src), logging.info)
        remote.scp_between_remotes(dst, src, port, password, password,
                                   username, username, src_path, dst_path,
                                   log_filename=log_filename,
                                   timeout=transfer_timeout)
        error.context("Compare original file and transferred file",
                      logging.info)

        cmd1 = "md5sum /tmp/1"
        cmd2 = "md5sum /tmp/3"
        md5sum1 = session.cmd(cmd1).split()[0]
        md5sum2 = session.cmd(cmd2).split()[0]
        if md5sum1 != md5sum2:
            raise error.TestError("File changed after transfer")

    nic_interface_list = []
    vms = params["vms"].split()
    timeout = float(params.get("login_timeout", 360))
    strict_check = params.get("strick_check", "no")
    host_ip = utils_net.get_ip_address_by_interface(params.get("netdst"))
    host_ip = params.get("srchost", host_ip)
    flood_minutes = float(params["flood_minutes"])
    nic_interface = []
    for vm_name in vms:
        guest_ifname = ""
        guest_ip = ""
        vm = env.get_vm(vm_name)
        session = vm.wait_for_serial_login(timeout=timeout)
        error.context("Check all the nics available or not", logging.info)
        for index, nic in enumerate(vm.virtnet):
            guest_ifname = utils_net.get_linux_ifname(session, nic.mac)
            guest_ip = vm.get_address(index)
            if not (guest_ifname and guest_ip):
                err_log = "vms %s get ip or ifname failed." % vm_name
                err_log = "ifname: %s, ip: %s." % (guest_ifname, guest_ip)
                raise error.TestFail(err_log)
            nic_interface = [guest_ifname, guest_ip, session]
            nic_interface_list.append(nic_interface)

    nic_interface_list_len = len(nic_interface_list)
    # ping and file transfer test
    for src_ip_index in range(nic_interface_list_len):
        error.context("Ping test from guest to host", logging.info)
        src_ip_info = nic_interface_list[src_ip_index]
        ping(src_ip_info[2], src_ip_info[0], host_ip, strict_check,
             flood_minutes)
        error.context("File transfer test between guest and host",
                      logging.info)
        file_transfer(src_ip_info[2], src_ip_info[1], host_ip)
        for dst_ip in nic_interface_list[src_ip_index:]:
            txt = "Ping test between %s and %s" % (src_ip_info[1], dst_ip[1])
            error.context(txt, logging.info)
            ping(src_ip_info[2], src_ip_info[0], dst_ip[1], strict_check,
                 flood_minutes)
            txt = "File transfer test between %s " % src_ip_info[1]
            txt += "and %s" % dst_ip[1]
            error.context(txt, logging.info)
            file_transfer(src_ip_info[2], src_ip_info[1], dst_ip[1])
开发者ID:maxujun,项目名称:tp-qemu,代码行数:101,代码来源:multi_vms_nics.py

示例7: run


#.........这里部分代码省略.........
            timegap = endtime - starttime
            if timegap > timeout:
                break

    def check_ping(status, output):
        """ ratio <5% is acceptance."""
        if status != 0:
            raise error.TestFail("Ping failed, staus:%s, output:%s"
                                 % (status, output))
        # if status != 0 the ping process seams hit issue.
        ratio = utils_test.get_loss_ratio(output)
        if ratio == -1:
            raise error.TestFail('''The ratio is %s, and status is %s,
                                    output is %s''' % (ratio, status, output))
        elif ratio > int(params["failed_ratio"]):
            raise error.TestFail("The loss raito is %s, test failed" % ratio)
        logging.info("ping pass with loss raito:%s, that less than %s" %
                     (ratio, params["failed_ratio"]))

    def team_if_exist():
        """ judge if team is alive well."""
        team_exists_cmd = params.get("team_if_exists_cmd")
        return session_serial.cmd_status(team_exists_cmd) == 0

    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    timeout = int(params.get("login_timeout", 1200))
    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)]
    session_serial.cmd_output_safe(params["nm_stop_cmd"])
    team_if = params.get("team_if")
    # initial

    error.context("Step1: Configure the team environment", logging.info)
    # steps of building the teaming environment starts
    modprobe_cmd = "modprobe team"
    session_serial.cmd_output_safe(modprobe_cmd)
    session_serial.cmd_output_safe(params["createteam_cmd"])
    # this cmd is to create the team0 and correspoding userspace daemon
    if not team_if_exist():
        raise error.TestFail("Interface %s is not created." % team_if)
    # check if team0 is created successfully
    ports, team_ip = team_port_add(ifnames, team_if)
    logging.debug("The list of the ports that added to %s : %s"
                  % (team_if, ports))
    logging.debug("The ip address of %s : %s" % (team_if, team_ip))
    output = session_serial.cmd_output_safe(params["team_debug_cmd"])
    logging.debug("team interface configuration: %s" % output)
    route_cmd = session_serial.cmd_output_safe(params["route_cmd"])
    logging.debug("The route table of guest: %s" % route_cmd)
    # this is not this case checkpoint, just to check if route works fine
    # steps of building finished

    try:
        error.context("Login in guest via ssh", logging.info)
        # steps of testing this case starts
        session = vm.wait_for_login(timeout=timeout)
        dest = utils_net.get_ip_address_by_interface(params["netdst"])
        count = params.get("count")
        timeout = float(count) * 2
        error.context("Step2: Check if guest can ping out:", logging.info)
        status, output = utils_test.ping(dest=dest, count=10,
                                         interface=team_if,
                                         timeout=30,
                                         session=session)
        check_ping(status, output)
        # small ping check if the team0 works w/o failover
        error.context("Step3: Start failover testing until ping finished",
                      logging.info)
        failover_thread = utils.InterruptedThread(failover, (ifnames, timeout))
        failover_thread.start()
        # start failover loop until ping finished
        error.context("Step4: Start ping host for %s counts"
                      % count, logging.info)
        if failover_thread.is_alive():
            status, output = utils_test.ping(dest=dest, count=count,
                                             interface=team_if,
                                             timeout=float(count) * 1.5,
                                             session=session)
            error.context("Step5: Check if ping succeeded", logging.info)
            check_ping(status, output)
        else:
            raise error.TestWarn("The failover thread is not alive")
        time.sleep(3)
        try:
            timeout = timeout * 1.5
            failover_thread.join(timeout)
        except Exception:
            raise error.TestWarn("Failed to join the failover thread")
        # finish the main steps and check the result
        session_serial.cmd_output_safe(params["killteam_cmd"])
        if team_if_exist():
            raise error.TestFail("Remove %s failed" % team_if)
        logging.info("%s removed" % team_if)
        # remove the team0 and the daemon, check if succeed
    finally:
        if session:
            session.close()
开发者ID:uni-peter-zheng,项目名称:tp-qemu,代码行数:101,代码来源:nic_teaming.py

示例8: run

def run(test, params, env):
    """
    create/delete macvtap in host

    1) Verify no other macvtap share the physical network device.
    2) Create a macvtap device in host.
    3) Check configuraton of macvtap device.
    4) Ping out from host with the interface that create macvtap.
    5) Delete the macvtap device create in step 2.
    6) Ping out from host with the interface that create macvtap.

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

    ifname = params.get("macvtap_base_interface")
    macvtap_mode = params.get("macvtap_mode", "passthru")
    dest_host = params.get("dest_host")
    set_mac = params.get("set_mac", "yes") == "yes"
    macvtaps = []

    if not ifname:
        ifname = params.get("netdst")
    ifname = utils_net.get_macvtap_base_iface(ifname)

    error.context("Verify no other macvtap share the physical network device.", logging.info)
    macvtap_devices = get_macvtap_device_on_ifname(ifname)
    for device in macvtap_devices:
        utils.system_output("ip link delete %s" % device)

    for mode in macvtap_mode.split():
        macvtap_name = "%s_01" % mode
        txt = "Create %s mode macvtap device %s on %s." % (mode, macvtap_name, ifname)
        error.context(txt, logging.info)
        cmd = " ip link add link %s name %s type macvtap mode %s" % (ifname, macvtap_name, mode)
        utils.system(cmd, timeout=240)
        if set_mac:
            txt = "Determine and configure mac address of %s, " % macvtap_name
            txt += "Then link up it."
            error.context(txt, logging.info)
            mac = utils_net.generate_mac_address_simple()
            cmd = " ip link set %s address %s up" % (macvtap_name, mac)
            utils.system(cmd, timeout=240)

        error.context("Check configuraton of macvtap device", logging.info)
        check_cmd = " ip -d link show %s" % macvtap_name
        try:
            tap_info = utils.system_output(check_cmd, timeout=240)
        except error.CmdError:
            err = "Fail to create %s mode macvtap on %s" % (mode, ifname)
            raise error.TestFail(err)
        if set_mac:
            if mac not in tap_info:
                err = "Fail to set mac for %s" % macvtap_name
                raise error.TestFail(err)
        macvtaps.append(macvtap_name)

    if not dest_host:
        dest_host_get_cmd = "ip route | awk '/default/ { print $3 }'"
        dest_host_get_cmd = params.get("dest_host_get_cmd", dest_host_get_cmd)
        dest_host = utils.system_output(dest_host_get_cmd).split()[-1]

    txt = "Ping dest host %s from " % dest_host
    txt += "localhost with the interface %s" % ifname
    error.context(txt, logging.info)
    status, output = utils_test.ping(dest_host, 10, interface=ifname, timeout=20)
    ratio = utils_test.get_loss_ratio(output)
    if "passthru" in macvtap_mode:
        ifnames = utils_net.get_host_iface()
        ifnames.remove(ifname)
        logging.info("ifnames = %s", ifnames)
        ips = []
        for name in ifnames:
            try:
                _ip = utils_net.get_ip_address_by_interface(name)
                if _ip != "127.0.0.1":
                    ips.append(_ip)
            except Exception:
                pass
        logging.info("ips = %s", ips)
        if not ips:
            if ratio != 100:
                err = "%s did not lost network connection after " % ifname
                err += " creating %s mode macvtap on it." % macvtap_mode
                raise error.TestFail(err)
        else:
            err = "%s is not the only network device in host" % ifname
            logging.debug(err)
    else:
        if ratio != 0:
            err = "Package lost during ping %s from %s " % (dest_host, ifname)
            err += "after creating %s mode macvtap on it." % macvtap_mode
            raise error.TestFail(err)

    for name in macvtaps:
        txt = "Delete macvtap device %s on %s." % (name, ifname)
        error.context(txt, logging.info)
        del_cmd = "ip link delete %s" % name
        utils.system(del_cmd)
#.........这里部分代码省略.........
开发者ID:uni-peter-zheng,项目名称:tp-qemu,代码行数:101,代码来源:create_macvtap_device.py

示例9: __init__

    def __init__(self, test, params, vm):
        """
        Sets class atributes from test parameters.

        @param test: QEMU test object.
        @param params: Dictionary with test parameters.
        """
        root_dir = data_dir.get_data_dir()
        self.deps_dir = os.path.join(test.virtdir, "deps")
        self.unattended_dir = os.path.join(test.virtdir, "unattended")
        self.params = params

        self.attributes = [
            "kernel_args",
            "finish_program",
            "cdrom_cd1",
            "unattended_file",
            "medium",
            "url",
            "kernel",
            "initrd",
            "nfs_server",
            "nfs_dir",
            "install_virtio",
            "floppy_name",
            "cdrom_unattended",
            "boot_path",
            "kernel_params",
            "extra_params",
            "qemu_img_binary",
            "cdkey",
            "finish_program",
            "vm_type",
            "process_check",
            "vfd_size",
        ]

        for a in self.attributes:
            setattr(self, a, params.get(a, ""))

        if self.install_virtio == "yes":
            v_attributes = [
                "virtio_floppy",
                "virtio_storage_path",
                "virtio_network_path",
                "virtio_oemsetup_id",
                "virtio_network_installer",
            ]
            for va in v_attributes:
                setattr(self, va, params.get(va, ""))

        self.tmpdir = test.tmpdir

        if getattr(self, "unattended_file"):
            self.unattended_file = os.path.join(test.virtdir, self.unattended_file)

        if getattr(self, "finish_program"):
            self.finish_program = os.path.join(test.virtdir, self.finish_program)

        if getattr(self, "qemu_img_binary"):
            if not os.path.isfile(getattr(self, "qemu_img_binary")):
                qemu_img_base_dir = os.path.join(data_dir.get_root_dir(), self.params.get("vm_type"))
                self.qemu_img_binary = os.path.join(qemu_img_base_dir, self.qemu_img_binary)

        if getattr(self, "cdrom_cd1"):
            self.cdrom_cd1 = os.path.join(root_dir, self.cdrom_cd1)
        self.cdrom_cd1_mount = tempfile.mkdtemp(prefix="cdrom_cd1_", dir=self.tmpdir)
        if getattr(self, "cdrom_unattended"):
            self.cdrom_unattended = os.path.join(root_dir, self.cdrom_unattended)
        if getattr(self, "kernel"):
            self.kernel = os.path.join(root_dir, self.kernel)
        if getattr(self, "initrd"):
            self.initrd = os.path.join(root_dir, self.initrd)

        if self.medium == "nfs":
            self.nfs_mount = tempfile.mkdtemp(prefix="nfs_", dir=self.tmpdir)

        setattr(self, "floppy", self.floppy_name)
        if getattr(self, "floppy"):
            self.floppy = os.path.join(root_dir, self.floppy)
            if not os.path.isdir(os.path.dirname(self.floppy)):
                os.makedirs(os.path.dirname(self.floppy))

        self.image_path = os.path.dirname(self.kernel)

        # Content server params
        # lookup host ip address for first nic by interface name
        try:
            auto_ip = utils_net.get_ip_address_by_interface(vm.virtnet[0].netdst)
        except utils_net.NetError:
            auto_ip = None

        self.url_auto_content_ip = params.get("url_auto_ip", auto_ip)
        self.url_auto_content_port = None

        # Kickstart server params
        # use the same IP as url_auto_content_ip, but a different port
        self.unattended_server_port = None

        # Embedded Syslog Server
#.........这里部分代码省略.........
开发者ID:sibiaoluo,项目名称:virt-test,代码行数:101,代码来源:unattended_install.py

示例10: run


#.........这里部分代码省略.........
    bridge_name = params.get("bridge_name", "br0")
    filter_name = params.get("filter_name", "vdsm-no-mac-spoofing")
    ping_count = params.get("ping_count", "5")
    ping_timeout = float(params.get("ping_timeout", "10"))
    iface_name = utils_net.get_net_if(state="UP")[0]
    bridge_script = NETWORK_SCRIPT + bridge_name
    iface_script = NETWORK_SCRIPT + iface_name
    iface_script_bk = os.path.join(data_dir.get_tmp_dir(), "iface-%s.bk" % iface_name)

    vms = params.get("vms").split()
    if len(vms) <= 1:
        test.cancel("Need two VMs to test")
    else:
        vm1_name = vms[0]
        vm2_name = vms[1]

    vm1 = env.get_vm(vm1_name)
    vm2 = env.get_vm(vm2_name)

    # Back up the interface script
    process.run("cp %s %s" % (iface_script, iface_script_bk), shell=True)
    # Back up vm xml
    vm1_xml_bak = vm_xml.VMXML.new_from_dumpxml(vm1_name)
    vm2_xml_bak = vm_xml.VMXML.new_from_dumpxml(vm2_name)

    # Stop NetworkManager service
    NM_service = service.Factory.create_service("NetworkManager")
    NM_status = NM_service.status()
    if NM_status is True:
        NM_service.stop()

    # Start network service
    NW_service = service.Factory.create_service("network")
    NW_status = NW_service.status()
    if NW_status is None:
        logging.debug("network service not found")
        if not utils_package.package_install('network-scripts') or \
                not utils_package.package_install('initscripts'):
            test.cancel("Failed to install network service")
    if NW_status is not True:
        logging.debug("network service is not running")
        NW_service.start()

    try:
        create_bridge(bridge_name, iface_name)
        define_nwfilter(filter_name)
        modify_iface_xml(bridge_name, filter_name, vm1_name)

        if vm1.is_alive():
            vm1.destroy()

        vm1.start()
        # Check if vm can get ip with the new create bridge
        session1 = session2 = None
        try:
            utils_net.update_mac_ip_address(vm1, timeout=120)
            vm1_ip = vm1.get_address()
        except Exception as errs:
            test.fail("vm1 can't get IP with the new create bridge: %s" % errs)

        # Check guest and host can ping each other
        host_ip = utils_net.get_ip_address_by_interface(bridge_name)
        remote_ip = params.get("remote_ip", "www.baidu.com")
        ping(host_ip, vm1_ip, ping_count, ping_timeout)
        ping(host_ip, remote_ip, ping_count, ping_timeout)
        session1 = vm1.wait_for_login()
        ping(vm1_ip, host_ip, ping_count, ping_timeout, session=session1)
        ping(vm1_ip, remote_ip, ping_count, ping_timeout, session=session1)

        # Start vm2 connect to the same bridge
        modify_iface_xml(bridge_name, filter_name, vm2_name)
        if vm2.is_alive():
            vm2.destroy()
        vm2.start()

        # Check if vm1 and vm2 can ping each other
        try:
            utils_net.update_mac_ip_address(vm2, timeout=120)
            vm2_ip = vm2.get_address()
        except Exception as errs:
            test.fail("vm2 can't get IP with the new create bridge: %s" % errs)
        session2 = vm2.wait_for_login()
        ping(vm2_ip, vm1_ip, ping_count, ping_timeout, session=session2)
        ping(vm1_ip, vm2_ip, ping_count, ping_timeout, session=session1)
    finally:
        logging.debug("Start to restore")
        vm1_xml_bak.sync()
        vm2_xml_bak.sync()
        virsh.nwfilter_undefine(filter_name, ignore_status=True)
        if libvirt.check_iface(bridge_name, "exists", "--all"):
            virsh.iface_unbridge(bridge_name, timeout=60, debug=True)
        if os.path.exists(iface_script_bk):
            process.run("mv %s %s" % (iface_script_bk, iface_script), shell=True)
        if os.path.exists(bridge_script):
            process.run("rm -rf %s" % bridge_script, shell=True)
        # reload network configuration
        NW_service.restart()
        # recover NetworkManager
        if NM_status is True:
            NM_service.start()
开发者ID:nasastry,项目名称:tp-libvirt,代码行数:101,代码来源:iface_bridge.py

示例11: run_netperf_udp

def run_netperf_udp(test, params, env):
    """
    Run netperf on server and client side, we need run this case on two
    machines. If dsthost is not set will start netperf server on local
    host and log a error message.:
    1) Start one vm guest os as client.
    2) Start a reference machine (dsthost) as server.
    3) Setup netperf on guest and reference machine (dsthost).
    4) Run netserver on server using control.server.
    5) Run netperf client command in guest several time with different
       message size.
    6) Compare UDP performance to make sure it is acceptable.

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

    def get_remote_host_session():
        dsthostssh = remote.remote_login("ssh", dsthost, 22, "root",
                                         passwd, "#", timeout=30)
        if dsthostssh:
            dsthostssh.set_status_test_command("echo $?")
            return dsthostssh
        else:
            return None

    def scp_to_remote(local_path="", remote_path=""):
        remote.scp_to_remote(dsthost, 22, "root", passwd, local_path,
                             remote_path)
        vm.copy_files_to(local_path, remote_path)

    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()

    session = vm.wait_for_login(timeout=int(params.get("login_timeout", 360)))

    dsthost = params.get("dsthost")
    if not dsthost:
        dsthost = utils_net.get_ip_address_by_interface(params.get("netdst"))
        logging.error("dsthost is not set, use localhost ip %s" % dsthost)
    else:
        logging.info("Dest host is %s" % dsthost)
    passwd = params.get("hostpasswd")
    test_timeout = float(params.get("test_timeout", "1200"))

    error.context("Create session connection to remote machine")
    dsthostssh = utils_misc.wait_for(get_remote_host_session, 120, 0, 2)
    if not dsthostssh:
        raise error.TestError("Could not login into remote host %s " % dsthost)

    # Get range of message size.
    message_size_range = params.get("message_size_range")
    message_size = message_size_range.split()
    start_size = int(message_size[0])
    end_size = int(message_size[1])
    step = int(message_size[2])
    m_size = start_size

    error.context("Copy netperf to dsthost and guest vm.")
    netperf_links = params["netperf_links"].split()
    remote_dir = params.get("remote_dir", "/var/tmp")
    for netperf_link in netperf_links:
        if utils.is_url(netperf_link):
            download_dir = data_dir.get_download_dir()
            md5sum = params.get("pkg_md5sum")
            netperf_dir = utils.unmap_url_cache(download_dir,
                                                netperf_link, md5sum)
        elif netperf_link:
            netperf_dir = os.path.join(test.virtdir, netperf_link)
        scp_to_remote(netperf_dir, remote_dir)

    # Setup netpref.
    error.context("Set up netperf on reference machine.", logging.info)
    cmd = params.get("setup_cmd")
    (status, output) = dsthostssh.cmd_status_output(cmd % remote_dir,
                                                    timeout=test_timeout)
    if status != 0:
        raise error.TestError("Fail to setup netperf on reference machine.")
    error.context("Setup netperf on guest os.", logging.info)
    (status, output) = session.cmd_status_output(cmd % remote_dir,
                                                 timeout=test_timeout)
    if status != 0:
        raise error.TestError("Fail to setup netperf on guest os.")

    # Start netperf server in dsthost.
    cmd = "killall netserver"
    dsthostssh.cmd_status_output(cmd)
    cmd = params.get("netserver_cmd")
    txt = "Run netserver on server (dsthost) using control.server."
    error.context(txt, logging.info)
    (status, output) = dsthostssh.cmd_status_output(cmd)
    if status != 0:
        txt = "Fail to start netperf server on remote machine."
        txt += " Command output: %s" % output
        raise error.TestError(txt)

    throughput = []

    # Run netperf with message size defined in range.
#.........这里部分代码省略.........
开发者ID:Antique,项目名称:virt-test,代码行数:101,代码来源:netperf_udp.py

示例12: run

def run(test, params, env):
    """
    Expose host MTU to guest test

    1) Boot up guest with param 'host_mtu=4000' in nic part
    2) Disable NetworkManager in guest
    3) set mtu of guest tap (eg: tap0) and physical nic (eg: eno1) to
       4000 in host
    4) check the mtu in guest
    5) ping from guest to external host with packet size 3972

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

    def get_ovs_ports(ovs):
        """
        Get ovs ports

        :param ovs: ovs bridge name
        """

        cmd = "ovs-vsctl list-ports %s" % ovs
        return process.system_output(cmd, shell=True).decode()

    def is_ovs_backend(netdst):
        """
        Check whether the host is OVS backend

        :param netdst: netdst get from command line
        """

        return netdst in process.system_output("ovs-vsctl list-br",
                                               ignore_status=True,
                                               shell=True).decode()

    def cleanup_ovs_ports(netdst, ports):
        """
        Clean up created ovs ports in this case

        :param netdst: netdst get from command line
        :param ports: existing ports need to be remain before this test
        """

        if is_ovs_backend(netdst) is True:
            ports = set(get_ovs_ports(netdst).splitlines()) - \
                    set(ports.splitlines())
            for p in ports:
                process.system("ovs-vsctl del-port %s %s" % (netdst, p))

    netdst = params.get("netdst", "switch")
    if netdst in utils_net.Bridge().list_br():
        host_hw_interface = utils_net.Bridge().list_iface()[0]
    elif is_ovs_backend(netdst) is True:
        host_hw_interface = get_ovs_ports(netdst)
        tmp_ports = re.findall(r"t[0-9]-[a-zA-Z0-9]{6}", host_hw_interface)
        if tmp_ports:
            for p in tmp_ports:
                process.system_output("ovs-vsctl del-port %s %s" %
                                      (netdst, p))
            host_hw_interface = get_ovs_ports(netdst)
    else:
        test.cancel("The host is using Macvtap backend, which is not"
                    " supported by now!")

    params["start_vm"] = "yes"
    env_process.preprocess_vm(test, params, env, params["main_vm"])

    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()

    vm_iface = vm.get_ifname()
    # TODO, will support windows later
    process.system_output(params["set_mtu_cmd"] % host_hw_interface)
    process.system_output(params["set_mtu_cmd"] % vm_iface)

    os_type = params.get("os_type", "linux")
    login_timeout = float(params.get("login_timeout", 360))
    session = vm.wait_for_login(timeout=login_timeout)

    host_ip = utils_net.get_ip_address_by_interface(params["netdst"])
    if os_type == "linux":  # TODO, will support windows later
        session.cmd_output_safe(params["nm_stop_cmd"])
        guest_ifname = utils_net.get_linux_ifname(session,
                                                  vm.get_mac_address())
        output = session.cmd_output_safe(
                params["check_guest_mtu_cmd"] % guest_ifname)
        error_context.context(output, logging.info)
        match_string = "mtu %s" % params["mtu_value"]
        if match_string in output:
            logging.info("Host mtu %s exposed to guest as expected!" %
                         params["mtu_value"])
            logging.info("Ping from guest to host with packet size 3972")
            status, output = utils_test.ping(host_ip, 10, packetsize=3972,
                                             timeout=30, session=session)
            ratio = utils_test.get_loss_ratio(output)
            if ratio != 0:
                test.fail("Loss ratio is %s", ratio)
        else:
#.........这里部分代码省略.........
开发者ID:yanan-fu,项目名称:tp-qemu,代码行数:101,代码来源:expose_host_mtu.py

示例13: run


#.........这里部分代码省略.........
                      logging.info)

        cmd1 = "md5sum /tmp/1"
        cmd2 = "md5sum /tmp/3"
        md5sum1 = session.cmd(cmd1).split()[0]
        md5sum2 = session.cmd(cmd2).split()[0]
        if md5sum1 != md5sum2:
            raise error.TestError("File changed after transfer")

    nic_interface_list = []
    check_irqbalance_cmd = params.get("check_irqbalance_cmd")
    stop_irqbalance_cmd = params.get("stop_irqbalance_cmd")
    start_irqbalance_cmd = params.get("start_irqbalance_cmd")
    status_irqbalance = params.get("status_irqbalance")
    vms = params["vms"].split()
    host_mem = utils_memory.memtotal() / (1024 * 1024)
    host_cpu_count = len(utils_misc.get_cpu_processors())
    vhost_count = 0
    if params.get("vhost"):
        vhost_count = 1
    if host_cpu_count < (1 + vhost_count) * len(vms):
        raise error.TestError("The host don't have enough cpus to start guest"
                              "pcus: %d, minimum of vcpus and vhost: %d" %
                              (host_cpu_count, (1 + vhost_count) * len(vms)))
    params['mem'] = host_mem / len(vms) * 1024
    params['smp'] = host_cpu_count / len(vms) - vhost_count
    if params['smp'] % 2 != 0:
        params['vcpu_sockets'] = 1
    params["start_vm"] = "yes"
    for vm_name in vms:
        env_process.preprocess_vm(test, params, env, vm_name)
    timeout = float(params.get("login_timeout", 360))
    strict_check = params.get("strick_check", "no")
    host_ip = utils_net.get_ip_address_by_interface(params.get("netdst"))
    host_ip = params.get("srchost", host_ip)
    flood_minutes = float(params["flood_minutes"])
    error.context("Check irqbalance service status", logging.info)
    o = process.system_output(check_irqbalance_cmd, ignore_status=True)
    check_stop_irqbalance = False
    if re.findall(status_irqbalance, o):
        logging.debug("stop irqbalance")
        process.run(stop_irqbalance_cmd)
        check_stop_irqbalance = True
        o = process.system_output(check_irqbalance_cmd, ignore_status=True)
        if re.findall(status_irqbalance, o):
            raise error.TestError("Can not stop irqbalance")
    thread_list = []
    nic_interface = []
    for vm_name in vms:
        guest_ifname = ""
        guest_ip = ""
        vm = env.get_vm(vm_name)
        session = vm.wait_for_login(timeout=timeout)
        thread_list.extend(vm.vcpu_threads)
        thread_list.extend(vm.vhost_threads)
        error.context("Check all the nics available or not", logging.info)
        for index, nic in enumerate(vm.virtnet):
            guest_ifname = utils_net.get_linux_ifname(session, nic.mac)
            guest_ip = vm.get_address(index)
            if not (guest_ifname and guest_ip):
                err_log = "vms %s get ip or ifname failed." % vm_name
                err_log = "ifname: %s, ip: %s." % (guest_ifname, guest_ip)
                raise error.TestFail(err_log)
            nic_interface = [guest_ifname, guest_ip, session]
            nic_interface_list.append(nic_interface)
    error.context("Pin vcpus and vhosts to host cpus", logging.info)
开发者ID:CongLi,项目名称:tp-qemu,代码行数:67,代码来源:multi_vms_nics.py

示例14: run


#.........这里部分代码省略.........

    def checkTcpdump(output, target_ip, host_ip, direction):
        """
        Check tcpdump result file and report unexpect packet to debug log.

        :parm output: string of tcpdump output.
        :parm target_p: ip of port in ovs be mirroring.
        :parm host_ip: ip of ovs port.
        :parm direction: mirror direction, all, only input or output.

        :return: bool type result.
        """
        rex = r".*IP (%s|%s) > " % (host_ip, target_ip)
        rex += "(%s|%s).*ICMP echo.*" % (target_ip, host_ip)
        if direction == "input":
            rex = r".*IP %s > %s.*ICMP echo reply.*" % (host_ip, target_ip)
        if direction == "output":
            rex = r".*IP %s > %s.*ICMP echo request.*" % (target_ip, host_ip)
        for idx, _ in enumerate(output.splitlines()):
            if not re.match(rex, _):
                logging.debug("Unexpect packet in line %d: %s" % (idx, _))
                return False
        return True

    os_dep.command("ovs-vsctl")
    if params.get("netdst") not in utils.system_output("ovs-vsctl show"):
        raise error.TestError("This is a openvswitch only test")

    netdst = params.get("netdst", "ovs0")
    direction = params.get("direction", "all")
    mirror_vm = params.get("mirror_vm", "vm1")
    target_vm = params.get("target_vm", "vm2")
    refer_vm = params.get("refer_vm", "vm3")
    login_timeout = int(params.get("login_timeout", "600"))
    ip_version = params.get("ip_version", "ipv4")
    host_ip = utils_net.get_ip_address_by_interface(netdst)
    try:
        vms_info = {}
        for p_vm in params.get("vms").split():
            o_vm = env.get_vm(p_vm)
            o_vm.verify_alive()
            session = o_vm.wait_for_serial_login(timeout=login_timeout)
            ifname = o_vm.get_ifname()
            ip = o_vm.wait_for_get_address(0, timeout=login_timeout,
                                           ip_version=ip_version)
            vms_info[p_vm] = [o_vm, ifname, ip, session]

        mirror_ifname = vms_info[mirror_vm][1]
        target_ifname = vms_info[target_vm][1]
        target_ip = vms_info[target_vm][2]
        refer_ip = vms_info[refer_vm][2]
        session = vms_info[mirror_vm][3]

        error.context("Create mirror port in ovs", logging.info)
        create_mirror_port(mirror_ifname, target_ifname, direction, netdst)
        ping_cmd = "ping -c 10 %s" % host_ip
        status, output = session.cmd_status_output(ping_cmd, timeout=60)
        if status == 0:
            ifcfg = session.cmd_output_safe("ifconfig")
            logging.debug("Guest network info: %s" % ifcfg)
            logging.debug("Ping results: %s" % output)
            raise error.TestFail("All packets from %s to host should lost"
                                 % mirror_vm)

        error.context("Start tcpdump threads in %s" % mirror_vm, logging.info)
        session.cmd("ifconfig eth0 0 up", timeout=60)
        for vm, ip in [(target_vm, target_ip), (refer_vm, refer_ip)]:
            tcpdump_cmd = "tcpdump -l -n host %s and icmp >" % ip
            tcpdump_cmd += "/tmp/tcpdump-%s.txt &" % vm
            session.sendline(tcpdump_cmd)
            time.sleep(0.5)

        error.context("Start ping threads in %s %s" % (target_vm, refer_vm),
                      logging.info)
        for vm in [target_vm, refer_vm]:
            ses = vms_info[vm][3]
            ses.cmd("ping %s -c 100" % host_ip, timeout=150)

        error.context("Check tcpdump results", logging.info)
        session.cmd_output_safe("pkill tcpdump")
        utils.system("ovs-vsctl clear bridge %s mirrors" % netdst)
        session.cmd("service network restart", timeout=60)
        for vm in [target_vm, refer_vm]:
            src_file = "/tmp/tcpdump-%s.txt" % vm
            dst_file = os.path.join(test.resultsdir, "tcpdump-%s.txt" % vm)
            vms_info[mirror_vm][0].copy_files_from(src_file, dst_file)
            fd = open(dst_file, "r")
            content = fd.read().strip()
            fd.close()
            if vm == refer_vm and content:
                raise error.TestFail(
                    "should not packet from %s dumped in %s" %
                    (refer_vm, mirror_vm))
            elif not checkTcpdump(content, target_ip, host_ip, direction):
                raise error.TestFail(
                    "Unexpect packages from %s dumped in %s" % (vm, mirror_vm))
    finally:
        for f in glob.glob("/var/log/openvswith/*.log"):
            dst = os.path.join(test.resultsdir, os.path.basename(f))
            shutil.copy(f, dst)
开发者ID:hshl1214,项目名称:tp-qemu,代码行数:101,代码来源:ovs_mirror.py

示例15: run


#.........这里部分代码省略.........
    4) Disable the primary link of guest.
    5) Check if new interface gets ip address.
    6) Ping guest's new ip from host.
    7) Re-enabling the primary link.
    8) Send a migration command to the source VM and wait until it's finished.
    9) Disable the primary link again.
    10) Ping guest's new ip from host.
    11) Re-enabling the primary link.

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

    def set_link(nic_name, up=False):
        for nic in vm.virtnet:
            if nic.nic_name != nic_name:
                vm.set_link(nic.device_id, up=up)

    vm = env.get_vm(params["main_vm"])
    vm.verify_alive()
    timeout = int(params.get("login_timeout", 360))
    session = vm.wait_for_serial_login(timeout=timeout)

    guest_is_not_windows = (params.get("os_type") != 'windows')
    run_dhclient = params.get("run_dhclient", "no")
    mig_timeout = float(params.get("mig_timeout", "3600"))
    nettype = params.get("nettype", "bridge")
    netdst = params.get("netdst", "virbr0")
    mig_protocol = params.get("migration_protocol", "tcp")
    mig_cancel_delay = int(params.get("mig_cancel") == "yes") * 2
    pci_model = params.get("pci_model")

    # Modprobe the module if specified in config file
    module = params.get("modprobe_module")
    if guest_is_not_windows and module:
        session.cmd_output("modprobe %s" % module)
    if session:
        session.close()

    error.context("Add network devices through monitor cmd", logging.info)
    nic_name = 'hotadded'
    enable_msix_vectors = params.get("enable_msix_vectors")
    nic_info = vm.hotplug_nic(nic_model=pci_model, nic_name=nic_name,
                              netdst=netdst, nettype=nettype,
                              queues=params.get('queues'),
                              enable_msix_vectors=enable_msix_vectors)
    nic_mac = nic_info['mac']
    vm.params['nics'] += " %s" % nic_name
    vm.params['nic_model_%s' % nic_name] = nic_info['nic_model']

    # Only run dhclient if explicitly set and guest is not running Windows.
    # Most modern Linux guests run NetworkManager, and thus do not need this.
    if run_dhclient == "yes" and guest_is_not_windows:
        session_serial = vm.wait_for_serial_login(timeout=timeout)
        ifname = utils_net.get_linux_ifname(session, nic_mac)
        utils_net.restart_guest_network(session_serial, ifname)
        # Guest need to take quite a long time to set the ip addr, sleep a
        # while to wait for guest done.
        time.sleep(60)

    error.context("Disable the primary link of guest", logging.info)
    set_link(nic_name, up=False)

    error.context("Check if new interface gets ip address", logging.info)
    try:
        ip = vm.wait_for_get_address(nic_name)
    except virt_vm.VMIPAddressMissingError:
        raise error.TestFail("Could not get or verify ip address of nic")
    logging.info("Got the ip address of new nic: %s", ip)

    error.context("Ping guest's new ip from host", logging.info)
    s, o = utils_test.ping(ip, 10, timeout=15)
    if s != 0:
        raise error.TestFail("New nic failed ping test with output:\n %s" % o)

    error.context("Re-enabling the primary link", logging.info)
    set_link(nic_name, up=True)

    error.context("Migrate from source VM to Destination VM", logging.info)
    vm.migrate(mig_timeout, mig_protocol, mig_cancel_delay, env=env)

    error.context("Disable the primary link", logging.info)
    set_link(nic_name, up=False)

    error.context("Ping guest's new ip from host", logging.info)
    s, o = utils_test.ping(ip, 10, timeout=15)
    if s != 0:
        raise error.TestFail("New nic failed ping test with output:\n %s" % o)

    error.context("Re-enabling the primary link", logging.info)
    set_link(nic_name, up=True)

    error.context("Reboot guest and verify new nic works", logging.info)
    host_ip = utils_net.get_ip_address_by_interface(netdst)
    session = vm.reboot(session=session)
    status, output = utils_test.ping(dest=host_ip, count=100,
                                     timeout=240, session=session)
    if status != 0:
        raise error.TestFail("Fail to ping host form guest")
开发者ID:MiriamDeng,项目名称:tp-qemu,代码行数:101,代码来源:migration_after_nichotplug.py


注:本文中的virttest.utils_net.get_ip_address_by_interface函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。