summaryrefslogtreecommitdiff
path: root/python
diff options
context:
space:
mode:
Diffstat (limited to 'python')
-rw-r--r--python/vyos/configdict.py77
-rw-r--r--python/vyos/configverify.py36
-rw-r--r--python/vyos/ifconfig/interface.py84
-rw-r--r--python/vyos/qos/base.py16
4 files changed, 168 insertions, 45 deletions
diff --git a/python/vyos/configdict.py b/python/vyos/configdict.py
index d316ece3b..8c311616c 100644
--- a/python/vyos/configdict.py
+++ b/python/vyos/configdict.py
@@ -20,6 +20,7 @@ import os
import json
from vyos.config import Config
+from vyos.config import ConfigDict
from vyos.utils.dict import dict_search
from vyos.utils.process import cmdl
@@ -233,37 +234,53 @@ def is_member(conf, interface, intftype=None):
def is_mirror_intf(conf, interface, direction=None):
"""
- Check whether the passed interface is used for port mirroring. Direction
- is optional, if not passed it will search all known direction
- (currently ingress and egress)
+ Check whether the passed interface is used as the mirror or redirect
+ target of other interfaces, including VLAN (vif, vif-s, vif-c)
+ sub-interfaces. Direction is optional, if not passed it will search all
+ known direction (currently ingress and egress)
Returns:
None -> Interface is not a monitor interface
- Array() -> This interface is a monitor interface of interfaces
+ dict -> {source interface name : source interface config dict} for every
+ interface mirroring or redirecting into the passed interface
"""
- from vyos.ifconfig import Section
-
directions = ['ingress', 'egress']
if direction not in directions + [None]:
raise ValueError(f'Unknown interface mirror direction "{direction}"')
direction = directions if direction == None else [direction]
- ret_val = None
- base = ['interfaces']
-
- for dir in direction:
- for iftype in conf.list_nodes(base):
- iftype_base = base + [iftype]
- for intf in conf.list_nodes(iftype_base):
- mirror = iftype_base + [intf, 'mirror', dir, interface]
- if conf.exists(mirror):
- path = ['interfaces', Section.section(intf), intf]
- tmp = conf.get_config_dict(path, key_mangling=('-', '_'),
- get_first_key=True)
- ret_val = {intf : tmp}
+ ret_val = {}
+ interfaces = conf.get_config_dict(
+ ['interfaces'],
+ key_mangling=('-', '_'),
+ get_first_key=True,
+ no_tag_node_value_mangle=True,
+ )
- return ret_val
+ def add_source(ifname, config):
+ targets = [config.get('mirror', {}).get(dir) for dir in direction]
+ # redirect only works on ingress
+ if 'ingress' in direction:
+ targets.append(config.get('redirect'))
+ if interface not in targets:
+ return
+ ret_val[ifname] = config
+ # QoS marker, see get_interface_dict()
+ if conf.exists(['qos', 'interface', ifname]):
+ ret_val[ifname]['qos'] = {}
+
+ for intfs in interfaces.values():
+ for intf, config in intfs.items():
+ add_source(intf, config)
+ for vif, vif_config in config.get('vif', {}).items():
+ add_source(f'{intf}.{vif}', vif_config)
+ for vif_s, vif_s_config in config.get('vif_s', {}).items():
+ add_source(f'{intf}.{vif_s}', vif_s_config)
+ for vif_c, vif_c_config in vif_s_config.get('vif_c', {}).items():
+ add_source(f'{intf}.{vif_s}.{vif_c}', vif_c_config)
+
+ return ret_val or None
def has_address_configured(conf, intf):
"""
@@ -564,6 +581,9 @@ def get_interface_dict(config, base, ifname='', recursive_defaults=True, with_pk
dict['ipv6']['address'].update({'interface_identifier_old': interface_identifier})
for vif, vif_config in dict.get('vif', {}).items():
+ # T6393: carry the CLI interfaces tree, see Config.get_config_dict()
+ dict['vif'][vif] = ConfigDict(vif_config)
+ dict['vif'][vif].interfaces_root = dict.interfaces_root
# Add subinterface name to dictionary
dict['vif'][vif].update({'ifname' : f'{ifname}.{vif}'})
@@ -584,6 +604,10 @@ def get_interface_dict(config, base, ifname='', recursive_defaults=True, with_pk
bridge = is_member(config, f'{ifname}.{vif}', 'bridge')
if bridge: dict['vif'][vif].update({'is_bridge_member' : bridge})
+ # Check if it is a monitor interface
+ mirror = is_mirror_intf(config, f'{ifname}.{vif}')
+ if mirror: dict['vif'][vif].update({'is_mirror_intf' : mirror})
+
# Check if any DHCP options changed which require a client restart
dhcp = is_node_changed(config, base + [ifname, 'vif', vif, 'dhcp-options'])
if dhcp: dict['vif'][vif].update({'dhcp_options_changed' : {}})
@@ -591,6 +615,8 @@ def get_interface_dict(config, base, ifname='', recursive_defaults=True, with_pk
if dhcpv6: dict['vif'][vif].update({'dhcpv6_options_changed' : {}})
for vif_s, vif_s_config in dict.get('vif_s', {}).items():
+ dict['vif_s'][vif_s] = ConfigDict(vif_s_config)
+ dict['vif_s'][vif_s].interfaces_root = dict.interfaces_root
# Add subinterface name to dictionary
dict['vif_s'][vif_s].update({'ifname' : f'{ifname}.{vif_s}'})
@@ -612,6 +638,10 @@ def get_interface_dict(config, base, ifname='', recursive_defaults=True, with_pk
bridge = is_member(config, f'{ifname}.{vif_s}', 'bridge')
if bridge: dict['vif_s'][vif_s].update({'is_bridge_member' : bridge})
+ # Check if it is a monitor interface
+ mirror = is_mirror_intf(config, f'{ifname}.{vif_s}')
+ if mirror: dict['vif_s'][vif_s].update({'is_mirror_intf' : mirror})
+
# Check if any DHCP options changed which require a client restart
dhcp = is_node_changed(config, base + [ifname, 'vif-s', vif_s, 'dhcp-options'])
if dhcp: dict['vif_s'][vif_s].update({'dhcp_options_changed' : {}})
@@ -619,6 +649,8 @@ def get_interface_dict(config, base, ifname='', recursive_defaults=True, with_pk
if dhcpv6: dict['vif_s'][vif_s].update({'dhcpv6_options_changed' : {}})
for vif_c, vif_c_config in vif_s_config.get('vif_c', {}).items():
+ dict['vif_s'][vif_s]['vif_c'][vif_c] = ConfigDict(vif_c_config)
+ dict['vif_s'][vif_s]['vif_c'][vif_c].interfaces_root = dict.interfaces_root
# Add subinterface name to dictionary
dict['vif_s'][vif_s]['vif_c'][vif_c].update({'ifname' : f'{ifname}.{vif_s}.{vif_c}'})
@@ -642,6 +674,11 @@ def get_interface_dict(config, base, ifname='', recursive_defaults=True, with_pk
if bridge: dict['vif_s'][vif_s]['vif_c'][vif_c].update(
{'is_bridge_member' : bridge})
+ # Check if it is a monitor interface
+ mirror = is_mirror_intf(config, f'{ifname}.{vif_s}.{vif_c}')
+ if mirror: dict['vif_s'][vif_s]['vif_c'][vif_c].update(
+ {'is_mirror_intf' : mirror})
+
# Check if any DHCP options changed which require a client restart
dhcp = is_node_changed(config, base + [ifname, 'vif-s', vif_s, 'vif-c', vif_c, 'dhcp-options'])
if dhcp: dict['vif_s'][vif_s]['vif_c'][vif_c].update({'dhcp_options_changed' : {}})
diff --git a/python/vyos/configverify.py b/python/vyos/configverify.py
index d918c53bb..714f544f0 100644
--- a/python/vyos/configverify.py
+++ b/python/vyos/configverify.py
@@ -188,21 +188,43 @@ def verify_mirror_redirect(config):
# limitation from the past
raise ConfigError('Cannot use QoS together with mirror!')
+ def vlan_configured(interface, vlan):
+ # vif or vif-s, or a vif-c below a vif-s
+ if len(vlan) == 1:
+ return (('vif' in interface and vlan[0] in interface['vif']) or
+ ('vif-s' in interface and vlan[0] in interface['vif-s']))
+ if len(vlan) == 2 and 'vif-s' in interface and vlan[0] in interface['vif-s']:
+ vif_s = interface['vif-s'][vlan[0]]
+ return 'vif-c' in vif_s and vlan[1] in vif_s['vif-c']
+ return False
+
+ def verify_target(kind, target):
+ # T6393: interface types are committed in priority order, the target
+ # may only be defined on the CLI and not (yet) exist in the Kernel.
+ # tc(8) can not reach a target in another netns
+ ifname, *vlan = target.split('.')
+ for interfaces in getattr(config, 'interfaces_root', {}).values():
+ if ifname in interfaces:
+ if 'netns' in interfaces[ifname]:
+ raise ConfigError(
+ f'Requested {kind} interface "{target}" is in a '
+ 'network namespace!'
+ )
+ if not vlan or vlan_configured(interfaces[ifname], vlan):
+ return
+ if not interface_exists(target):
+ raise ConfigError(f'Requested {kind} interface "{target}" does not exist!')
+
if 'mirror' in config:
for direction, mirror_interface in config['mirror'].items():
- if not interface_exists(mirror_interface):
- raise ConfigError(f'Requested mirror interface "{mirror_interface}" '\
- 'does not exist!')
+ verify_target('mirror', mirror_interface)
if mirror_interface == config['ifname']:
raise ConfigError(f'Cannot mirror "{direction}" traffic back '\
'the originating interface!')
if 'redirect' in config:
- redirect_ifname = config['redirect']
- if not interface_exists(redirect_ifname):
- raise ConfigError(f'Requested redirect interface "{redirect_ifname}" '\
- 'does not exist!')
+ verify_target('redirect', config['redirect'])
def verify_authentication(config):
"""
diff --git a/python/vyos/ifconfig/interface.py b/python/vyos/ifconfig/interface.py
index b00bbc18a..7ae85ae79 100644
--- a/python/vyos/ifconfig/interface.py
+++ b/python/vyos/ifconfig/interface.py
@@ -26,6 +26,7 @@ from netifaces import ifaddresses # pylint: disable = no-name-in-module
from socket import AF_INET
from socket import AF_INET6
+from vyos.base import Warning
from vyos.configdict import list_diff
from vyos.configdict import dict_merge
from vyos.configdict import get_vlan_ids
@@ -41,6 +42,7 @@ from vyos.utils.network import get_interface_config
from vyos.utils.network import get_interface_address
from vyos.utils.network import get_interface_namespace
from vyos.utils.network import get_vrf_tableid
+from vyos.utils.network import interface_exists
from vyos.utils.network import is_netns_interface
from vyos.utils.process import is_systemd_service_active
from vyos.utils.process import stop_systemd_unit
@@ -1729,33 +1731,69 @@ class Interface(Control):
# Please refer to the document for details
# - https://man7.org/linux/man-pages/man8/tc.8.html
# - https://man7.org/linux/man-pages/man8/tc-mirred.8.html
- # Depending if we are the source or the target interface of the port
- # mirror we need to setup some variables.
# Don't allow for netns yet
if 'netns' in self.config:
return None
- source_if = self.ifname
+ # Our own mirror/redirect configuration
+ self._apply_mirror_redirect(self.ifname, self.config)
- mirror_config = None
- if 'mirror' in self.config:
- mirror_config = self.config['mirror']
- if 'is_mirror_intf' in self.config:
- source_if = next(iter(self.config['is_mirror_intf']))
- mirror_config = self.config['is_mirror_intf'][source_if].get('mirror', None)
-
- redirect_config = None
+ # Install the filters of interfaces mirroring or redirecting into us,
+ # they could not do it themselves if we did not exist yet (T3089, T6393)
+ for source_if, source_config in self.config.get('is_mirror_intf', {}).items():
+ if not interface_exists(source_if):
+ continue
+ if self._mirror_redirect_installed(source_if, source_config):
+ continue
+ self._apply_mirror_redirect(source_if, source_config)
+
+ def _mirred_filters(self, dev, parent):
+ """tc(8) filters with a mirred action on dev/parent: (filter, target)"""
+ out, _ = self._popen(f'tc -j filter show dev {dev} parent {parent}')
+ for tc_filter in json.loads(out or '[]'):
+ for action in dict_search('options.actions', tc_filter) or []:
+ if action.get('kind') == 'mirred':
+ yield tc_filter, action.get('to_dev')
+
+ def _mirror_redirect_installed(self, source_if, config):
+ """Check if source_if has all of its tc(8) mirred filters into us"""
+ parents = []
+ for direction, target in config.get('mirror', {}).items():
+ if target == self.ifname:
+ parents.append('ffff:' if direction == 'ingress' else '1:')
+ if config.get('redirect') == self.ifname:
+ parents.append('ffff:')
+ for parent in parents:
+ targets = [target for _, target in self._mirred_filters(source_if, parent)]
+ if self.ifname not in targets:
+ return False
+ return True
+ def _apply_mirror_redirect(self, source_if, config):
+ """
+ Install the tc(8) mirror or redirect filters of source_if according to
+ its configuration dictionary, we are either source_if or its target.
+ """
# clear existing ingess - ignore errors (e.g. "Error: Cannot find specified
# qdisc on specified device") - we simply cleanup all stuff here
- if not 'qos' in self.config:
+ if 'qos' not in config:
self._popen(f'tc qdisc del dev {source_if} root 2>/dev/null')
self._popen(f'tc qdisc del dev {source_if} ingress 2>/dev/null')
+ else:
+ # keep the QoS qdiscs and filters, only remove our own redirect filter
+ self._popen(f'tc filter del dev {source_if} parent ffff: pref 65000 2>/dev/null')
# Apply interface mirror policy
- if mirror_config:
- for direction, target_if in mirror_config.items():
+ if 'mirror' in config:
+ for direction, target_if in config['mirror'].items():
+ if not interface_exists(target_if):
+ Warning(
+ f'Mirror target "{target_if}" of "{source_if}" does not '
+ 'exist yet, tc filter will be installed once it is created'
+ )
+ continue
+
if direction == 'ingress':
handle = 'ffff: ingress'
parent = 'ffff:'
@@ -1773,13 +1811,23 @@ class Interface(Control):
if err: print('tc filter for mirror port failed')
# Apply interface traffic redirection policy
- elif 'redirect' in self.config:
- _, err = self._popen(f'tc qdisc add dev {source_if} handle ffff: ingress')
+ elif 'redirect' in config:
+ target_if = config['redirect']
+ if not interface_exists(target_if):
+ Warning(
+ f'Redirect target "{target_if}" of "{source_if}" does not '
+ 'exist yet, tc filter will be installed once it is created'
+ )
+ return None
+
+ # replace keeps an ingress qdisc of a QoS policy in place
+ _, err = self._popen(f'tc qdisc replace dev {source_if} handle ffff: ingress')
if err: print(f'tc qdisc add for redirect failed!')
- target_if = self.config['redirect']
+ # Lowest priority: an ingress QoS policy polices and redirects the
+ # traffic it matches first, see vyos.qos.base
_, err = self._popen(f'tc filter add dev {source_if} parent ffff: protocol '\
- f'all prio 10 u32 match u32 0 0 flowid 1:1 action mirred '\
+ f'all prio 65000 u32 match u32 0 0 flowid 1:1 action mirred '\
f'egress redirect dev {target_if}')
if err: print('tc filter for redirect failed')
diff --git a/python/vyos/qos/base.py b/python/vyos/qos/base.py
index 651d3f1e1..736b197e1 100644
--- a/python/vyos/qos/base.py
+++ b/python/vyos/qos/base.py
@@ -242,6 +242,12 @@ class QoSBase:
import pprint
pprint.pprint(config)
+ # T6393: traffic of an ingress limiter on an interface with "redirect"
+ # is redirected after policing, see qos.py apply_interface()
+ redirect = []
+ if 'redirect' in config:
+ redirect = ['action', 'mirred', 'egress', 'redirect', 'dev', config['redirect']]
+
if 'class' in config:
# T9134: every class match is installed as its own tc filter, and
# tc ties a filter priority ("prio"/"pref") to a single protocol -
@@ -431,6 +437,7 @@ class QoSBase:
# add pedit before flowid for filters without police
if dscp_action:
filter_cmd += dscp_action
+ filter_cmd += redirect
filter_cmd += ['flowid', f'{self._parent:x}:{cls:x}']
self._cmdl(filter_cmd)
@@ -450,6 +457,9 @@ class QoSBase:
filter_cmd += ['conform-exceed', str(action)]
if 'not_exceed' in cls_config:
action = cls_config['not_exceed']
+ # "ok" would end the action chain before the redirect
+ if redirect and action == 'ok':
+ action = 'pipe'
filter_cmd[-1] += f'/{action}'
if 'bandwidth' in cls_config:
@@ -468,6 +478,7 @@ class QoSBase:
filter_cmd += dscp_action
cls = int(cls)
+ filter_cmd += redirect
filter_cmd += ['flowid', f'{self._parent:x}:{cls:x}']
self._cmdl(filter_cmd)
@@ -547,6 +558,9 @@ class QoSBase:
filter_cmd += ['conform-exceed', str(action)]
if 'not_exceed' in config['default']:
action = config['default']['not_exceed']
+ # "ok" would end the action chain before the redirect
+ if redirect and action == 'ok':
+ action = 'pipe'
filter_cmd[-1] += f'/{action}'
if 'bandwidth' in config['default']:
@@ -561,6 +575,8 @@ class QoSBase:
mtu = config['default']['mtu']
filter_cmd += ['mtu', str(mtu)]
+ filter_cmd += redirect
+
if 'class' in config:
filter_cmd += ['flowid', f'{self._parent:x}:{default_cls_id:x}']