예제 #1
0
    def __init__(self):
        """
        Initialisation function.
        """
        super(QemuVirtioNet, self).__init__()
        self._logger = logging.getLogger(__name__)

        # insert vanilla ovs specific modules
        tasks.run_task(['sudo', 'modprobe', 'vhost_net'], self._logger,
                       'Loading vhost_net module...', True)

        # calculate indexes of guest devices (e.g. charx, dpdkvhostuserx)
        i = self._number * 2
        if1 = str(i)
        if2 = str(i + 1)

        self._cmd += [
            '-netdev',
            'type=tap,id=' + self._net1 + ',script=no,downscript=no,' +
            'ifname=tap' + if1 + ',vhost=on',
            '-device',
            'virtio-net-pci,mac=' +
            S.getValue('GUEST_NET1_MAC')[self._number] + ',netdev=' +
            self._net1 + ',csum=off,gso=off,' +
            'guest_tso4=off,guest_tso6=off,guest_ecn=off',
            '-netdev',
            'type=tap,id=' + self._net2 + ',script=no,downscript=no,' +
            'ifname=tap' + if2 + ',vhost=on',
            '-device',
            'virtio-net-pci,mac=' +
            S.getValue('GUEST_NET2_MAC')[self._number] + ',netdev=' +
            self._net2 + ',csum=off,gso=off,' +
            'guest_tso4=off,guest_tso6=off,guest_ecn=off',
        ]
예제 #2
0
def add_veth_port(port, peer_port):
    """
    Add a veth port
    :param port:port name for the first port
    :param peer_port: port name for the peer port
    :return: None
    """
    # touch some files in a tmp area so we can track them. This allows us to
    # track VSPerf created veth ports so they can be cleaned up if needed.
    if not os.path.isdir('/tmp/veth'):
        try:
            os.mkdir('/tmp/veth')
        except os.error:
            # OK don't crash but cleanup may be an issue
            _LOGGER.error('Unable to create veth temp folder.')
            _LOGGER.error(
                'Veth ports may not be removed on testcase completion')
    if os.path.isdir('/tmp/veth'):
        with open('/tmp/veth/{}-{}'.format(port, peer_port), 'a'):
            os.utime('/tmp/veth/{}-{}'.format(port, peer_port), None)
    tasks.run_task([
        'sudo', 'ip', 'link', 'add', port, 'type', 'veth', 'peer', 'name',
        peer_port
    ], _LOGGER, 'Adding veth port {} with peer port {}...'.format(
        port, peer_port), False)
예제 #3
0
def _unbind_nics():
    """Unbind NICs using the Intel DPDK ``dpdk*bind.py`` tool.
    """
    if not len(_NICS_PCI):
        _LOGGER.info('NICs are not configured - nothing to unbind')
        return
    try:
        tasks.run_task(
            ['sudo', S.getValue('TOOLS')['bind-tool'], '--unbind'] + _NICS_PCI,
            _LOGGER, 'Unbinding NICs %s...' % str(_NICS_PCI), True)
    except subprocess.CalledProcessError:
        _LOGGER.error('Unable to unbind NICs %s', str(_NICS_PCI))
    # Rebind NICs to their original drivers
    # using the Intel DPDK ``dpdk*bind.py`` tool.
    for nic in _NICS:
        try:
            if nic['driver']:
                tasks.run_task([
                    'sudo',
                    S.getValue('TOOLS')['bind-tool'], '--bind', nic['driver'],
                    nic['pci']
                ], _LOGGER, 'Binding NIC %s to %s...' %
                               (nic['pci'], nic['driver']), True)
        except subprocess.CalledProcessError:
            _LOGGER.error('Unable to bind NIC %s to driver %s', nic['pci'],
                          nic['driver'])
예제 #4
0
    def _copy_fwd_tools_for_guest(self):
        """Copy dpdk and l2fwd code to GUEST_SHARE_DIR[s] for use by guests.
        """
        counter = 0
        # method is executed only for pvp and pvvp, so let's count number of 'v'
        while counter < self.deployment.count('v'):
            guest_dir = S.getValue('GUEST_SHARE_DIR')[counter]

            # create shared dir if it doesn't exist
            if not os.path.exists(guest_dir):
                os.makedirs(guest_dir)

            # copy sources into shared dir only if neccessary
            if 'testpmd' in self.guest_loopback or 'l2fwd' in self.guest_loopback:
                try:
                    tasks.run_task([
                        'rsync', '-a', '-r', '-l', r'--exclude="\.git"',
                        os.path.join(S.getValue('RTE_SDK'), ''),
                        os.path.join(guest_dir, 'DPDK')
                    ], self._logger, 'Copying DPDK to shared directory...',
                                   True)
                    tasks.run_task([
                        'rsync', '-a', '-r', '-l',
                        os.path.join(S.getValue('ROOT_DIR'), 'src/l2fwd/'),
                        os.path.join(guest_dir, 'l2fwd')
                    ], self._logger, 'Copying l2fwd to shared directory...',
                                   True)
                except subprocess.CalledProcessError:
                    self._logger.error(
                        'Unable to copy DPDK and l2fwd to shared directory')

            counter += 1
예제 #5
0
def _unbind_nics():
    """Unbind NICs using the Intel DPDK ``dpdk_nic_bind.py`` tool.
    """
    nic_drivers = _unbind_nics_get_driver()
    try:
        tasks.run_task(['sudo', RTE_PCI_TOOL, '--unbind'] +
                       settings.getValue('WHITELIST_NICS'), _LOGGER,
                       'Unbinding NICs %s...' %
                       str(settings.getValue('WHITELIST_NICS')),
                       True)
    except subprocess.CalledProcessError:
        _LOGGER.error('Unable to unbind NICs %s',
                      str(settings.getValue('WHITELIST_NICS')))
    # Rebind NICs to their original drivers
    # using the Intel DPDK ``dpdk_nic_bind.py`` tool.
    for i, nic in enumerate(settings.getValue('WHITELIST_NICS')):
        try:
            if nic_drivers[i] != '':
                tasks.run_task(['sudo', RTE_PCI_TOOL, '--bind',
                                nic_drivers[i], nic],
                               _LOGGER, 'Binding NIC %s...' %
                               nic,
                               True)
        except subprocess.CalledProcessError:
            _LOGGER.error('Unable to bind NICs %s to drivers %s',
                          str(settings.getValue('WHITELIST_NICS')),
                          nic_drivers)
예제 #6
0
 def cleanup_metrics(self):
     """
     Cleaup the old or archived metrics
     """
     for name in glob.glob(os.path.join('/tmp/csv/', '*')):
         tasks.run_task(['sudo', 'rm', '-rf', name], self.logger,
                        'Cleaning up Metrics', True)
예제 #7
0
파일: ovs.py 프로젝트: opnfv/vineperf
    def _start_ovsdb(self):
        """Start ``ovsdb-server`` instance.

        :returns: None
        """
        ovsdb_tool_bin = settings.getValue('TOOLS')['ovsdb-tool']
        tasks.run_task([
            'sudo', ovsdb_tool_bin, 'create',
            os.path.join(settings.getValue('TOOLS')['ovs_etc_tmp'], 'conf.db'),
            settings.getValue('TOOLS')['ovsschema']
        ], self._logger, 'Creating ovsdb configuration database...')

        ovsdb_server_bin = settings.getValue('TOOLS')['ovsdb-server']

        if settings.getValue('CLEAN_OUTPUT'):
            tasks.run_background_task([
                'sudo', ovsdb_server_bin,
                '--remote=punix:%s' % os.path.join(
                    settings.getValue('TOOLS')['ovs_var_tmp'], 'db.sock'),
                '--remote=db:Open_vSwitch,Open_vSwitch,manager_options',
                '--pidfile=' + self._ovsdb_pidfile_path, '--overwrite-pidfile',
                '--verbose=off'
            ], self._logger, 'Starting ovsdb-server...')
        else:
            tasks.run_background_task([
                'sudo', ovsdb_server_bin,
                '--remote=punix:%s' % os.path.join(
                    settings.getValue('TOOLS')['ovs_var_tmp'], 'db.sock'),
                '--remote=db:Open_vSwitch,Open_vSwitch,manager_options',
                '--pidfile=' + self._ovsdb_pidfile_path, '--overwrite-pidfile'
            ], self._logger, 'Starting ovsdb-server...')
예제 #8
0
파일: ovs.py 프로젝트: opnfv/vineperf
    def _kill_ovsdb(self):
        """Kill ``ovsdb-server`` instance.

        :returns: None
        """
        if os.path.isfile(self._ovsdb_pidfile_path):
            with open(self._ovsdb_pidfile_path, "r") as pidfile:
                ovsdb_pid = pidfile.read().strip()

            self._logger.info("Killing ovsdb with pid: %s", ovsdb_pid)

            if ovsdb_pid:
                tasks.terminate_task(ovsdb_pid, logger=self._logger)

        # restore original content of ovs_var_tmp and ovs_etc_tmp; It is
        # essential for OVS installed from binary packages.
        if self._stamp:
            for tmp_dir in ['ovs_var_tmp', 'ovs_etc_tmp']:
                orig_dir = os.path.normpath(
                    settings.getValue('TOOLS')[tmp_dir])
                if os.path.exists('{}.{}'.format(orig_dir, self._stamp)):
                    self._logger.info('Restoring backup of %s directory...',
                                      tmp_dir)
                    tasks.run_task(['sudo', 'rm', '-rf', orig_dir],
                                   self._logger)
                    tasks.run_task([
                        'sudo', 'mv', '{}.{}'.format(orig_dir, self._stamp),
                        orig_dir
                    ], self._logger)
예제 #9
0
def create_namespace(name):
    """
    Create a linux namespace. Raises RuntimeError if namespace already exists
    in the system.
    :param name: name of the namespace to be created as string
    :return: None
    """
    if name in get_system_namespace_list():
        raise RuntimeError('Namespace already exists in system')

    # touch some files in a tmp area so we can track them separately from
    # the OS's internal namespace tracking. This allows us to track VSPerf
    # created namespaces so they can be cleaned up if needed.
    if not os.path.isdir('/tmp/namespaces'):
        try:
            os.mkdir('/tmp/namespaces')
        except os.error:
            # OK don't crash, but cleanup may be an issue...
            _LOGGER.error('Unable to create namespace temp folder.')
            _LOGGER.error(
                'Namespaces will not be removed on test case completion')
    if os.path.isdir('/tmp/namespaces'):
        with open('/tmp/namespaces/{}'.format(name), 'a'):
            os.utime('/tmp/namespaces/{}'.format(name), None)

    tasks.run_task(['sudo', 'ip', 'netns', 'add', name], _LOGGER,
                   'Creating namespace {}...'.format(name), False)
    tasks.run_task(
        ['sudo', 'ip', 'netns', 'exec', name, 'ip', 'link', 'set', 'lo', 'up'],
        _LOGGER, 'Enabling loopback interface...', False)
예제 #10
0
    def stop(self):
        """See IVswitch for general description

        Kills ovsdb and vswitchd and removes kernel modules.
        """
        # remove all tap interfaces
        for i in range(self._vport_id):
            tapx = 'tap' + str(i)
            tap_cmd_list = ['sudo', 'ip', 'tuntap', 'del', tapx, 'mode', 'tap']
            # let's assume, that all VMs have NIC QUEUES enabled or disabled
            # at the same time
            if int(settings.getValue('GUEST_NIC_QUEUES')[0]):
                tap_cmd_list += ['multi_queue']
            tasks.run_task(tap_cmd_list, self._logger, 'Deleting ' + tapx,
                           False)
        self._vport_id = 0

        # remove datapath before vswitch shutdown
        dpctl = DPCtl()
        dpctl.del_dp()

        super(OvsVanilla, self).stop()

        # give vswitch time to terminate before modules are removed
        time.sleep(5)
        self._module_manager.remove_modules()
예제 #11
0
    def add_phy_port(self, switch_name):
        """
        Method adds port based on configured VSWITCH_VANILLA_PHY_PORT_NAMES
        stored in config file.

        See IVswitch for general description
        """
        if self._current_id == len(self._ports):
            self._logger.error("Can't add port! There are only " +
                               len(self._ports) + " ports " +
                               "defined in config!")
            raise

        if not self._ports[self._current_id]:
            self._logger.error("VSWITCH_VANILLA_PHY_PORT_NAMES not set")
            raise ValueError("Invalid VSWITCH_VANILLA_PHY_PORT_NAMES")

        bridge = self._bridges[switch_name]
        port_name = self._ports[self._current_id]
        params = []

        # For PVP only
        tasks.run_task(['sudo', 'ifconfig', port_name, '0'],
                       _LOGGER, 'Remove IP', False)

        of_port = bridge.add_port(port_name, params)
        self._current_id += 1
        return (port_name, of_port)
예제 #12
0
    def add_phy_port(self, switch_name):
        """
        Method adds port based on detected device names.

        See IVswitch for general description
        """
        if self._current_id == len(self._ports):
            raise RuntimeError(
                "Can't add phy port! There are only {} ports defined "
                "by WHITELIST_NICS parameter!".format(len(self._ports)))
        if not self._ports[self._current_id]:
            self._logger.error("Can't detect device name for NIC %s",
                               self._current_id)
            raise ValueError("Invalid device name for %s" % self._current_id)

        bridge = self._bridges[switch_name]
        port_name = self._ports[self._current_id]
        params = []

        # For PVP only
        tasks.run_task(['sudo', 'ip', 'addr', 'flush', 'dev', port_name[0]],
                       self._logger, 'Remove IP', False)
        tasks.run_task(
            ['sudo', 'ip', 'link', 'set', 'dev', port_name[0], 'up'],
            self._logger, 'Bring up ' + port_name[0], False)

        of_port = bridge.add_port(port_name[0], params)
        self._current_id += 1
        return (port_name, of_port)
예제 #13
0
파일: ovs.py 프로젝트: opnfv/vineperf
 def _disable_console_output(self):
     """
     Configure vswitch to disable console output
     """
     ovsappctl_tool_bin = settings.getValue('TOOLS')['ovs-appctl']
     tasks.run_task(
         ['sudo', ovsappctl_tool_bin, 'vlog/set', ' console:off'],
         self._logger, 'Turning off the logs ...')
예제 #14
0
def _remove_vhost_net():
    """Remove vhost-net driver and file.
    """
    _DPDK_MODULE_MANAGER.remove_module('vhost-net')
    try:
        tasks.run_task(['sudo', 'rm', '-f', '/dev/vhost-net'], _LOGGER,
                       'Removing \'/dev/vhost-net\' directory...', True)
    except subprocess.CalledProcessError:
        _LOGGER.error('Unable to remove directory \'/dev/vhost-net\'.')
예제 #15
0
def delete_namespace(name):
    """
    Delete linux network namespace
    :param name: namespace to delete
    :return: None
    """
    # delete the file if it exists in the temp area
    if os.path.exists('/tmp/namespaces/{}'.format(name)):
        os.remove('/tmp/namespaces/{}'.format(name))
    tasks.run_task(['sudo', 'ip', 'netns', 'delete', name], _LOGGER,
                   'Deleting namespace {}...'.format(name), False)
예제 #16
0
    def __init__(self):
        """See IVswitch for general description
        """
        self._logfile = os.path.join(S.getValue('LOG_DIR'),
                                     S.getValue('LOG_FILE_VPP'))
        self._logger = logging.getLogger(__name__)
        self._expect = r'vpp#'
        self._timeout = 30
        self._vswitch_args = []
        self._cmd = []
        self._cmd_template = ['sudo', '-E', S.getValue('TOOLS')['vpp']]
        self._stamp = None
        self._logger = logging.getLogger(__name__)
        self._phy_ports = []
        self._virt_ports = []
        self._switches = {}
        self._vpp_ctl = ['sudo', S.getValue('TOOLS')['vppctl']]

        # configure DPDK NICs
        tmp_args = copy.deepcopy(S.getValue('VSWITCH_VPP_ARGS'))
        if 'dpdk' not in tmp_args:
            tmp_args['dpdk'] = []

        # override socket-mem settings
        for tmp_arg in tmp_args['dpdk']:
            if tmp_arg.startswith('socket-mem'):
                tmp_args['dpdk'].remove(tmp_arg)
        tmp_args['dpdk'].append('socket-mem ' +
                                ','.join(S.getValue('DPDK_SOCKET_MEM')))

        # create directory for vhostuser sockets if needed
        if not os.path.exists(S.getValue('TOOLS')['ovs_var_tmp']):
            tasks.run_task(
                ['sudo', 'mkdir', '-p',
                 S.getValue('TOOLS')['ovs_var_tmp']], self._logger)

        # configure path to the plugins
        tmp_args['plugin_path'] = S.getValue('TOOLS')['vpp_plugin_path']

        # cli sock file must be used for VPP 17.10 and newer
        if S.getValue('VSWITCH_VPP_CLI_SOCK'):
            self._vpp_ctl += ['-s', S.getValue('VSWITCH_VPP_CLI_SOCK')]
            tmp_args['unix'].append('cli-listen {}'.format(
                S.getValue('VSWITCH_VPP_CLI_SOCK')))

        mqs = int(S.getValue('VSWITCH_DPDK_MULTI_QUEUES'))
        tmp_rxqs = ''
        if mqs:
            tmp_rxqs = " {{ num-rx-queues {} }}".format(mqs)

        # configure physical ports
        for nic in S.getValue('NICS'):
            tmp_args['dpdk'].append("dev {}{}".format(nic['pci'], tmp_rxqs))
        self._vswitch_args = self._process_vpp_args(tmp_args)
예제 #17
0
def _umount_hugepages():
    """Ensure hugepages are unmounted.
    """
    if not _is_hugepage_mounted():
        return

    try:
        tasks.run_task(['sudo', 'umount', settings.getValue('HUGEPAGE_DIR')],
                       _LOGGER, 'Unmounting hugepages...', True)
    except subprocess.CalledProcessError:
        _LOGGER.error('Unable to umount hugepages.')
예제 #18
0
    def kill(self, signal='-15', sleep=2):
        """
        Kill stress load if it is active
        """
        if self._running and self._child and self._child.isalive():
            tasks.run_task(['sudo', 'pkill', signal, self._proc_name], self._logger)
        time.sleep(sleep)

        self._logger.info(
            'Log available at %s', self._logfile)
        self._running = False
예제 #19
0
def _bind_nics():
    """Bind NICs using the Intel DPDK ``dpdk_nic_bind.py`` tool.
    """
    try:
        tasks.run_task(['sudo', RTE_PCI_TOOL, '--bind', 'igb_uio'] +
                       settings.getValue('WHITELIST_NICS'), _LOGGER,
                       'Binding NICs %s...' %
                       settings.getValue('WHITELIST_NICS'),
                       True)
    except subprocess.CalledProcessError:
        _LOGGER.error('Unable to bind NICs %s',
                      str(settings.getValue('WHITELIST_NICS')))
예제 #20
0
    def stop(self):
        """
        Stops collection of statistics by pidstat and stores statistic summary
        for each monitored process into self._results dictionary
        """
        if self._pid:
            self._pid = 0
            # in python3.4 it's not possible to send signal through pid of sudo
            # process, so all pidstat processes are interupted instead
            # as a workaround
            tasks.run_task(['sudo', 'pkill', '--signal', '2', 'pidstat'],
                           self._logger)

        self._logger.info('Pidstat log available at %s', self._log)

        # let's give pidstat some time to write down average summary
        time.sleep(2)

        # parse average values from log file and store them to _results dict
        self._results = OrderedDict()
        logfile = open(self._log, 'r')
        with logfile:
            line = logfile.readline()
            while line:
                line = line.strip()
                # process only lines with summary
                if line[0:7] == 'Average':
                    if line[-7:] == 'Command':
                        # store header fields if detected
                        tmp_header = line[8:].split()
                    else:
                        # combine stored header fields with actual values
                        tmp_res = OrderedDict(zip(tmp_header,
                                                  line[8:].split()))
                        cmd = tmp_res.pop('Command')
                        # remove unused fields (given by option '-t')
                        tmp_res.pop('UID')
                        tmp_res.pop('TID')
                        if '|_' not in cmd:  # main process
                            # use process's name and its pid as unique key
                            tmp_pid = tmp_res.pop('TGID')
                            tmp_key = "%s_%s" % (cmd, tmp_pid)
                            # do not trust cpu usage of pid
                            # see VSPERF-569 for more details
                            if 'CPU' not in tmp_header:
                                self.update_results(tmp_key, tmp_res, False)
                        else:  # thread
                            # accumulate cpu usage of all threads
                            if 'CPU' in tmp_header:
                                tmp_res.pop('TGID')
                                self.update_results(tmp_key, tmp_res, True)

                line = logfile.readline()
예제 #21
0
def reset_port_to_root(port, name):
    """
    Return the assigned port to the root namespace
    :param port: port to return as string
    :param name: namespace the port currently resides
    :return: None
    """
    tasks.run_task([
        'sudo', 'ip', 'netns', 'exec', name, 'ip', 'link', 'set', port,
        'netns', '1'
    ], _LOGGER, 'Assigning port {} to namespace {}...'.format(port, name),
                   False)
예제 #22
0
def _bind_nics():
    """Bind NICs using the bind tool specified in the configuration.
    """
    if not _NICS_PCI:
        _LOGGER.info('NICs are not configured - nothing to bind')
        return
    try:
        _driver = 'igb_uio'
        if 'vfio-pci' in S.getValue('TOOLS')['dpdk_modules']:
            _driver = 'vfio-pci'
            tasks.run_task(['sudo', 'chmod', 'a+x', '/dev/vfio'], _LOGGER,
                           'Setting VFIO permissions .. a+x', True)
            tasks.run_task(['sudo', 'chmod', '-R', '666', '/dev/vfio/'],
                           _LOGGER, 'Setting VFIO permissions .. 0666', True)
        if 'driverctl' in S.getValue('TOOLS')['bind-tool'].lower():
            for nic in _NICS_PCI:
                tasks.run_task([
                    'sudo',
                    S.getValue('TOOLS')['bind-tool'], '-v', 'set-override'
                ] + [nic] + [_driver], _LOGGER, 'Binding NIC %s...' % nic,
                               True)
        else:
            tasks.run_task([
                'sudo',
                S.getValue('TOOLS')['bind-tool'], '--bind=' + _driver
            ] + _NICS_PCI, _LOGGER, 'Binding NICs %s...' % _NICS_PCI, True)
    except subprocess.CalledProcessError:
        _LOGGER.error('Unable to bind NICs %s', str(_NICS_PCI))
예제 #23
0
파일: prox.py 프로젝트: opnfv/vineperf
 def send_rfc2544_throughput(self,
                             traffic=None,
                             tests=1,
                             duration=20,
                             lossrate=0.0):
     """
     Send traffic per RFC2544 throughput test specifications.
     """
     print("Run with Duration: {}, Tests: {} & Lossrate: {}".format(
         duration, tests, lossrate))
     pkt_size = None
     if traffic and 'l2' in traffic:
         if 'framesize' in traffic['l2']:
             framesize = traffic['l2']['framesize']
             pkt_size = '[' + str(framesize) + ']'
     if not settings.getValue('K8S'):
         # First render all the configurations and place it
         filesdir = settings.getValue('TRAFFICGEN_PROX_FILES_DIR')
         confdir = settings.getValue('TRAFFICGEN_PROX_CONF_DIR')
         render.render_content_jinja(pkt_size)
         # copy some static files to config folder.
         for stfile in settings.getValue(
                 'TRAFFICGEN_PROX_STATIC_CONF_FILES'):
             srcfile = os.path.join(filesdir, stfile)
             if os.path.exists(srcfile):
                 cmd = ['cp', srcfile, confdir]
                 tasks.run_task(cmd, self._logger,
                                'Copying Static Conf. Files')
         # in appropriate folder: pick /tmp or /opt or $HOME
         envfile = os.path.join(
             confdir, settings.getValue('TRAFFICGEN_PROX_ENV_FILE'))
         tstfile = os.path.join(
             confdir, settings.getValue('TRAFFICGEN_PROX_TEST_FILE'))
         mmapfile = os.path.join(confdir, 'machine.map')
         cmd = [
             'python', '-m', 'runrapid', '--env', envfile, '--test',
             tstfile, '--map', mmapfile, '--runtime',
             settings.getValue('TRAFFICGEN_PROX_RUNTIME')
         ]
         output, error = tasks.run_task(cmd, self._logger,
                                        'Running RUN-RAPID command')
         if output:
             return self.get_rfc2544_results(output)
         else:
             self._logger.info(error)
             return None
     else:
         self._logger.info("Only Baremetal Support is included.")
         print("Only Baremetal Support is included")
         return None
예제 #24
0
    def _kill_ovsdb(self):
        """Kill ``ovsdb-server`` instance.

        :returns: None
        """
        with open(self._ovsdb_pidfile_path, "r") as pidfile:
            ovsdb_pid = pidfile.read().strip()

        self._logger.info("Killing ovsdb with pid: " + ovsdb_pid)

        if ovsdb_pid:
            tasks.run_task(
                ['sudo', 'kill', '-15', str(ovsdb_pid)], self._logger,
                'Killing ovsdb-server...')
예제 #25
0
def del_veth_port(port, peer_port):
    """
    Delete the veth ports, the peer will automatically be deleted on deletion
    of the first port param
    :param port: port name to delete
    :param port: peer port name
    :return: None
    """
    # delete the file if it exists in the temp area
    if os.path.exists('/tmp/veth/{}-{}'.format(port, peer_port)):
        os.remove('/tmp/veth/{}-{}'.format(port, peer_port))
    tasks.run_task(['sudo', 'ip', 'link', 'del', port], _LOGGER,
                   'Deleting veth port {} with peer {}...'.format(
                       port, peer_port), False)
예제 #26
0
 def stop(self, sig, slp):
     """
     Stops VNF instance.
     """
     if self._running:
         self._logger.info('Killing VNF...')
         # force termination of VNF and wait to terminate; It will avoid
         # sporadic reboot of host.
         super(QemuVM, self).kill(signal=sig, sleep=slp)
     # remove shared dir if it exists to avoid issues with file consistency
     if os.path.exists(self._shared_dir):
         tasks.run_task(['rm', '-f', '-r', self._shared_dir], self._logger,
                        'Removing content of shared directory...', True)
     self._running = False
예제 #27
0
def add_ip_to_namespace_eth(port, name, ip_addr, cidr):
    """
    Assign port ip address in namespace
    :param port: port to assign ip to
    :param name: namespace where port resides
    :param ip_addr: ip address in dot notation format
    :param cidr: cidr as string
    :return:
    """
    ip_string = '{}/{}'.format(ip_addr, cidr)
    tasks.run_task([
        'sudo', 'ip', 'netns', 'exec', name, 'ip', 'addr', 'add', ip_string,
        'dev', port
    ], _LOGGER, 'Assigning ip to port {}...'.format(port), False)
예제 #28
0
    def _setup_decap(self):
        """ Sets up the switch for overlay P2P decapsulation test
        """
        self._logger.debug('Setup using %s', str(self._vswitch_class))

        try:
            self._vswitch.start()
            bridge = S.getValue('TUNNEL_INTEGRATION_BRIDGE')
            bridge_ext = S.getValue('TUNNEL_EXTERNAL_BRIDGE')
            bridge_ext_ip = S.getValue('TUNNEL_EXTERNAL_BRIDGE_IP')
            tgen_ip1 = S.getValue('TRAFFICGEN_PORT1_IP')
            self._vswitch.add_switch(bridge)

            tasks.run_task(['sudo', 'ip', 'addr', 'add',
                            S.getValue('VTEP_IP1'), 'dev', bridge],
                           self._logger, 'Assign ' +
                           S.getValue('VTEP_IP1') + ' to ' + bridge, False)
            tasks.run_task(['sudo', 'ip', 'link', 'set', 'dev', bridge, 'up'],
                           self._logger, 'Bring up ' + bridge, False)

            tunnel_type = self._traffic['tunnel_type']

            self._vswitch.add_switch(bridge_ext)
            self._vswitch.add_phy_port(bridge)
            (_, phy2_number) = self._vswitch.add_phy_port(bridge_ext)
            if tunnel_type == "vxlan":
                vxlan_vni = 'options:key=' + S.getValue('VXLAN_VNI')
                (_, phy3_number) = self._vswitch.add_tunnel_port(bridge_ext,
                                                                 tgen_ip1,
                                                                 tunnel_type,
                                                                 params=[vxlan_vni])
            else:
                (_, phy3_number) = self._vswitch.add_tunnel_port(bridge_ext,
                                                                 tgen_ip1,
                                                                 tunnel_type)
            tasks.run_task(['sudo', 'ip', 'addr', 'add',
                            bridge_ext_ip,
                            'dev', bridge_ext],
                           self._logger, 'Assign ' +
                           bridge_ext_ip
                           + ' to ' + bridge_ext)

            tasks.run_task(['sudo', 'ip', 'link', 'set', 'dev', bridge_ext,
                            'up'],
                           self._logger,
                           'Set ' + bridge_ext + ' status to up')

            self._vswitch.set_tunnel_arp(tgen_ip1,
                                         S.getValue('TRAFFICGEN_PORT1_MAC'),
                                         bridge)
            # Test is unidirectional for now
            self._vswitch.del_flow(bridge_ext)
            flow1 = add_ports_to_flow(S.getValue('OVS_FLOW_TEMPLATE'), phy3_number,
                                      phy2_number)
            self._vswitch.add_flow(bridge_ext, flow1)

        except:
            self._vswitch.stop()
            raise
    def _setup_decap(self):
        """ Sets up the switch for overlay P2P decapsulation test
        """
        self._logger.debug('Setup using ' + str(self._vswitch_class))

        try:
            self._vswitch.start()
            bridge = settings.getValue('TUNNEL_INTEGRATION_BRIDGE')
            bridge_ext = settings.getValue('TUNNEL_EXTERNAL_BRIDGE')
            bridge_ext_ip = settings.getValue('TUNNEL_EXTERNAL_BRIDGE_IP')
            tgen_ip1 = settings.getValue('TRAFFICGEN_PORT1_IP')
            self._vswitch.add_switch(bridge)

            tasks.run_task(['sudo', 'ip', 'addr', 'add',
                            settings.getValue('VTEP_IP1'), 'dev', bridge],
                           self._logger, 'Assign ' +
                           settings.getValue('VTEP_IP1') + ' to ' + bridge, False)
            tasks.run_task(['sudo', 'ip', 'link', 'set', 'dev', bridge, 'up'],
                           self._logger, 'Bring up ' + bridge, False)

            tunnel_type = self._traffic['tunnel_type']

            self._vswitch.add_switch(bridge_ext)
            self._vswitch.add_phy_port(bridge)
            (_, phy2_number) = self._vswitch.add_phy_port(bridge_ext)
            if tunnel_type == "vxlan":
                vxlan_vni = 'options:key=' + settings.getValue('VXLAN_VNI')
                (_, phy3_number) = self._vswitch.add_tunnel_port(bridge_ext,
                                                                 tgen_ip1,
                                                                 tunnel_type,
                                                                 params=[vxlan_vni])
            else:
                (_, phy3_number) = self._vswitch.add_tunnel_port(bridge_ext,
                                                                 tgen_ip1,
                                                                 tunnel_type)
            tasks.run_task(['sudo', 'ip', 'addr', 'add',
                            bridge_ext_ip,
                            'dev', bridge_ext],
                           self._logger, 'Assign ' +
                           bridge_ext_ip
                           + ' to ' + bridge_ext)

            tasks.run_task(['sudo', 'ip', 'link', 'set', 'dev', bridge_ext,
                            'up'],
                           self._logger,
                           'Set ' + bridge_ext + ' status to up')

            self._vswitch.set_tunnel_arp(tgen_ip1,
                                         settings.getValue('TRAFFICGEN_PORT1_MAC'),
                                         bridge)
            # Test is unidirectional for now
            self._vswitch.del_flow(bridge_ext)
            flow1 = add_ports_to_flow(_FLOW_TEMPLATE, phy3_number,
                                      phy2_number)
            self._vswitch.add_flow(bridge_ext, flow1)

        except:
            self._vswitch.stop()
            raise
예제 #30
0
def deallocate_hugepages():
    """De-allocate hugepages that were allocated on the fly
    """
    # pylint: disable=global-statement
    global _ALLOCATED_HUGEPAGES
    if _ALLOCATED_HUGEPAGES:
        nr_hugepages = 'vm.nr_hugepages= 0'
        try:
            tasks.run_task(['sudo', 'sysctl', nr_hugepages],
                           _LOGGER, 'Trying to de-allocate hugepages..', True)
        except subprocess.CalledProcessError:
            _LOGGER.error('Unable to de-allocate hugepages.')
            return False
        _ALLOCATED_HUGEPAGES = False
    return True
예제 #31
0
def _remove_vhost_net():
    """Remove vhost-net driver and file.
    """
    if _is_module_inserted('vhost_net'):
        try:
            tasks.run_task(['sudo', 'rmmod', 'vhost_net'], _LOGGER,
                           'Removing \'/dev/vhost-net\' directory...', True)
        except subprocess.CalledProcessError:
            _LOGGER.error('Unable to remove module \'vhost_net\'.')

    try:
        tasks.run_task(['sudo', 'rm', '-f', '/dev/vhost-net'], _LOGGER,
                       'Removing \'/dev/vhost-net\' directory...', True)
    except subprocess.CalledProcessError:
        _LOGGER.error('Unable to remove directory \'/dev/vhost-net\'.')
    def _setup_encap(self):
        """ Sets up the switch for overlay P2P encapsulation test

        Create 2 bridges br0 (integration bridge) and br-ext and a VXLAN port
        for encapsulation.
        """
        self._logger.debug('Setup using ' + str(self._vswitch_class))

        try:
            self._vswitch.start()
            bridge = settings.getValue('TUNNEL_INTEGRATION_BRIDGE')
            bridge_ext = settings.getValue('TUNNEL_EXTERNAL_BRIDGE')
            bridge_ext_ip = settings.getValue('TUNNEL_EXTERNAL_BRIDGE_IP')
            tg_port2_mac = settings.getValue('TRAFFICGEN_PORT2_MAC')
            vtep_ip2 = settings.getValue('VTEP_IP2')
            self._vswitch.add_switch(bridge)

            tasks.run_task(['sudo', 'ifconfig', bridge,
                            settings.getValue('VTEP_IP1')],
                           self._logger, 'Assign ' +
                           settings.getValue('VTEP_IP1') + ' to ' + bridge,
                           False)

            tunnel_type = self._traffic['tunnel_type']

            self._vswitch.add_switch(bridge_ext)
            (_, phy1_number) = self._vswitch.add_phy_port(bridge)
            (_, phy2_number) = self._vswitch.add_tunnel_port(bridge,
                                                             vtep_ip2,
                                                             tunnel_type)
            self._vswitch.add_phy_port(bridge_ext)

            tasks.run_task(['sudo', 'ip', 'addr', 'add',
                            bridge_ext_ip,
                            'dev', bridge_ext], self._logger, 'Assign ' +
                           bridge_ext_ip + ' to ' + bridge_ext)

            tasks.run_task(['sudo', 'ip', 'link', 'set', 'dev', bridge_ext,
                            'up'], self._logger,
                           'Set ' + bridge_ext + 'status to up')

            self._vswitch.add_route(bridge,
                                    settings.getValue('VTEP_IP2_SUBNET'),
                                    bridge_ext)

            if settings.getValue('VSWITCH').endswith('Vanilla'):
                tasks.run_task(['sudo', 'arp', '-s', vtep_ip2, tg_port2_mac],
                               self._logger,
                               'Set ' + bridge_ext + ' status to up')
            else:
                self._vswitch.set_tunnel_arp(vtep_ip2,
                                             tg_port2_mac,
                                             bridge_ext)

            # Test is unidirectional for now
            self._vswitch.del_flow(bridge)
            flow1 = add_ports_to_flow(_FLOW_TEMPLATE, phy1_number,
                                      phy2_number)
            self._vswitch.add_flow(bridge, flow1)

        except:
            self._vswitch.stop()
            raise