def test_hmcfailover(self):
     '''
     Triggers Failover for the Network virtualized
     device
     '''
     original = self.get_active_device_logport(self.slot_num[0])
     for _ in range(self.count):
         before = self.get_active_device_logport(self.slot_num[0])
         self.trigger_failover(
             self.get_backing_device_logport(self.slot_num[0]))
         time.sleep(10)
         after = self.get_active_device_logport(self.slot_num[0])
         self.log.debug("Active backing device: %s", after)
         if before == after:
             self.fail("No failover happened")
         device = self.find_device(self.mac_id[0])
         networkinterface = NetworkInterface(device, self.local)
         if networkinterface.ping_check(self.peer_ip[0],
                                        count=5) is not None:
             self.fail("Failover has affected Network connectivity")
     if original != self.get_active_device_logport(self.slot_num[0]):
         self.trigger_failover(original)
     if original != self.get_active_device_logport(self.slot_num[0]):
         self.log.warn("Fail: Activating Initial backing dev %s" % original)
     self.check_dmesg_error()
 def test_vnic_dlpar(self):
     '''
     Perform vNIC device hot add and hot remove using drmgr command
     '''
     for slot_no, device_ip, netmask, mac, peer_ip in zip(
             self.slot_num, self.device_ip, self.netmask, self.mac_id,
             self.peer_ip):
         self.update_backing_devices(slot_no)
         dev_id = self.find_device_id(mac)
         device_name = self.find_device(mac)
         slot = self.find_virtual_slot(dev_id)
         if slot:
             try:
                 for _ in range(self.num_of_dlpar):
                     self.drmgr_vnic_dlpar('-r', slot)
                     self.drmgr_vnic_dlpar('-a', slot)
                     self.wait_intrerface(device_name)
             except CmdError as details:
                 self.log.debug(str(details))
                 self.fail("dlpar operation did not complete")
             device = self.find_device(mac)
             networkinterface = NetworkInterface(device, self.local)
             try:
                 networkinterface.add_ipaddr(device_ip, netmask)
             except Exception:
                 networkinterface.save(device_ip, netmask)
             if not wait.wait_for(networkinterface.is_link_up, timeout=120):
                 self.fail("Unable to bring up the link on the Network \
                           virtualized device")
             if networkinterface.ping_check(peer_ip, count=5) is not None:
                 self.fail("dlpar has affected Network connectivity")
         else:
             self.fail("slot not found")
     self.check_dmesg_error()
 def test_clientfailover(self):
     '''
     Performs Client initiated failover for Network virtualized
     device
     '''
     device_id = self.find_device_id(self.mac_id[0])
     try:
         for _ in range(self.count):
             for val in range(int(self.backing_dev_count())):
                 self.log.info(
                     "Performing Client initiated\
                               failover - Attempt %s", int(val + 1))
                 genio.write_file_or_fail(
                     "/sys/devices/vio/%s/failover" % device_id, "1")
                 time.sleep(10)
                 self.log.info("Running a ping test to check if failover \
                                 affected Network connectivity")
                 device = self.find_device(self.mac_id[0])
                 networkinterface = NetworkInterface(device, self.local)
                 if networkinterface.ping_check(self.peer_ip[0],
                                                count=5,
                                                options="-w50") is not None:
                     self.fail("Ping test failed. Network virtualized \
                                failover has affected Network connectivity")
     except CmdError as details:
         self.log.debug(str(details))
         self.fail("Client initiated Failover for Network virtualized \
                   device has failed")
     self.check_dmesg_error()
 def test_vnic_auto_failover(self):
     '''
     Set the priority for vNIC active and backing devices and check if autofailover works
     '''
     if len(self.backing_adapter) >= 2:
         for _ in range(self.count):
             self.update_backing_devices(self.slot_num[0])
             backing_logport = self.get_backing_device_logport(
                 self.slot_num[0])
             active_logport = self.get_active_device_logport(
                 self.slot_num[0])
             if self.enable_auto_failover():
                 if not self.change_failover_priority(backing_logport, '1'):
                     self.fail(
                         "Fail to change the priority for backing device %s",
                         backing_logport)
                 if not self.change_failover_priority(
                         active_logport, '100'):
                     self.fail(
                         "Fail to change the priority for active device %s",
                         active_logport)
                 time.sleep(10)
                 if backing_logport != self.get_active_device_logport(
                         self.slot_num[0]):
                     self.fail("Auto failover of backing device failed")
                 device = self.find_device(self.mac_id[0])
                 networkinterface = NetworkInterface(device, self.local)
                 if networkinterface.ping_check(self.peer_ip[0],
                                                count=5) is not None:
                     self.fail("Auto failover has effected connectivity")
             else:
                 self.fail("Could not enable auto failover")
     else:
         self.cancel("Provide more backing device, only 1 given")
     self.check_dmesg_error()
Пример #5
0
    def test_add_migratable_sriov(self):
        '''
        test to create Migratable sriov device
        '''
        if not self.migratable:
            self.cancel("Test unsupported")

        for slot, port, mac, ipaddr, netmask, peer_ip in zip(self.sriov_adapter,
                                                             self.sriov_port,
                                                             self.mac_id, self.ipaddr,
                                                             self.netmask, self.peer_ip):

            self.device_add_remove(slot, port, mac, '', 'add')
            if not self.list_device(mac):
                self.fail(
                    "failed to list Migratable logical device after add operation")
            bond_device = self.get_hnv_bond(mac)
            if bond_device:
                ret = process.run('nmcli c mod id %s ipv4.method manual ipv4.addres %s/%s' %
                                  (bond_device, ipaddr, self.prefix), ignore_status=True)
                if ret.exit_status:
                    self.fail("nmcli ip configuration for hnv bond fail with %s"
                              % (ret.exit_status))
                ret = process.run('nmcli c up %s' %
                                  bond_device, ignore_status=True)
                if ret.exit_status:
                    self.fail("hnv bond ip bring up fail with %s"
                              % (ret.exit_status))
                networkinterface = NetworkInterface(bond_device, self.local)
                if networkinterface.ping_check(peer_ip, count=5) is not None:
                    self.fail("ping check failed for hnv bond device")
            else:
                self.fail("failed to create hnv bond device")
Пример #6
0
    def test_rmdev_viosfailover(self):
        '''
        using mrdev and mkdev command to check vios failover works
        '''

        self.session = Session(self.vios_ip,
                               user=self.vios_user,
                               password=self.vios_pwd)
        if not wait.wait_for(self.session.connect, timeout=30):
            self.fail("Failed connecting to VIOS")

        cmd = "ioscli lsmap -all -vnic -cpid %s" % self.lpar_id
        vnic_servers = self.session.cmd(cmd).stdout_text.splitlines()
        device = self.find_device(self.mac_id[0])
        temp_idx = vnic_servers.index("Client device name:" + device)
        vnic_server = vnic_servers[temp_idx - 5].split()[0]

        cmd = "ioscli lsmap -vnic -vadapter %s" % vnic_server
        output = self.session.cmd(cmd)

        vnic_backing_device = None
        for line in output.stdout_text.splitlines():
            if 'Backing device' in line:
                vnic_backing_device = line.split(':')[-1]

        before = self.get_active_device_logport(self.slot_num[0])
        self.log.debug("Active backing device before : %s", before)

        self.validate_vios_command('rmdev -l %s' % vnic_server, 'Defined')
        if vnic_backing_device:
            self.validate_vios_command('rmdev -l %s' % vnic_backing_device,
                                       'Defined')

        time.sleep(10)

        for backing_dev in self.backing_dev_list().splitlines():
            if backing_dev.startswith('%s,' % self.slot_num[0]):
                backing_dev = backing_dev.strip('%s,"' % self.slot_num[0])
                if 'Powered Off' not in backing_dev:
                    self.fail("Failover did not occur")

        time.sleep(60)

        if vnic_backing_device:
            self.validate_vios_command('mkdev -l %s' % vnic_backing_device,
                                       'Available')
        self.validate_vios_command('mkdev -l %s' % vnic_server, 'Available')

        networkinterface = NetworkInterface(device, self.local)
        if networkinterface.ping_check(self.peer_ip[0], count=5) is not None:
            self.fail("Ping test failed. Network virtualized \
                      vios failover has affected Network connectivity")
        self.check_dmesg_error()
Пример #7
0
 def test_bridge_run(self):
     '''
     run bridge test
     '''
     local = LocalHost()
     networkinterface = NetworkInterface(self.bridge_interface, local,
                                         if_type="Bridge")
     networkinterface.add_ipaddr(self.ipaddr, self.netmask)
     networkinterface.bring_up()
     networkinterface.save(self.ipaddr, self.netmask)
     if networkinterface.ping_check(self.peer_ip, count=5) is not None:
         self.fail('Ping using bridge failed')
     networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
Пример #8
0
 def test_disable_enable_dev(self):
     '''
     Test if disabling and enabling of an adapter works
     '''
     self.disable_enable_dev('d')
     self.is_disabled_enabled_dev('1')
     self.disable_enable_dev('e')
     self.is_disabled_enabled_dev('0')
     device = self.find_device(self.mac_id[0])
     networkinterface = NetworkInterface(device, self.local)
     wait.wait_for(networkinterface.is_link_up, timeout=60)
     if networkinterface.ping_check(self.peer_ip[0], count=5) is not None:
         self.fail("Enabling and disabling of the interface has affected network connectivity")
     self.check_dmesg_error()
    def test_rmdev_viosfailover(self):
        '''
        using mrdev and mkdev command to check vios failover works
        '''

        self.session = Session(self.vios_ip,
                               user=self.vios_user,
                               password=self.vios_pwd)
        if not self.session.connect():
            self.fail("Failed connecting to VIOS")

        cmd = "ioscli lsmap -all -vnic -cpid %s" % self.lpar_id
        vnic_server = self.session.cmd(
            cmd).stdout_text.splitlines()[2].split()[0]

        cmd = "ioscli lsmap -vnic -vadapter %s" % vnic_server
        output = self.session.cmd(cmd)

        vnic_backing_device = None
        for line in output.stdout_text.splitlines():
            if 'Backing device' in line:
                vnic_backing_device = line.split(':')[-1]

        before = self.get_active_device_logport(self.slot_num[0])
        self.log.debug("Active backing device before : %s", before)

        self.validate_vios_command('rmdev -l %s' % vnic_server, 'Defined')
        if vnic_backing_device:
            self.validate_vios_command('rmdev -l %s' % vnic_backing_device,
                                       'Defined')

        after = self.get_active_device_logport(self.slot_num[0])
        self.log.debug("Active backing device after: %s", after)

        if before == after:
            self.fail("failover not occour")
        time.sleep(20)

        if vnic_backing_device:
            self.validate_vios_command('mkdev -l %s' % vnic_backing_device,
                                       'Available')
        self.validate_vios_command('mkdev -l %s' % vnic_server, 'Available')

        device = self.find_device(self.mac_id[0])
        networkinterface = NetworkInterface(device, self.local)
        if networkinterface.ping_check(self.peer_ip[0], count=5) is not None:
            self.fail("Ping test failed. Network virtualized \
                      vios failover has affected Network connectivity")
        self.check_dmesg_error()
Пример #10
0
 def net_recovery_check():
     """
     Checks if the network adapter fuctionality like ping/link_state,
     after adapter added back.
     Returns True on propper Recovery, False if not.
     """
     self.log.info("entering the net recovery check")
     local = LocalHost()
     iface = pci.get_interfaces_in_pci_address(pci_addr, 'net')
     networkinterface = NetworkInterface(iface[0], local)
     if wait.wait_for(networkinterface.is_link_up, timeout=120):
         if networkinterface.ping_check(self.peer_ip, count=5) is None:
             self.log.info("inteface is up and pinging")
             return True
     return False
 def test_add_logical_device(self):
     '''
     test to create logical sriov device
     '''
     for slot, port, mac, ipaddr, netmask, peer_ip in zip(
             self.sriov_adapter, self.sriov_port, self.mac_id, self.ipaddr,
             self.netmask, self.peer_ip):
         self.device_add_remove(slot, port, mac, '', 'add')
         if not self.list_device(mac):
             self.fail("failed to list logical device after add operation")
         device = self.find_device(mac)
         networkinterface = NetworkInterface(device, self.local)
         networkinterface.add_ipaddr(ipaddr, netmask)
         networkinterface.bring_up()
         if networkinterface.ping_check(peer_ip, count=5) is not None:
             self.fail("ping check failed")
Пример #12
0
    def test_vnic_hmc_dlpar(self):
        """
        Perform vNIC device hot add and hot remove
        """
        for slot_no, device_ip, netmask, mac, peer_ip, sriov_port, adapter_id in zip(
                self.slot_num, self.device_ip, self.netmask, self.mac_id,
                self.peer_ip, self.sriov_port, self.backing_adapter_id):
            self.update_backing_devices(slot_no)
            device_name = self.find_device(mac)
            networkinterface = NetworkInterface(device_name, self.local)
            count = 0
            self.log.info("Preforming DLPAR on %s" % device_name)
            for _ in range(self.num_of_dlpar):
                self.log.info("DLPAR iteration #%d" % count)
                num_backingdevs = self.backing_dev_count_w_slot_num(slot_no)

                self.device_add_remove(slot_no, '', '', '', 'remove')
                if networkinterface.is_available():
                    self.fail("DLPAR remove did not remove interface")

                self.device_add_remove(slot_no, mac, sriov_port, adapter_id,
                                       'add')
                for c in range(1, num_backingdevs):
                    self.backing_dev_add_remove('add', c)
                    self.wait_interface(device_name)

                try:
                    networkinterface.add_ipaddr(device_ip, netmask)
                except Exception:
                    networkinterface.save(device_ip, netmask)
                    networkinterface.add_ipaddr(device_ip, netmask)
                networkinterface.bring_up()

                if not wait.wait_for(networkinterface.is_link_up, timeout=120):
                    self.fail(
                        "Unable to bring up the link on the Network virtualized device"
                    )

                time.sleep(5)

                if networkinterface.ping_check(peer_ip, count=5) is not None:
                    self.fail("dlpar has affected Network connectivity")
                count += 1
        self.check_dmesg_error()
Пример #13
0
class SwitchTest(Test):
    '''
    switch port test
    '''
    def setUp(self):
        '''
        To get all the parameter for the test
        '''
        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="")
        local = LocalHost()
        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.peer = self.params.get("peer_ip")
        if not self.peer:
            self.cancel("No peer provided")
        if self.networkinterface.ping_check(self.peer, count=2) is not None:
            self.cancel("No connection to peer")
        self.switch_name = self.params.get("switch_name", '*', default="")
        self.userid = self.params.get("userid", '*', default="")
        self.password = self.params.get("password", '*', default="")
        self.port_id = self.params.get("port_id", default="")
        if not self.port_id:
            self.cancel("user should specify port id")
        self.switch_login(self.switch_name, self.userid, self.password)

    def switch_login(self, ip, username, password):
        '''
        Login method for remote fc switch
        '''
        self.tnc = paramiko.SSHClient()
        self.tnc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.tnc.connect(ip,
                         username=username,
                         password=password,
                         look_for_keys=False,
                         allow_agent=False)
        self.log.info("SSH connection established to " + ip)
        self.remote_conn = self.tnc.invoke_shell()
        self.log.info("Interactive SSH session established")
        assert self.remote_conn
        self.remote_conn.send("iscli" + '\n')

    def _send_only_result(self, command, response):
        output = response.decode("utf-8").splitlines()
        if command in output[0]:
            output.pop(0)
        output.pop()
        output = [element.lstrip() + '\n' for element in output]
        response = ''.join(output)
        response = response.strip()
        self.log.info(''.join(response))
        return ''.join(response)

    def run_switch_command(self, command, timeout=300):
        '''
        Run command method for running commands on fc switch
        '''
        self.prompt = "#"
        self.log.info("Running the %s command on fc/nic switch", command)
        if not hasattr(self, 'tnc'):
            self.fail("telnet connection to the fc/nic switch not yet done")
        self.remote_conn.send(command + '\n')
        response = self.remote_conn.recv(1000)
        return self._send_only_result(command, response)

    def test(self):
        '''
        switch port enable and disable test
        '''
        self.log.info("Enabling the privilege mode")
        self.run_switch_command("enable")
        self.log.info("Entering configuration mode")
        self.run_switch_command("conf t")
        cmd = "interface port %s" % self.port_id
        self.run_switch_command(cmd)
        self.run_switch_command("shutdown")
        time.sleep(5)
        if self.networkinterface.ping_check(self.peer, count=5) is None:
            self.fail("pinging after disable port")
        self.run_switch_command("no shutdown")
        time.sleep(5)
        if self.networkinterface.ping_check(self.peer, count=5) is not None:
            self.fail("ping test failed")
        self.run_switch_command("end")

    def tearDown(self):
        '''
        unset ip address
        '''
        self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
        self.networkinterface.restore_from_backup()
Пример #14
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()
Пример #15
0
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)
        local = LocalHost()
        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.log.info(
                    "backup file not availbale, could not restore file.")
        self.remotehost.remote_session.quit()
        self.remotehost_public.remote_session.quit()
        if 'scp' or 'ssh' in str(self.name.name):
            self.session.quit()
Пример #16
0
class VethdlparTest(Test):
    '''
    DLPAR veth script does veth device add,remove.
    Update the details in yaml file.
    '''
    def setUp(self):
        '''
        Gather necessary test inputs.
        '''
        self.interface = self.params.get('interface', default=None)
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        self.peer_ip = self.params.get('peer_ip', default=None)
        self.num_of_dlpar = int(self.params.get("num_of_dlpar", default='1'))
        self.vios_ip = self.params.get('vios_ip', '*', default=None)
        self.vios_user = self.params.get('vios_username', '*', default=None)
        self.vios_pwd = self.params.get('vios_pwd', '*', default=None)
        self.session = Session(self.vios_ip,
                               user=self.vios_user,
                               password=self.vios_pwd)
        self.session.connect()
        local = LocalHost()
        self.networkinterface = NetworkInterface(self.interface, 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()
        cmd = "lscfg -l %s" % self.interface
        for line in process.system_output(cmd, shell=True).decode("utf-8") \
                                                          .splitlines():
            if self.interface in line:
                self.slot = line.split()[-1].split('-')[-2]
        cmd = "ioscli lsmap -all -net"
        output = self.session.cmd(cmd)
        for line in output.stdout_text.splitlines():
            if self.slot in line:
                self.iface = line.split()[0]
        cmd = "ioscli lsmap -vadapter %s -net" % self.iface
        output = self.session.cmd(cmd)
        for line in output.stdout_text.splitlines():
            if "SEA" in line:
                self.sea = line.split()[-1]
        if not self.sea:
            self.cancel("failed to get SEA")
        self.log.info(self.sea)
        if self.networkinterface.ping_check(self.peer_ip, count=5) is not None:
            self.cancel("peer connection is failed")

    def veth_dlpar_remove(self):
        '''
        veth dlpar remove operation
        '''
        cmd = "rmdev -l %s" % self.sea
        cmd_l = "echo \"%s\" | ioscli oem_setup_env" % cmd
        output = self.session.cmd(cmd_l)
        self.log.info(output.stdout_text)
        if output.exit_status != 0:
            self.fail("failed dlpar remove operation")

    def veth_dlpar_add(self):
        '''
        veth dlpar add operation
        '''
        cmd = "mkdev -l %s" % self.sea
        cmd_l = "echo \"%s\" | ioscli oem_setup_env" % cmd
        output = self.session.cmd(cmd_l)
        self.log.info(output.stdout_text)
        if output.exit_status != 0:
            self.fail("Failed dlpar add operation")

    def test_dlpar(self):
        '''
        veth dlapr remove and add operation
        '''
        for _ in range(self.num_of_dlpar):
            self.veth_dlpar_remove()
            time.sleep(30)
            self.veth_dlpar_add()
            if self.networkinterface.ping_check(self.peer_ip,
                                                count=5) is not None:
                self.fail("ping failed after add operation")

    def tearDown(self):
        self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
        self.networkinterface.restore_from_backup()
        self.session.quit()
Пример #17
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()
Пример #18
0
class VethdlparTest(Test):
    '''
    DLPAR veth script does veth device add,remove.
    Update the details in yaml file.
    '''
    def setUp(self):
        '''
        Gather necessary test inputs.
        '''
        self.interface = self.params.get('interface', default=None)
        self.peer_ip = self.params.get('peer_ip', default=None)
        self.num_of_dlpar = int(self.params.get("num_of_dlpar", default='1'))
        self.vios_ip = self.params.get('vios_ip', '*', default=None)
        self.vios_user = self.params.get('vios_username', '*', default=None)
        self.vios_pwd = self.params.get('vios_pwd', '*', default=None)
        self.login(self.vios_ip, self.vios_user, self.vios_pwd)
        cmd = "lscfg -l %s" % self.interface
        for line in process.system_output(cmd, shell=True).decode("utf-8") \
                                                          .splitlines():
            if self.interface in line:
                self.slot = line.split()[-1].split('-')[-2]
        cmd = "lsmap -all -net"
        output = self.run_command(cmd)
        for line in output.splitlines():
            if self.slot in line:
                self.iface = line.split()[0]
        cmd = "lsmap -vadapter %s -net" % self.iface
        output = self.run_command(cmd)
        for line in output.splitlines():
            if "SEA" in line:
                self.sea = line.split()[-1]
        if not self.sea:
            self.cancel("failed to get SEA")
        self.log.info(self.sea)
        local = LocalHost()
        self.networkinterface = NetworkInterface(self.interface, local)
        if self.networkinterface.ping_check(self.peer_ip, count=5) is not None:
            self.cancel("peer connection is failed")

    def login(self, ipaddr, username, password):
        '''
        SSH Login method for remote server
        '''
        pxh = pxssh.pxssh(encoding='utf-8')
        # Work-around for old pxssh not having options= parameter
        pxh.SSH_OPTS = "%s  -o 'StrictHostKeyChecking=no'" % pxh.SSH_OPTS
        pxh.SSH_OPTS = "%s  -o 'UserKnownHostsFile /dev/null' " % pxh.SSH_OPTS
        pxh.force_password = True

        pxh.login(ipaddr, username, password)
        pxh.sendline()
        pxh.prompt(timeout=60)
        pxh.sendline('exec bash --norc --noprofile')
        pxh.prompt(timeout=60)
        # Ubuntu likes to be "helpful" and alias grep to
        # include color, which isn't helpful at all. So let's
        # go back to absolutely no messing around with the shell
        pxh.set_unique_prompt()
        pxh.prompt(timeout=60)
        self.pxssh = pxh

    def run_command(self, command, timeout=300):
        '''
        SSH Run command method for running commands on remote server
        '''
        self.log.info("Running the command on peer lpar: %s", command)
        if not hasattr(self, 'pxssh'):
            self.fail("SSH Console setup is not yet done")
        con = self.pxssh
        con.sendline(command)
        con.expect("\n")  # from us
        con.expect(con.PROMPT, timeout=timeout)
        output = "".join(con.before)
        con.sendline("echo $?")
        con.prompt(timeout)
        exitcode = int(''.join(con.before.splitlines()[1:]))
        if exitcode != 0:
            raise CommandFailed(command, output, exitcode)
        return output

    def veth_dlpar_remove(self):
        '''
        veth dlpar remove operation
        '''
        cmd = "rmdev -l %s" % self.sea
        cmd_l = "echo \"%s\" | oem_setup_env" % cmd
        try:
            output = self.run_command(cmd_l)
            self.log.info(output)
        except CommandFailed as cf:
            self.fail("failed dlpar remove operation as %s" % cf)

    def veth_dlpar_add(self):
        '''
        veth dlpar add operation
        '''
        cmd = "mkdev -l %s" % self.sea
        cmd_l = "echo \"%s\" | oem_setup_env" % cmd
        try:
            output = self.run_command(cmd_l)
            self.log.info(output)
        except CommandFailed as cf:
            self.fail("Failed dlpar add operation as %s" % cf)

    def test_dlpar(self):
        '''
        veth dlapr remove and add operation
        '''
        for _ in range(self.num_of_dlpar):
            self.veth_dlpar_remove()
            time.sleep(30)
            self.veth_dlpar_add()
            if self.networkinterface.ping_check(self.peer_ip,
                                                count=5) is not None:
                self.fail("ping failed after add operation")

    def tearDown(self):
        if self.pxssh.isalive():
            self.pxssh.terminate()
Пример #19
0
class Moduleparameter(Test):
    """
    This Script verfies driver module parameter.
    """
    def setUp(self):
        """
        get parameters
        """
        self.module = self.params.get('module', default=None)
        interfaces = netifaces.interfaces()
        self.ifaces = self.params.get("interface")
        if self.ifaces not in interfaces:
            self.cancel("%s interface is not available" % self.ifaces)
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        self.peer = self.params.get("peer_ip")
        if not self.peer:
            self.cancel("No peer provided")
        self.param_name = self.params.get('module_param_name', default=None)
        self.param_value = self.params.get('module_param_value', default=None)
        self.sysfs_chk = self.params.get('sysfs_check_required', default=None)
        local = LocalHost()
        if self.ifaces[0:2] == 'ib':
            self.networkinterface = NetworkInterface(self.ifaces,
                                                     local,
                                                     if_type='Infiniband')
            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)
        else:
            self.networkinterface = NetworkInterface(self.ifaces, 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.load_unload_sleep_time = 10
        self.error_modules = []
        self.mod_list = []
        self.uname = linux_modules.platform.uname()[2]
        if self.built_in_module(self.module) is True:
            self.cancel("Module %s is Built-in Skipping " % self.module)
        if self.param_check() is False:
            self.cancel("Param %s is not Valid for Module %s" %
                        (self.param_name, self.module))

    def built_in_module(self, module):
        """
        checking whether the given module is built_in module or not
        """
        path = "/lib/modules/%s/modules.builtin" % self.uname
        for each in genio.read_all_lines(path):
            out = process.getoutput(each.split('/')[-1])
            if module == out.split('.'[0]):
                return True
            return False

    def sysfs_value_check(self):
        '''
        Checks if sysfs value matches to test value, Returns True if yes.
        Returns False otherwise.
        '''
        value_check = process.system_output(
            '/usr/bin/cat \
                               /sys/module/%s/parameters/%s' %
            (self.module, self.param_name)).decode('utf-8')
        if self.param_value not in value_check:
            return False
        return True

    def param_check(self):
        '''
        Checks if Param is available for the Module, Returns True if yes.
        Returns False otherwise.
        '''
        value_check = process.system_output('/usr/sbin/modinfo -p %s ' %
                                            self.module).decode('utf-8')
        if self.param_name not in value_check:
            return False
        return True

    def module_load_unload(self, mod1):
        """
        Unloading and loading the given module
        """
        if linux_modules.module_is_loaded(mod1) is False:
            linux_modules.load_module(mod1)
            time.sleep(self.load_unload_sleep_time)
        sub_mod = linux_modules.get_submodules(mod1)
        if sub_mod:
            for mod in sub_mod:
                linux_modules.unload_module(mod)
                if linux_modules.module_is_loaded(mod) is True:
                    self.error_modules.append(mod)
                    break
        if linux_modules.unload_module(mod1) is False:
            self.fail("Unloading Module %s failed" % mod1)
        time.sleep(self.load_unload_sleep_time)
        cmd = "%s %s=%s" % (mod1, self.param_name, self.param_value)
        if linux_modules.load_module(cmd) is False:
            self.fail("Param %s = Value %s Failed for Module %s" %
                      (self.param_name, self.param_value, mod1))
        time.sleep(self.load_unload_sleep_time)
        if self.sysfs_chk:
            if self.sysfs_value_check() is False:
                self.fail("Sysfs check failed ")
        if not wait.wait_for(self.networkinterface.is_link_up, timeout=120):
            self.fail("Link up of interface is taking longer than 120s")
        if self.networkinterface.ping_check(self.peer,
                                            count=1000,
                                            options='-f') is not None:
            self.fail("ping test failed")

    def test(self):
        """
        Test Begins here
        """
        self.module_load_unload(self.module)
        if self.error_modules:
            self.fail("Failed Modules: %s" % self.error_modules)

    def tearDown(self):
        """
        Restore back the default Parameters
        """
        self.log.info("Restoring Default param")
        linux_modules.unload_module(self.module)
        linux_modules.load_module(self.module)
        time.sleep(self.load_unload_sleep_time)
        if linux_modules.module_is_loaded(self.module) is False:
            self.fail("Cannot restore default values for Module : %s" %
                      self.module)
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.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')
            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)
        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:
                self.fail("failed")
        self.log.info(
            process.run("ifconfig %s" % self.iface,
                        shell=True,
                        verbose=True,
                        ignore_status=True))
        if self.networkinterface.ping_check(self.peer, count=100,
                                            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=101,
                                                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")
class VirtualizationDriverBindTest(Test):
    """
    virtualized devices can be bound and unbound to drivers.
    This test verifies that for a given virtualized device.
    :param device: Name of the virtualized device
    """
    def setUp(self):
        """
        Identify the virtualized device.
        """
        smm = SoftwareManager()
        for pkg in ["net-tools"]:
            if not smm.check_installed(pkg) and not smm.install(pkg):
                self.cancel("%s package is need to test" % pkg)
        interfaces = netifaces.interfaces()
        self.virtual_device = self.params.get('virtual_device')
        self.virtual_slot = self.params.get('virtual_slot')
        if "T" in self.virtual_slot:
            self.virtual_slot = self.virtual_slot.split("-T")[0]
        output = process.system_output("lsslot", shell=True)
        for line in output.decode("utf-8").splitlines():
            if self.virtual_slot in line:
                self.device_type = line.split()[-1]
                self.device = line.split()[-2]
        self.count = int(self.params.get('count', default="1"))
        self.peer_ip = self.params.get('peer_ip', default=None)
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        local = LocalHost()
        if self.device_type in ["l-lan", "vnic"]:
            if self.virtual_device not in interfaces:
                self.cancel("%s interface is not available" %
                            self.virtual_device)
            self.networkinterface = NetworkInterface(self.virtual_device,
                                                     local)
            if self.virtual_device in local.get_default_route_interface():
                self.cancel("Test could not run on default interface")
            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()
        else:
            if disk.is_root_device(self.virtual_device):
                self.cancel("Test could not run on root disk")

    def is_exists_device(self, device):
        '''
        Check whether the scsi_device is present in lsscsi output
        '''
        devices = []
        output = process.system_output("lsscsi").decode('utf-8')
        for line in output.splitlines():
            devices.append(line.split('/')[-1].strip(' '))
        if device in devices:
            return True
        return False

    def test(self):
        """
        Performs driver unbind and bind for the Network virtualized device
        """
        if self.device_type in ["l-lan", "vnic"]:
            if self.networkinterface.ping_check(self.peer_ip,
                                                count=5) is not None:
                self.cancel(
                    "Please make sure the network peer is configured ?")
        else:
            if self.is_exists_device(self.virtual_device) is False:
                self.cancel("failed to detect the test disk")
        try:
            for _ in range(self.count):
                for operation in ["unbind", "bind"]:
                    self.log.info(
                        "Running %s operation for Network virtualized \
                                   device" % operation)
                    dict = {
                        "vnic": "ibmvnic",
                        "l-lan": "ibmveth",
                        "v-scsi": "ibmvscsi",
                        "vfc-client": "ibmvfc"
                    }
                    if self.device_type in dict.keys():
                        param = dict[self.device_type]
                        genio.write_file(
                            os.path.join("/sys/bus/vio/drivers/%s" % param,
                                         operation), "%s" % self.device)
                    time.sleep(5)
                if self.device_type in ["l-lan", "vnic"]:
                    self.log.info(
                        "Running a ping test to check if unbind/bind \
                                   affected newtwork connectivity")
                    if self.networkinterface.ping_check(self.peer_ip,
                                                        count=5) is not None:
                        self.fail("Ping test failed. Network virtualized \
                                  unbind/bind has affected Network connectivity"
                                  )
                else:
                    self.log.info("checking for disk available if unbind/bind \
                                   affected to disk")
                    if self.is_exists_device(self.virtual_device) is False:
                        self.fail("exists device test failed.unbind/bind has \
                                   affected disk")
        except CmdError as details:
            self.log.debug(str(details))
            self.fail("Driver %s operation failed for Network virtualized \
                       device %s" % (operation, self.interface))

    def tearDown(self):
        """
        remove ip from interface
        """
        if self.device_type in ["l-lan", "vnic"]:
            self.networkinterface.remove_ipaddr(self.ipaddr, self.netmask)
            self.networkinterface.restore_from_backup()