class NetworkTest(Test):
    '''
    To test different types of pings
    '''

    def setUp(self):
        '''
        To check and install dependencies for the test
        '''
        smm = SoftwareManager()
        pkgs = ["ethtool", "net-tools"]
        detected_distro = distro.detect()
        if detected_distro.name == "Ubuntu":
            pkgs.extend(["openssh-client", "iputils-ping"])
        elif detected_distro.name == "SuSE":
            pkgs.extend(["openssh", "iputils"])
        else:
            pkgs.extend(["openssh-clients", "iputils"])
        for pkg in pkgs:
            if not smm.check_installed(pkg) and not smm.install(pkg):
                self.cancel("%s package is need to test" % pkg)
        interfaces = netifaces.interfaces()
        interface = self.params.get("interface")
        if interface not in interfaces:
            self.cancel("%s interface is not available" % interface)
        self.iface = interface
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        self.ip_config = self.params.get("ip_config", default=True)
        self.hbond = self.params.get("hbond", default=False)
        for root, dirct, files in os.walk("/root/.ssh"):
            for file in files:
                if file.startswith("avocado-master-root"):
                    path = os.path.join(root, file)
                    os.remove(path)
        local = LocalHost()
        if self.hbond:
            self.networkinterface = NetworkInterface(self.iface, local, if_type='Bond')
        else:
            self.networkinterface = NetworkInterface(self.iface, local)
        if self.ip_config:
            try:
                self.networkinterface.add_ipaddr(self.ipaddr, self.netmask)
                self.networkinterface.save(self.ipaddr, self.netmask)
            except Exception:
                self.networkinterface.save(self.ipaddr, self.netmask)
            self.networkinterface.bring_up()
        if not wait.wait_for(self.networkinterface.is_link_up, timeout=120):
            self.fail("Link up of interface is taking longer than 120 seconds")
        self.peer = self.params.get("peer_ip")
        if not self.peer:
            self.cancel("No peer provided")
        self.mtu = self.params.get("mtu", default=1500)
        self.peer_public_ip = self.params.get("peer_public_ip", default="")
        self.peer_user = self.params.get("peer_user", default="root")
        self.peer_password = self.params.get("peer_password", '*',
                                             default=None)
        if 'scp' or 'ssh' in str(self.name.name):
            self.session = Session(self.peer, user=self.peer_user,
                                   password=self.peer_password)
            if not self.session.connect():
                self.cancel("failed connecting to peer")
        self.remotehost = RemoteHost(self.peer, self.peer_user,
                                     password=self.peer_password)
        self.peer_interface = self.remotehost.get_interface_by_ipaddr(self.peer).name
        self.peer_networkinterface = NetworkInterface(self.peer_interface,
                                                      self.remotehost)
        self.remotehost_public = RemoteHost(self.peer_public_ip, self.peer_user,
                                            password=self.peer_password)
        self.peer_public_networkinterface = NetworkInterface(self.peer_interface,
                                                             self.remotehost_public)
        self.mtu = self.params.get("mtu", default=1500)
        self.mtu_set()
        if self.networkinterface.ping_check(self.peer, count=5) is not None:
            self.cancel("No connection to peer")

    def mtu_set(self):
        '''
        set mtu size
        '''
        if self.peer_networkinterface.set_mtu(self.mtu) is not None:
            self.cancel("Failed to set mtu in peer")
        if self.networkinterface.set_mtu(self.mtu) is not None:
            self.cancel("Failed to set mtu in host")

    def test_gro(self):
        '''
        Test GRO
        '''
        ro_type = "gro"
        ro_type_full = "generic-receive-offload"
        if not self.offload_state(ro_type_full):
            self.fail("Could not get state of %s" % ro_type)
        if self.offload_state(ro_type_full) == 'fixed':
            self.fail("Can not change the state of %s" % ro_type)
        self.offload_toggle_test(ro_type, ro_type_full)

    def test_gso(self):
        '''
        Test GSO
        '''
        ro_type = "gso"
        ro_type_full = "generic-segmentation-offload"
        if not self.offload_state(ro_type_full):
            self.fail("Could not get state of %s" % ro_type)
        if self.offload_state(ro_type_full) == 'fixed':
            self.fail("Can not change the state of %s" % ro_type)
        self.offload_toggle_test(ro_type, ro_type_full)

    def test_lro(self):
        '''
        Test LRO
        '''
        ro_type = "lro"
        ro_type_full = "large-receive-offload"
        path = '/sys/class/net/%s/device/uevent' % self.iface
        if os.path.exists(path):
            output = open(path, 'r').read()
            for line in output.splitlines():
                if "OF_NAME" in line:
                    if 'vnic' in line.split('=')[-1]:
                        self.cancel("Unsupported on vNIC")
        if not self.offload_state(ro_type_full):
            self.fail("Could not get state of %s" % ro_type)
        if self.offload_state(ro_type_full) == 'fixed':
            self.fail("Can not change the state of %s" % ro_type)
        self.offload_toggle_test(ro_type, ro_type_full)

    def test_tso(self):
        '''
        Test TSO
        '''
        ro_type = "tso"
        ro_type_full = "tcp-segmentation-offload"
        if not self.offload_state(ro_type_full):
            self.fail("Could not get state of %s" % ro_type)
        if self.offload_state(ro_type_full) == 'fixed':
            self.fail("Can not change the state of %s" % ro_type)
        self.offload_toggle_test(ro_type, ro_type_full)

    def test_ping(self):
        '''
        ping to peer machine
        '''
        if self.networkinterface.ping_check(self.peer, count=10) is not None:
            self.fail("ping test failed")

    def test_floodping(self):
        '''
        Flood ping to peer machine
        '''
        if self.networkinterface.ping_check(self.peer, count=500000,
                                            options='-f') is not None:
            self.fail("flood ping test failed")

    def test_ssh(self):
        '''
        Test ssh
        '''
        cmd = "echo hi"
        output = self.session.cmd(cmd)
        if not output.exit_status == 0:
            self.fail("unable to ssh into peer machine")

    def test_scp(self):
        '''
        Test scp
        '''
        process.run("dd if=/dev/zero of=/tmp/tempfile bs=1024000000 count=1",
                    shell=True)
        md_val1 = hashlib.md5(open('/tmp/tempfile', 'rb').read()).hexdigest()
        destination = "%s:/tmp" % self.peer
        output = self.session.copy_files('/tmp/tempfile', destination)
        if not output:
            self.fail("unable to copy into peer machine")

        source = "%s:/tmp/tempfile" % self.peer
        output = self.session.copy_files(source, '/tmp')
        if not output:
            self.fail("unable to copy from peer machine")

        md_val2 = hashlib.md5(open('/tmp/tempfile', 'rb').read()).hexdigest()
        if md_val1 != md_val2:
            self.fail("Test Failed")

    def test_jumbo_frame(self):
        '''
        Test jumbo frames
        '''
        if self.networkinterface.ping_check(self.peer, count=30,
                                            options='-i 0.1 -s %d'
                                            % (int(self.mtu) - 28)) is not None:
            self.fail("jumbo frame test failed")

    def test_statistics(self):
        '''
        Test Statistics
        '''
        rx_file = "/sys/class/net/%s/statistics/rx_packets" % self.iface
        tx_file = "/sys/class/net/%s/statistics/tx_packets" % self.iface
        rx_before = genio.read_file(rx_file)
        tx_before = genio.read_file(tx_file)
        self.networkinterface.ping_check(self.peer, count=500000, options='-f')
        rx_after = genio.read_file(rx_file)
        tx_after = genio.read_file(tx_file)
        if (rx_after <= rx_before) or (tx_after <= tx_before):
            self.log.debug("Before\nrx: %s tx: %s" % (rx_before, tx_before))
            self.log.debug("After\nrx: %s tx: %s" % (rx_after, tx_after))
            self.fail("Statistics not incremented properly")

    def mtu_set_back(self):
        '''
        Test set mtu back to 1500
        '''
        try:
            self.peer_networkinterface.set_mtu('1500')
        except Exception:
            self.peer_public_networkinterface.set_mtu('1500')
        if self.networkinterface.set_mtu('1500') is not None:
            self.cancel("Failed to set mtu in host")

    def offload_toggle_test(self, ro_type, ro_type_full):
        '''
        Check to toggle the LRO / GRO / GSO / TSO
        '''
        for state in ["off", "on"]:
            if not self.offload_state_change(ro_type,
                                             ro_type_full, state):
                self.fail("%s %s failed" % (ro_type, state))
            if self.networkinterface.ping_check(self.peer, count=500000,
                                                options='-f') is not None:
                self.fail("ping failed in %s %s" % (ro_type, state))

    def offload_state_change(self, ro_type, ro_type_full, state):
        '''
        Change the state of LRO / GRO / GSO / TSO to specified state
        '''
        cmd = "ethtool -K %s %s %s" % (self.iface, ro_type, state)
        if process.system(cmd, shell=True, ignore_status=True) != 0:
            return False
        if self.offload_state(ro_type_full) != state:
            return False
        return True

    def offload_state(self, ro_type_full):
        '''
        Return the state of LRO / GRO / GSO / TSO.
        If the state can not be changed, we return 'fixed'.
        If any other error, we return ''.
        '''
        cmd = "ethtool -k %s" % self.iface
        output = process.system_output(cmd, shell=True,
                                       ignore_status=True).decode("utf-8")
        for line in output.splitlines():
            if ro_type_full in line:
                if 'fixed' in line.split()[-1]:
                    return 'fixed'
                return line.split()[-1]
        return ''

    def test_promisc(self):
        '''
        promisc mode testing
        '''
        cmd = "ip link set %s promisc on" % self.iface
        if process.system(cmd, shell=True, ignore_status=True) != 0:
            self.fail("failed to enable promisc mode")
        self.networkinterface.ping_check(self.peer, count=100000, options='-f')
        cmd = "ip link set %s promisc off" % self.iface
        if process.system(cmd, shell=True, ignore_status=True) != 0:
            self.fail("failed to disable promisc mode")
        self.networkinterface.ping_check(self.peer, count=5)

    def tearDown(self):
        '''
        Remove the files created
        '''
        self.mtu_set_back()
        if 'scp' in str(self.name.name):
            process.run("rm -rf /tmp/tempfile")
            cmd = "rm -rf /tmp/tempfile"
            self.session.cmd(cmd)
        if self.ip_config:
            self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
            try:
                self.networkinterface.restore_from_backup()
            except Exception:
                self.networkinterface.remove_cfg_file()
                self.log.info("backup file not availbale, could not restore file.")
            if self.hbond:
                self.networkinterface.restore_slave_cfg_file()
        self.remotehost.remote_session.quit()
        self.remotehost_public.remote_session.quit()
        if 'scp' or 'ssh' in str(self.name.name):
            self.session.quit()
Пример #2
0
class Ethtool(Test):
    '''
    To test different types of pings
    '''

    def setUp(self):
        '''
        To check and install dependencies for the test
        '''
        smm = SoftwareManager()
        pkgs = ["ethtool", "net-tools"]
        detected_distro = distro.detect()
        if detected_distro.name == "Ubuntu":
            pkgs.extend(["iputils-ping"])
        elif detected_distro.name == "SuSE":
            pkgs.extend(["iputils"])
        else:
            pkgs.extend(["iputils"])
        for pkg in pkgs:
            if not smm.check_installed(pkg) and not smm.install(pkg):
                self.cancel("%s package is need to test" % pkg)
        interfaces = netifaces.interfaces()
        interface = self.params.get("interface")
        if interface not in interfaces:
            self.cancel("%s interface is not available" % interface)
        self.iface = interface
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        self.hbond = self.params.get("hbond", default=False)
        self.peer = self.params.get("peer_ip")
        self.tx = self.params.get("tx_channel", default='')
        self.rx = self.params.get("rx_channel", default='')
        self.other = self.params.get("other_channel", default='')
        self.combined = self.params.get("combined_channel", default='')
        if not self.peer:
            self.cancel("No peer provided")
        local = LocalHost()
        if self.iface[0:2] == 'ib':
            self.networkinterface = NetworkInterface(self.iface, local,
                                                     if_type='Infiniband')
        elif self.hbond:
            self.networkinterface = NetworkInterface(self.iface, local,
                                                     if_type='Bond')
        else:
            self.networkinterface = NetworkInterface(self.iface, local)
        try:
            self.networkinterface.add_ipaddr(self.ipaddr, self.netmask)
            self.networkinterface.save(self.ipaddr, self.netmask)
        except Exception:
            self.networkinterface.save(self.ipaddr, self.netmask)
        self.networkinterface.bring_up()
        if not wait.wait_for(self.networkinterface.is_link_up, timeout=120):
            self.cancel("Link up of interface is taking longer than 120s")
        if self.networkinterface.ping_check(self.peer, count=5) is not None:
            self.cancel("No connection to peer")
        self.args = self.params.get("arg", default='')
        self.elapse = self.params.get("action_elapse", default='')
        self.priv_test = self.params.get("privflag_test", default=False)
        if self.priv_test:
            cmd = "ethtool --show-priv-flags %s" % (self.iface)
            self.ret_val = process.run(cmd, shell=True, verbose=True,
                                       ignore_status=True)
            if self.ret_val.exit_status:
                self.cancel("Device Doesn't support Private flags")

    def interface_state_change(self, interface, state, status):
        '''
        Set the interface state specified, and return True if done.
        Returns False otherwise.
        '''
        cmd = "ip link set dev %s %s" % (interface, state)
        if state == "up":
            if process.system(cmd, shell=True, ignore_status=True) != 0:
                return False
            if not wait.wait_for(self.networkinterface.is_link_up,
                                 timeout=120):
                self.fail("Link up of interface is taking longer than 120s")
        else:
            if process.system(cmd, shell=True, ignore_status=True) != 0:
                return False
        if status != self.interface_link_status(interface):
            return False
        return True

    def interface_link_status(self, interface):
        '''
        Return the status of the interface link from ethtool.
        '''
        cmd = "ethtool %s" % interface
        for line in process.system_output(cmd, shell=True,
                                          ignore_status=True).decode("utf-8") \
                                                             .splitlines():
            if 'Link detected' in line:
                return line.split()[-1]
        return ''

    def test_ethtool(self):
        '''
        Test the ethtool args provided
        '''
        for state, status in zip(["down", "up"], ["no", "yes"]):
            if not self.interface_state_change(self.iface, state, status):
                self.fail("interface %s failed" % state)
            if self.args == "-L":
                value = [self.tx, self.rx, self.other, self.combined]
                self.param = ['tx', 'rx', 'other', 'combined']
                default = []
                cmd_l = "ethtool %s %s %s" % ("-l", self.iface, self.elapse)
                output = process.run(cmd_l, shell=True, verbose=True,
                                     ignore_status=True).stdout_text \
                                                        .splitlines()[2:6]
                for i in range(len(output)):
                    default.append(output[i].split(':')[1])
                    if 'n/a' in output[i]:
                        self.param[i], value[i], default[i] = '', '', ''
                self.default_set = default.copy()
                elements = all([elem == '' for elem in value])
                if elements:
                    self.log.warn("Cannot set device channel for null")
                else:
                    for i in range(4):
                        if default[i] != '':
                            default[i] = ['0', '1', int(default[i])//2,
                                          default[i], int(default[i])+1]
                            for j in range(5):
                                if value[i] != '':
                                    cmd = "ethtool %s %s %s %s" % (
                                            self.args, self.iface,
                                            self.param[i], default[i][j])
                                    result = process.run(cmd, shell=True,
                                                         verbose=True,
                                                         ignore_status=True)
                                    if state is 'up':
                                        if self.networkinterface.ping_check(
                                           self.peer, count=5) is not None:
                                            self.cancel("ping fail value %s \
                                                    to %s parameter" % (
                                                    default[i][j],
                                                    self.param[i]))
                                    err_channel = "no RX or TX channel"
                                    err_count = "count exceeds maximum"
                                    if result.exit_status != 0:
                                        if err_channel in result.stderr_text:
                                            self.log.info("Cannot set %s \
                                                    value on %s parameter" % (
                                                    default[i][j],
                                                    self.param[i]))
                                        elif err_count in result.stderr_text:
                                            self.log.info("Cannot set %s \
                                                    value on %s parameter" % (
                                                    default[i][j],
                                                    self.param[i]))
                                        else:
                                            self.fail("%s %s" % (
                                                self.args, result.stderr_text))
                    cmd = "ethtool %s %s %s %s %s %s %s %s %s %s" % (
                        self.args, self.iface, self.param[0], value[0],
                        self.param[1], value[1], self.param[2], value[2],
                        self.param[3], value[3])
                    ret = process.run(cmd, shell=True, verbose=True,
                                      ignore_status=True)
                    if ret.exit_status != 0:
                        self.fail("%s %s" % (self.args, ret.stderr_text))
            else:
                cmd = "ethtool %s %s %s" % (self.args, self.iface, self.elapse)
                ret = process.run(cmd, shell=True, verbose=True,
                                  ignore_status=True)
                if ret.exit_status != 0:
                    if "Operation not supported" in ret.stderr_text:
                        self.log.warn("%s failed" % self.args)
                    else:
                        self.fail("%s failed" % self.args)
        if not wait.wait_for(lambda: self.networkinterface.are_packets_lost(
                        self.peer, options=['-c 10000', '-f']), timeout=30):
            self.cancel("Packet recieved in Ping flood is not 100 percent \
                         after waiting for 30sec")
        if self.priv_test:
            self.ethtool_toggle_priv_flags()

    def ethtool_toggle_priv_flags(self):
        '''
        Toggle the priv flag settings of the driver.
        '''
        priv_pass = []
        priv_fail = []
        for oper in ('toggle', 'setback'):
            for line in self.ret_val.stdout_text.splitlines():
                if "off" in line:
                    val = "on"
                else:
                    val = "off"
                if "flags" not in line:
                    priv_flag = line.split(':')[0]
                    cmd = "ethtool --set-priv-flags %s \"%s\" %s" % \
                          (self.iface, priv_flag.rstrip(), val)
                    ret1 = process.run(cmd, shell=True, verbose=True,
                                       ignore_status=True)
                    if ret1.exit_status == 0 or 'supported' in \
                       ret1.stderr_text:
                        priv_pass.append(priv_flag.rstrip())
                    else:
                        priv_fail.append(priv_flag.rstrip())
            if self.networkinterface.ping_check(self.peer, count=500000,
                                                options='-f') is not None:
                self.fail("Ping failed oper = %s" % oper)
        if priv_fail:
            self.fail("Private flags could not be toggled: %s" %
                      ",".join(list(set(priv_fail))))

    def tearDown(self):
        '''
        Set the interface up at the end of test.
        '''
        if self.args == "-L":
            cmd = "ethtool %s %s %s %s %s %s %s %s %s %s" % (
                self.args, self.iface, self.param[0], self.default_set[0],
                self.param[1], self.default_set[1], self.param[2],
                self.default_set[2], self.param[3], self.default_set[3])
            ret = process.run(cmd, shell=True, verbose=True,
                              ignore_status=True)
            if ret.exit_status != 0:
                self.fail("%s %s" % (self.args, ret.stderr_text))
        self.interface_state_change(self.iface, "up", "yes")
        self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
        try:
            self.networkinterface.restore_from_backup()
        except Exception:
            self.networkinterface.remove_cfg_file()
            self.log.info("backup file not availbale, could not restore file.")
        if self.hbond:
            self.networkinterface.restore_slave_cfg_file()
class ReceiveMulticastTest(Test):
    '''
    check multicast receive
    using ping tool
    '''

    def setUp(self):
        '''
        To check and install dependencies for the test
        '''
        self.peer = self.params.get("peer_ip", default="")
        self.user = self.params.get("user_name", default="root")
        self.peer_password = self.params.get("peer_password",
                                             '*', default="None")
        interfaces = netifaces.interfaces()
        self.iface = self.params.get("interface", default="")
        if self.iface not in interfaces:
            self.cancel("%s interface is not available" % self.iface)
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        self.hbond = self.params.get("hbond", default=False)
        local = LocalHost()
        if self.hbond:
            self.networkinterface = NetworkInterface(self.iface, local,
                                                     if_type='Bond')
        else:
            self.networkinterface = NetworkInterface(self.iface, local)
        try:
            self.networkinterface.add_ipaddr(self.ipaddr, self.netmask)
            self.networkinterface.save(self.ipaddr, self.netmask)
        except Exception:
            self.networkinterface.save(self.ipaddr, self.netmask)
        self.networkinterface.bring_up()

        self.session = Session(self.peer, user=self.user,
                               password=self.peer_password)
        if not self.session.connect():
            self.cancel("failed connecting to peer")
        self.count = self.params.get("count", default="500000")
        smm = SoftwareManager()
        pkgs = ["net-tools"]
        detected_distro = distro.detect()
        if detected_distro.name == "Ubuntu":
            pkgs.extend(["openssh-client", "iputils-ping"])
        elif detected_distro.name == "SuSE":
            pkgs.extend(["openssh", "iputils"])
        else:
            pkgs.extend(["openssh-clients", "iputils"])
        for pkg in pkgs:
            if not smm.check_installed(pkg) and not smm.install(pkg):
                self.cancel("%s package is need to test" % pkg)
        if self.peer == "":
            self.cancel("peer ip should specify in input")
        cmd = "ip addr show  | grep %s" % self.peer
        output = self.session.cmd(cmd)
        result = ""
        result = result.join(output.stdout.decode("utf-8"))
        self.peerif = result.split()[-1]
        if self.peerif == "":
            self.cancel("unable to get peer interface")
        cmd = "ip -f inet -o addr show %s | awk '{print $4}' | cut -d / -f1"\
              % self.iface
        self.local_ip = process.system_output(cmd, shell=True).strip()
        if self.local_ip == "":
            self.cancel("unable to get local ip")

    def test_multicast(self):
        '''
        ping to peer machine
        '''
        cmd = "echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts"
        if process.system(cmd, shell=True, verbose=True,
                          ignore_status=True) != 0:
            self.fail("unable to set value to icmp_echo_ignore_broadcasts")
        cmd = "ip link set %s allmulticast on" % self.iface
        if process.system(cmd, shell=True, verbose=True,
                          ignore_status=True) != 0:
            self.fail("unable to set all mulicast option to test interface")
        cmd = "ip route add 224.0.0.0/4 dev %s" % self.peerif
        output = self.session.cmd(cmd)
        if not output.exit_status == 0:
            self.fail("Unable to add route for Peer interafce")
        cmd = "timeout 600 ping -I %s 224.0.0.1 -c %s -f" % (self.peerif,
                                                             self.count)
        output = self.session.cmd(cmd)
        if not output.exit_status == 0:
            self.fail("multicast test failed")

    def tearDown(self):
        '''
        delete multicast route and turn off multicast option
        '''
        cmd = "ip route del 224.0.0.0/4"
        output = self.session.cmd(cmd)
        if not output.exit_status == 0:
            self.log.info("Unable to delete multicast route added for peer")
        cmd = "echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts"
        if process.system(cmd, shell=True, verbose=True,
                          ignore_status=True) != 0:
            self.log.info("unable to unset all mulicast option")
        cmd = "ip link set %s allmulticast off" % self.iface
        if process.system(cmd, shell=True, verbose=True,
                          ignore_status=True) != 0:
            self.log.info("unable to unset all mulicast option")
        self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
        try:
            self.networkinterface.restore_from_backup()
        except Exception:
            self.networkinterface.remove_cfg_file()
            self.log.info("backup file not availbale, could not restore file.")
        if self.hbond:
            self.networkinterface.restore_slave_cfg_file()
        self.session.quit()
Пример #4
0
class Iperf(Test):
    """
    Iperf Test
    """
    def setUp(self):
        """
        To check and install dependencies for the test
        """
        self.peer_user = self.params.get("peer_user", default="root")
        self.peer_ip = self.params.get("peer_ip", default="")
        self.peer_public_ip = self.params.get("peer_public_ip", default="")
        self.peer_password = self.params.get("peer_password",
                                             '*',
                                             default=None)
        interfaces = netifaces.interfaces()
        self.iface = self.params.get("interface", default="")
        if self.iface not in interfaces:
            self.cancel("%s interface is not available" % self.iface)
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        self.hbond = self.params.get("hbond", default=False)
        localhost = LocalHost()
        if self.hbond:
            self.networkinterface = NetworkInterface(self.iface,
                                                     localhost,
                                                     if_type='Bond')
        else:
            self.networkinterface = NetworkInterface(self.iface, localhost)
        try:
            self.networkinterface.add_ipaddr(self.ipaddr, self.netmask)
            self.networkinterface.save(self.ipaddr, self.netmask)
        except Exception:
            self.networkinterface.save(self.ipaddr, self.netmask)
        self.networkinterface.bring_up()
        self.session = Session(self.peer_ip,
                               user=self.peer_user,
                               password=self.peer_password)
        if not self.session.connect():
            self.cancel("failed connecting to peer")
        smm = SoftwareManager()
        for pkg in ["gcc", "autoconf", "perl", "m4", "libtool", "gcc-c++"]:
            if not smm.check_installed(pkg) and not smm.install(pkg):
                self.cancel("%s package is need to test" % pkg)
            cmd = "%s install %s" % (smm.backend.base_command, pkg)
            output = self.session.cmd(cmd)
            if not output.exit_status == 0:
                self.cancel(
                    "unable to install the package %s on peer machine " % pkg)

        detected_distro = distro.detect()
        pkg = "nmap"
        if detected_distro.name == 'rhel':
            if not smm.check_installed(pkg) and not smm.install(pkg):
                self.cancel("%s package Can not install" % pkg)
        if detected_distro.name == "SuSE":
            self.nmap = os.path.join(self.teststmpdir, 'nmap')
            nmap_download = self.params.get("nmap_download",
                                            default="https:"
                                            "//nmap.org/dist/"
                                            "nmap-7.80.tar.bz2")
            tarball = self.fetch_asset(nmap_download)
            self.version = os.path.basename(tarball.split('.tar')[0])
            self.n_map = os.path.join(self.nmap, self.version)
            archive.extract(tarball, self.nmap)
            os.chdir(self.n_map)
            process.system('./configure ppc64le', shell=True)
            build.make(self.n_map)
            process.system('./nping/nping -h', shell=True)

        if self.peer_ip == "":
            self.cancel("%s peer machine is not available" % self.peer_ip)
        self.mtu = self.params.get("mtu", default=1500)
        self.remotehost = RemoteHost(self.peer_ip,
                                     self.peer_user,
                                     password=self.peer_password)
        self.peer_interface = self.remotehost.get_interface_by_ipaddr(
            self.peer_ip).name
        self.peer_networkinterface = NetworkInterface(self.peer_interface,
                                                      self.remotehost)
        self.remotehost_public = RemoteHost(self.peer_public_ip,
                                            self.peer_user,
                                            password=self.peer_password)
        self.peer_public_networkinterface = NetworkInterface(
            self.peer_interface, self.remotehost_public)
        if self.peer_networkinterface.set_mtu(self.mtu) is not None:
            self.cancel("Failed to set mtu in peer")
        if self.networkinterface.set_mtu(self.mtu) is not None:
            self.cancel("Failed to set mtu in host")
        self.iperf = os.path.join(self.teststmpdir, 'iperf')
        iperf_download = self.params.get("iperf_download",
                                         default="https:"
                                         "//sourceforge.net/projects/iperf2/"
                                         "files/iperf-2.0.13.tar.gz")
        tarball = self.fetch_asset(iperf_download, expire='7d')
        archive.extract(tarball, self.iperf)
        self.version = os.path.basename(tarball.split('.tar')[0])
        self.iperf_dir = os.path.join(self.iperf, self.version)
        destination = "%s:/tmp" % self.peer_ip
        output = self.session.copy_files(self.iperf_dir,
                                         destination,
                                         recursive=True)
        if not output:
            self.cancel("unable to copy the iperf into peer machine")
        cmd = "cd /tmp/%s;./configure ppc64le;make" % self.version
        output = self.session.cmd(cmd)
        if not output.exit_status == 0:
            self.cancel("Unable to compile Iperf into peer machine")
        self.iperf_run = str(self.params.get("IPERF_SERVER_RUN", default=0))
        if self.iperf_run == '1':
            cmd = "/tmp/%s/src/iperf -s" % self.version
            cmd = self.session.get_raw_ssh_command(cmd)
            self.obj = SubProcess(cmd)
            self.obj.start()
        os.chdir(self.iperf_dir)
        process.system('./configure', shell=True)
        build.make(self.iperf_dir)
        self.iperf = os.path.join(self.iperf_dir, 'src')
        self.expected_tp = self.params.get("EXPECTED_THROUGHPUT", default="85")

    def nping(self):
        """
        Run nping test with tcp packets
        """
        detected_distro = distro.detect()
        if detected_distro.name == "SuSE":
            os.chdir(self.n_map)
            cmd = "./nping/nping --tcp %s -c 10" % self.peer_ip
            return process.run(cmd, verbose=False, shell=True)
        else:
            cmd = "nping --tcp %s -c 10" % self.peer_ip
            return process.run(cmd, verbose=False, shell=True)

    def test(self):
        """
        Test run is a One way throughput test. In this test, we have one host
        transmitting (or receiving) data from a client. This transmit large
        messages using multiple threads or processes.
        """
        speed = int(read_file("/sys/class/net/%s/speed" % self.iface))
        os.chdir(self.iperf)
        cmd = "./iperf -c %s" % self.peer_ip
        result = process.run(cmd, shell=True, ignore_status=True)
        nping_result = self.nping()
        if result.exit_status:
            self.fail("FAIL: Iperf Run failed")
        for line in result.stdout.decode("utf-8").splitlines():
            if 'local {}'.format(self.ipaddr) in line:
                id = line[3]
        for line in result.stdout.decode("utf-8").splitlines():
            if id in line and 'Mbits/sec' in line:
                tput = int(line.split()[6])
            elif id in line and 'Gbits/sec' in line:
                tput = int(float(line.split()[6])) * 1000
        if tput < (int(self.expected_tp) * speed) / 100:
            self.fail(
                "FAIL: Throughput Actual - %s%%, Expected - %s%%"
                ", Throughput Actual value - %s " %
                ((tput * 100) / speed, self.expected_tp, str(tput) + 'Mb/sec'))
        for line in nping_result.stdout.decode("utf-8").splitlines():
            if 'Raw packets' in line:
                lost = int(line.split("|")[2].split(" ")[2]) * 10
                if lost > 60:
                    self.fail("FAIL: Ping fails after iperf test")

    def tearDown(self):
        """
        Killing Iperf process in peer machine
        """
        cmd = "pkill iperf; rm -rf /tmp/%s" % self.version
        output = self.session.cmd(cmd)
        if not output.exit_status == 0:
            self.fail("Either the ssh to peer machine machine\
                       failed or iperf process was not killed")
        self.obj.stop()
        if self.networkinterface.set_mtu('1500') is not None:
            self.cancel("Failed to set mtu in host")
        try:
            self.peer_networkinterface.set_mtu('1500')
        except Exception:
            self.peer_public_networkinterface.set_mtu('1500')
        self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
        try:
            self.networkinterface.restore_from_backup()
        except Exception:
            self.networkinterface.remove_cfg_file()
            self.log.info("backup file not availbale, could not restore file.")
        if self.hbond:
            self.networkinterface.restore_slave_cfg_file()
        self.remotehost.remote_session.quit()
        self.remotehost_public.remote_session.quit()
        self.session.quit()
Пример #5
0
class TcpdumpTest(Test):
    """
    Test the tcpdump for specified interface.
    """

    def setUp(self):
        """
        Set up.
        """
        self.iface = self.params.get("interface", default="")
        self.count = self.params.get("count", default="500")
        self.peer_ip = self.params.get("peer_ip", default="")
        self.peer_public_ip = self.params.get("peer_public_ip", default="")
        self.drop = self.params.get("drop_accepted", default="10")
        self.host_ip = self.params.get("host_ip", default="")
        self.option = self.params.get("option", default='')
        self.hbond = self.params.get("hbond", default=False)
        # Check if interface exists in the system
        self.networkinterface = None
        interfaces = netifaces.interfaces()
        if not self.iface:
            self.cancel("Please specify interface to be used")
        if self.iface not in interfaces:
            self.cancel("%s interface is not available" % self.iface)
        if not self.peer_ip:
            self.cancel("peer ip should specify in input")
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        localhost = LocalHost()
        if self.hbond:
            self.networkinterface = NetworkInterface(self.iface, localhost,
                                                     if_type='Bond')
        else:
            self.networkinterface = NetworkInterface(self.iface, localhost)
        try:
            self.networkinterface.add_ipaddr(self.ipaddr, self.netmask)
            self.networkinterface.save(self.ipaddr, self.netmask)
        except Exception:
            self.networkinterface.save(self.ipaddr, self.netmask)
        self.networkinterface.bring_up()
        if not wait.wait_for(self.networkinterface.is_link_up, timeout=120):
            self.cancel("Link up of interface is taking longer than 120 seconds")
        self.peer_user = self.params.get("peer_user", default="root")
        self.peer_password = self.params.get("peer_password", '*',
                                             default="None")
        self.timeout = self.params.get("TIMEOUT", default="600")
        self.mtu = self.params.get("mtu", default=1500)
        self.mtu_timeout = self.params.get("mtu_timeout", default=30)
        self.remotehost = RemoteHost(self.peer_ip, self.peer_user,
                                     password=self.peer_password)
        self.peer_interface = self.remotehost.get_interface_by_ipaddr(self.peer_ip).name
        self.peer_networkinterface = NetworkInterface(self.peer_interface,
                                                      self.remotehost)
        self.remotehost_public = RemoteHost(self.peer_public_ip, self.peer_user,
                                            password=self.peer_password)
        self.peer_public_networkinterface = NetworkInterface(self.peer_interface,
                                                             self.remotehost_public)
        if self.peer_networkinterface.set_mtu(self.mtu, timeout=self.mtu_timeout) is not None:
            self.cancel("Failed to set mtu in peer")
        if self.networkinterface.set_mtu(self.mtu, timeout=self.mtu_timeout) is not None:
            self.cancel("Failed to set mtu in host")

        # Install needed packages
        smm = SoftwareManager()
        detected_distro = distro.detect()
        pkgs = ['tcpdump', 'flex', 'bison', 'gcc', 'gcc-c++', 'nmap']
        for pkg in pkgs:
            if not smm.check_installed(pkg) and not smm.install(pkg):
                self.cancel("%s package Can not install" % pkg)
        if detected_distro.name == "SuSE":
            self.nmap = os.path.join(self.teststmpdir, 'nmap')
            nmap_download = self.params.get("nmap_download", default="https:"
                                            "//nmap.org/dist/"
                                            "nmap-7.80.tar.bz2")
            tarball = self.fetch_asset(nmap_download)
            self.version = os.path.basename(tarball.split('.tar')[0])
            self.n_map = os.path.join(self.nmap, self.version)
            archive.extract(tarball, self.nmap)
            os.chdir(self.n_map)
            process.system('./configure ppc64le', shell=True)
            build.make(self.n_map)
            process.system('./nping/nping -h', shell=True)

    def test(self):
        """
        Performs the tcpdump test.
        """
        cmd = "ping -I %s %s -c %s" % (self.iface, self.peer_ip, self.count)
        output_file = os.path.join(self.outputdir, 'tcpdump')
        if self.option in ('tcp', 'udp', 'icmp'):
            obj = self.nping(self.option)
            obj.start()
        else:
            obj = process.SubProcess(cmd, verbose=False, shell=True)
            obj.start()
        cmd = "timeout %s tcpdump -i %s -n -c %s" % (self.timeout, self.iface, self.count)
        if self.option in ('host', 'src'):
            cmd = "%s %s %s" % (cmd, self.option, self.host_ip)
        elif self.option == "dst":
            cmd = "%s %s %s" % (cmd, self.option, self.peer_ip)
        else:
            cmd = "%s %s" % (cmd, self.option)
        cmd = "%s -w '%s'" % (cmd, output_file)
        for line in process.run(cmd, shell=True,
                                ignore_status=True).stderr.decode("utf-8") \
                                                   .splitlines():
            if "packets dropped by kernel" in line:
                self.log.info(line)
                if int(line[0]) >= (int(self.drop) * int(self.count) / 100):
                    self.fail("%s, more than %s percent" % (line, self.drop))
        obj.stop()

    def nping(self, param):
        """
        perform nping
        """
        if self.count <= 10:
            nping_count = round((200 * int(self.count)) / 100)
        else:
            nping_count = round((120 * int(self.count)) / 100)
        detected_distro = distro.detect()
        if detected_distro.name == "SuSE":
            cmd = "./nping/nping --%s %s -c %s" % (param,
                                                   self.peer_ip, nping_count)
            return process.SubProcess(cmd, verbose=False, shell=True)
        else:
            cmd = "nping --%s %s -c %s" % (param, self.peer_ip, nping_count)
            return process.SubProcess(cmd, verbose=False, shell=True)

    def tearDown(self):
        '''
        unset ip for host interface
        '''
        if self.networkinterface:
            if self.networkinterface.set_mtu('1500', timeout=self.mtu_timeout) is not None:
                self.cancel("Failed to set mtu in host")
            try:
                self.peer_networkinterface.set_mtu('1500', timeout=self.mtu_timeout)
            except Exception:
                self.peer_public_networkinterface.set_mtu('1500', timeout=self.mtu_timeout)
            self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
            try:
                self.networkinterface.restore_from_backup()
            except Exception:
                self.networkinterface.remove_cfg_file()
                self.log.info("backup file not availbale, could not restore file.")
            if self.hbond:
                self.networkinterface.restore_slave_cfg_file()
            self.remotehost.remote_session.quit()
            self.remotehost_public.remote_session.quit()
Пример #6
0
class Bridging(Test):
    '''
    Test bridge interface
    '''
    def check_failure(self, cmd):
        if process.system(cmd, sudo=True, shell=True, ignore_status=True):
            self.fail("Command %s failed" % cmd)

    def setUp(self):
        self.host_interfaces = self.params.get("interfaces",
                                               default="").split(" ")
        if not self.host_interfaces:
            self.cancel("User should specify host interface/s")

        if self.host_interfaces[0:2] == 'ib':
            self.cancel("Network Bridge is not supported for IB")

        interfaces = netifaces.interfaces()
        for host_interface in self.host_interfaces:
            if host_interface not in interfaces:
                self.cancel("Interface is not available")

        self.peer_ip = self.params.get("peer_ip", default=None)
        if not self.peer_ip:
            self.cancel("User should specify peer IP")
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        self.bridge_interface = self.params.get("bridge_interface",
                                                default="br0")
        local = LocalHost()
        self.networkinterface = NetworkInterface(self.bridge_interface,
                                                 local,
                                                 if_type="Bridge")

    def test_bridge_create(self):
        '''
        Set up the ethernet bridge configuration in the linux kernel
        '''
        detected_distro = distro.detect()
        net_path = 'network-scripts'
        if detected_distro.name == "SuSE":
            net_path = 'network'
        if os.path.exists('/etc/sysconfig/%s/ifcfg-%s' %
                          (net_path, self.bridge_interface)):
            self.networkinterface.remove_cfg_file()
            self.check_failure('ip link del %s' % self.bridge_interface)
        self.check_failure('ip link add dev %s type bridge' %
                           self.bridge_interface)
        check_flag = False
        cmd = 'ip -d link show %s' % self.bridge_interface
        check_br = process.system_output(cmd, verbose=True,
                                         ignore_status=True).decode("utf-8")
        for line in check_br.splitlines():
            if line.find('bridge'):
                check_flag = True
        if not check_flag:
            self.fail('Bridge interface is not created')
        for host_interface in self.host_interfaces:
            self.check_failure('ip link set %s master %s' %
                               (host_interface, self.bridge_interface))
            self.check_failure('ip addr flush dev %s' % host_interface)

    def test_bridge_run(self):
        '''
        run bridge test
        '''
        try:
            self.networkinterface.add_ipaddr(self.ipaddr, self.netmask)
            self.networkinterface.save(self.ipaddr, self.netmask)
        except Exception:
            self.networkinterface.save(self.ipaddr, self.netmask)
        self.networkinterface.bring_up()
        if self.networkinterface.ping_check(self.peer_ip, count=5) is not None:
            self.fail('Ping using bridge failed')
        self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)

    def test_bridge_delete(self):
        '''
        Set to original state
        '''
        self.check_failure('ip link del dev %s' % self.bridge_interface)
        try:
            self.networkinterface.restore_from_backup()
        except Exception:
            self.networkinterface.remove_cfg_file()
class Ethtool(Test):
    '''
    To test different types of pings
    '''
    def setUp(self):
        '''
        To check and install dependencies for the test
        '''
        smm = SoftwareManager()
        pkgs = ["ethtool", "net-tools"]
        detected_distro = distro.detect()
        if detected_distro.name == "Ubuntu":
            pkgs.extend(["iputils-ping"])
        elif detected_distro.name == "SuSE":
            pkgs.extend(["iputils"])
        else:
            pkgs.extend(["iputils"])
        for pkg in pkgs:
            if not smm.check_installed(pkg) and not smm.install(pkg):
                self.cancel("%s package is need to test" % pkg)
        interfaces = netifaces.interfaces()
        interface = self.params.get("interface")
        if interface not in interfaces:
            self.cancel("%s interface is not available" % interface)
        self.iface = interface
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        self.hbond = self.params.get("hbond", default=False)
        self.peer = self.params.get("peer_ip")
        if not self.peer:
            self.cancel("No peer provided")
        local = LocalHost()
        if self.iface[0:2] == 'ib':
            self.networkinterface = NetworkInterface(self.iface,
                                                     local,
                                                     if_type='Infiniband')
        elif self.hbond:
            self.networkinterface = NetworkInterface(self.iface,
                                                     local,
                                                     if_type='Bond')
        else:
            self.networkinterface = NetworkInterface(self.iface, local)
        try:
            self.networkinterface.add_ipaddr(self.ipaddr, self.netmask)
            self.networkinterface.save(self.ipaddr, self.netmask)
        except Exception:
            self.networkinterface.save(self.ipaddr, self.netmask)
        self.networkinterface.bring_up()
        if not wait.wait_for(self.networkinterface.is_link_up, timeout=120):
            self.cancel("Link up of interface is taking longer than 120s")
        if self.networkinterface.ping_check(self.peer, count=5) is not None:
            self.cancel("No connection to peer")
        self.args = self.params.get("arg", default='')
        self.elapse = self.params.get("action_elapse", default='')
        self.priv_test = self.params.get("privflag_test", default=False)
        if self.priv_test:
            cmd = "ethtool --show-priv-flags %s" % (self.iface)
            self.ret_val = process.run(cmd,
                                       shell=True,
                                       verbose=True,
                                       ignore_status=True)
            if self.ret_val.exit_status:
                self.cancel("Device Doesn't support Private flags")

    def interface_state_change(self, interface, state, status):
        '''
        Set the interface state specified, and return True if done.
        Returns False otherwise.
        '''
        cmd = "ip link set dev %s %s" % (interface, state)
        if state == "up":
            if process.system(cmd, shell=True, ignore_status=True) != 0:
                return False
            if not wait.wait_for(self.networkinterface.is_link_up,
                                 timeout=120):
                self.fail("Link up of interface is taking longer than 120s")
        else:
            if process.system(cmd, shell=True, ignore_status=True) != 0:
                return False
        if status != self.interface_link_status(interface):
            return False
        return True

    def interface_link_status(self, interface):
        '''
        Return the status of the interface link from ethtool.
        '''
        cmd = "ethtool %s" % interface
        for line in process.system_output(cmd, shell=True,
                                          ignore_status=True).decode("utf-8") \
                                                             .splitlines():
            if 'Link detected' in line:
                return line.split()[-1]
        return ''

    def test_ethtool(self):
        '''
        Test the ethtool args provided
        '''
        for state, status in zip(["down", "up"], ["no", "yes"]):
            if not self.interface_state_change(self.iface, state, status):
                self.fail("interface %s failed" % state)
            cmd = "ethtool %s %s %s" % (self.args, self.iface, self.elapse)
            ret = process.run(cmd,
                              shell=True,
                              verbose=True,
                              ignore_status=True)
            if ret.exit_status != 0:
                if "Operation not supported" in ret.stderr_text:
                    self.log.warn("%s failed" % self.args)
                else:
                    self.fail("failed")
        if self.networkinterface.ping_check(self.peer,
                                            count=10000,
                                            options='-f') is not None:
            self.fail("flood ping test failed")
        if self.priv_test:
            self.ethtool_toggle_priv_flags()

    def ethtool_toggle_priv_flags(self):
        '''
        Toggle the priv flag settings of the driver.
        '''
        priv_pass = []
        priv_fail = []
        for oper in ('toggle', 'setback'):
            for line in self.ret_val.stdout_text.splitlines():
                if "off" in line:
                    val = "on"
                else:
                    val = "off"
                if "flags" not in line:
                    priv_flag = line.split(':')[0]
                    cmd = "ethtool --set-priv-flags %s \"%s\" %s" % \
                          (self.iface, priv_flag.rstrip(), val)
                    ret1 = process.run(cmd,
                                       shell=True,
                                       verbose=True,
                                       ignore_status=True)
                    if ret1.exit_status == 0 or 'supported' in \
                       ret1.stderr_text:
                        priv_pass.append(priv_flag.rstrip())
                    else:
                        priv_fail.append(priv_flag.rstrip())
            if self.networkinterface.ping_check(self.peer,
                                                count=500000,
                                                options='-f') is not None:
                self.fail("Ping failed oper = %s" % oper)
        if priv_fail:
            self.fail("Private flags could not be toggled: %s" %
                      ",".join(list(set(priv_fail))))

    def tearDown(self):
        '''
        Set the interface up at the end of test.
        '''
        self.interface_state_change(self.iface, "up", "yes")
        self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
        try:
            self.networkinterface.restore_from_backup()
        except Exception:
            self.networkinterface.remove_cfg_file()
            self.log.info("backup file not availbale, could not restore file.")
        if self.hbond:
            self.networkinterface.restore_slave_cfg_file()