diff options
Diffstat (limited to 'src/conf_mode')
-rwxr-xr-x | src/conf_mode/firewall.py | 1 | ||||
-rwxr-xr-x | src/conf_mode/interfaces_openvpn.py | 6 | ||||
-rwxr-xr-x | src/conf_mode/interfaces_wireless.py | 10 | ||||
-rwxr-xr-x | src/conf_mode/load-balancing_reverse-proxy.py | 8 | ||||
-rwxr-xr-x | src/conf_mode/pki.py | 36 | ||||
-rwxr-xr-x | src/conf_mode/protocols_bgp.py | 62 | ||||
-rwxr-xr-x | src/conf_mode/protocols_pim.py | 14 | ||||
-rwxr-xr-x | src/conf_mode/qos.py | 23 | ||||
-rwxr-xr-x | src/conf_mode/service_ipoe-server.py | 2 | ||||
-rwxr-xr-x | src/conf_mode/service_pppoe-server.py | 19 | ||||
-rwxr-xr-x | src/conf_mode/system_host-name.py | 10 | ||||
-rwxr-xr-x | src/conf_mode/system_ip.py | 5 | ||||
-rwxr-xr-x | src/conf_mode/vrf.py | 19 | ||||
-rw-r--r-- | src/conf_mode/vrf_vni.py | 103 |
14 files changed, 166 insertions, 152 deletions
diff --git a/src/conf_mode/firewall.py b/src/conf_mode/firewall.py index 3cf618363..e96e57154 100755 --- a/src/conf_mode/firewall.py +++ b/src/conf_mode/firewall.py @@ -44,6 +44,7 @@ nftables_conf = '/run/nftables.conf' sysfs_config = { 'all_ping': {'sysfs': '/proc/sys/net/ipv4/icmp_echo_ignore_all', 'enable': '0', 'disable': '1'}, 'broadcast_ping': {'sysfs': '/proc/sys/net/ipv4/icmp_echo_ignore_broadcasts', 'enable': '0', 'disable': '1'}, + 'directed_broadcast' : {'sysfs': '/proc/sys/net/ipv4/conf/all/bc_forwarding', 'enable': '1', 'disable': '0'}, 'ip_src_route': {'sysfs': '/proc/sys/net/ipv4/conf/*/accept_source_route'}, 'ipv6_receive_redirects': {'sysfs': '/proc/sys/net/ipv6/conf/*/accept_redirects'}, 'ipv6_src_route': {'sysfs': '/proc/sys/net/ipv6/conf/*/accept_source_route', 'enable': '0', 'disable': '-1'}, diff --git a/src/conf_mode/interfaces_openvpn.py b/src/conf_mode/interfaces_openvpn.py index 505ec55c6..0ecffd3be 100755 --- a/src/conf_mode/interfaces_openvpn.py +++ b/src/conf_mode/interfaces_openvpn.py @@ -198,6 +198,12 @@ def verify_pki(openvpn): raise ConfigError(f'Cannot use encrypted private key on openvpn interface {interface}') if 'dh_params' in tls: + if 'dh' not in pki: + raise ConfigError(f'pki dh is not configured') + proposed_dh = tls['dh_params'] + if proposed_dh not in pki['dh'].keys(): + raise ConfigError(f"pki dh '{proposed_dh}' is not configured") + pki_dh = pki['dh'][tls['dh_params']] dh_params = load_dh_parameters(pki_dh['parameters']) dh_numbers = dh_params.parameter_numbers() diff --git a/src/conf_mode/interfaces_wireless.py b/src/conf_mode/interfaces_wireless.py index 02b4a2500..c0a17c0bc 100755 --- a/src/conf_mode/interfaces_wireless.py +++ b/src/conf_mode/interfaces_wireless.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # -# Copyright (C) 2019-2020 VyOS maintainers and contributors +# Copyright (C) 2019-2024 VyOS maintainers and contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 or later as @@ -31,8 +31,9 @@ from vyos.configverify import verify_vrf from vyos.configverify import verify_bond_bridge_member from vyos.ifconfig import WiFiIf from vyos.template import render -from vyos.utils.process import call from vyos.utils.dict import dict_search +from vyos.utils.kernel import check_kmod +from vyos.utils.process import call from vyos import ConfigError from vyos import airbag airbag.enable() @@ -118,6 +119,10 @@ def verify(wifi): if 'physical_device' not in wifi: raise ConfigError('You must specify a physical-device "phy"') + physical_device = wifi['physical_device'] + if not os.path.exists(f'/sys/class/ieee80211/{physical_device}'): + raise ConfigError(f'Wirelss interface PHY "{physical_device}" does not exist!') + if 'type' not in wifi: raise ConfigError('You must specify a WiFi mode') @@ -266,6 +271,7 @@ def apply(wifi): if __name__ == '__main__': try: + check_kmod('mac80211') c = get_config() verify(c) generate(c) diff --git a/src/conf_mode/load-balancing_reverse-proxy.py b/src/conf_mode/load-balancing_reverse-proxy.py index 694a4e1ea..1569d8d71 100755 --- a/src/conf_mode/load-balancing_reverse-proxy.py +++ b/src/conf_mode/load-balancing_reverse-proxy.py @@ -75,6 +75,10 @@ def verify(lb): raise ConfigError(f'"TCP" port "{tmp_port}" is used by another service') for back, back_config in lb['backend'].items(): + if 'http-check' in back_config: + http_check = back_config['http-check'] + if 'expect' in http_check and 'status' in http_check['expect'] and 'string' in http_check['expect']: + raise ConfigError(f'"expect status" and "expect string" can not be configured together!') if 'server' not in back_config: raise ConfigError(f'"{back} server" must be configured!') for bk_server, bk_server_conf in back_config['server'].items(): @@ -84,6 +88,10 @@ def verify(lb): if {'send_proxy', 'send_proxy_v2'} <= set(bk_server_conf): raise ConfigError(f'Cannot use both "send-proxy" and "send-proxy-v2" for server "{bk_server}"') + if 'ssl' in back_config: + if {'no_verify', 'ca_certificate'} <= set(back_config['ssl']): + raise ConfigError(f'backend {back} cannot have both ssl options no-verify and ca-certificate set!') + for front, front_config in lb['service'].items(): for cert in dict_search('ssl.certificate', front_config) or []: verify_pki_certificate(lb, cert) diff --git a/src/conf_mode/pki.py b/src/conf_mode/pki.py index 3ab6ac5c3..8deec0e85 100755 --- a/src/conf_mode/pki.py +++ b/src/conf_mode/pki.py @@ -24,6 +24,8 @@ from vyos.config import config_dict_merge from vyos.configdep import set_dependents from vyos.configdep import call_dependents from vyos.configdict import node_changed +from vyos.configdiff import Diff +from vyos.configdiff import get_config_diff from vyos.defaults import directories from vyos.pki import is_ca_certificate from vyos.pki import load_certificate @@ -136,32 +138,32 @@ def get_config(config=None): if len(argv) > 1 and argv[1] == 'certbot_renew': pki['certbot_renew'] = {} - tmp = node_changed(conf, base + ['ca'], recursive=True) + tmp = node_changed(conf, base + ['ca'], recursive=True, expand_nodes=Diff.DELETE | Diff.ADD) if tmp: if 'changed' not in pki: pki.update({'changed':{}}) pki['changed'].update({'ca' : tmp}) - tmp = node_changed(conf, base + ['certificate'], recursive=True) + tmp = node_changed(conf, base + ['certificate'], recursive=True, expand_nodes=Diff.DELETE | Diff.ADD) if tmp: if 'changed' not in pki: pki.update({'changed':{}}) pki['changed'].update({'certificate' : tmp}) - tmp = node_changed(conf, base + ['dh'], recursive=True) + tmp = node_changed(conf, base + ['dh'], recursive=True, expand_nodes=Diff.DELETE | Diff.ADD) if tmp: if 'changed' not in pki: pki.update({'changed':{}}) pki['changed'].update({'dh' : tmp}) - tmp = node_changed(conf, base + ['key-pair'], recursive=True) + tmp = node_changed(conf, base + ['key-pair'], recursive=True, expand_nodes=Diff.DELETE | Diff.ADD) if tmp: if 'changed' not in pki: pki.update({'changed':{}}) pki['changed'].update({'key_pair' : tmp}) - tmp = node_changed(conf, base + ['openssh'], recursive=True) + tmp = node_changed(conf, base + ['openssh'], recursive=True, expand_nodes=Diff.DELETE | Diff.ADD) if tmp: if 'changed' not in pki: pki.update({'changed':{}}) pki['changed'].update({'openssh' : tmp}) - tmp = node_changed(conf, base + ['openvpn', 'shared-secret'], recursive=True) + tmp = node_changed(conf, base + ['openvpn', 'shared-secret'], recursive=True, expand_nodes=Diff.DELETE | Diff.ADD) if tmp: if 'changed' not in pki: pki.update({'changed':{}}) pki['changed'].update({'openvpn' : tmp}) @@ -198,6 +200,7 @@ def get_config(config=None): pki['system'] = conf.get_config_dict([], key_mangling=('-', '_'), get_first_key=True, no_tag_node_value_mangle=True) + D = get_config_diff(conf) for search in sync_search: for key in search['keys']: @@ -217,15 +220,22 @@ def get_config(config=None): if not search_dict: continue for found_name, found_path in dict_search_recursive(search_dict, key): - if found_name == item_name: - path = search['path'] - path_str = ' '.join(path + found_path) - print(f'PKI: Updating config: {path_str} {found_name}') + if isinstance(found_name, list) and item_name not in found_name: + continue + + if isinstance(found_name, str) and found_name != item_name: + continue + + path = search['path'] + path_str = ' '.join(path + found_path) + print(f'PKI: Updating config: {path_str} {item_name}') - if path[0] == 'interfaces': - ifname = found_path[0] + if path[0] == 'interfaces': + ifname = found_path[0] + if not D.node_changed_presence(path + [ifname]): set_dependents(path[1], conf, ifname) - else: + else: + if not D.node_changed_presence(path): set_dependents(path[1], conf) return pki diff --git a/src/conf_mode/protocols_bgp.py b/src/conf_mode/protocols_bgp.py index 2b16de775..44409c0e3 100755 --- a/src/conf_mode/protocols_bgp.py +++ b/src/conf_mode/protocols_bgp.py @@ -31,6 +31,7 @@ from vyos.utils.dict import dict_search from vyos.utils.network import get_interface_vrf from vyos.utils.network import is_addr_assigned from vyos.utils.process import process_named_running +from vyos.utils.process import call from vyos import ConfigError from vyos import frr from vyos import airbag @@ -50,13 +51,8 @@ def get_config(config=None): # eqivalent of the C foo ? 'a' : 'b' statement base = vrf and ['vrf', 'name', vrf, 'protocols', 'bgp'] or base_path - bgp = conf.get_config_dict( - base, - key_mangling=('-', '_'), - get_first_key=True, - no_tag_node_value_mangle=True, - with_recursive_defaults=True, - ) + bgp = conf.get_config_dict(base, key_mangling=('-', '_'), + get_first_key=True, no_tag_node_value_mangle=True) bgp['dependent_vrfs'] = conf.get_config_dict(['vrf', 'name'], key_mangling=('-', '_'), @@ -75,22 +71,29 @@ def get_config(config=None): if vrf: bgp.update({'vrf' : vrf}) # We can not delete the BGP VRF instance if there is a L3VNI configured + # FRR L3VNI must be deleted first otherwise we will see error: + # "FRR error: Please unconfigure l3vni 3000" tmp = ['vrf', 'name', vrf, 'vni'] - if conf.exists(tmp): - bgp.update({'vni' : conf.return_value(tmp)}) + if conf.exists_effective(tmp): + bgp.update({'vni' : conf.return_effective_value(tmp)}) # We can safely delete ourself from the dependent vrf list if vrf in bgp['dependent_vrfs']: del bgp['dependent_vrfs'][vrf] - bgp['dependent_vrfs'].update({'default': {'protocols': { - 'bgp': conf.get_config_dict(base_path, key_mangling=('-', '_'), - get_first_key=True, - no_tag_node_value_mangle=True)}}}) + bgp['dependent_vrfs'].update({'default': {'protocols': { + 'bgp': conf.get_config_dict(base_path, key_mangling=('-', '_'), + get_first_key=True, + no_tag_node_value_mangle=True)}}}) + if not conf.exists(base): # If bgp instance is deleted then mark it bgp.update({'deleted' : ''}) return bgp + # We have gathered the dict representation of the CLI, but there are default + # options which we need to update into the dictionary retrived. + bgp = conf.merge_defaults(bgp, recursive=True) + # We also need some additional information from the config, prefix-lists # and route-maps for instance. They will be used in verify(). # @@ -242,10 +245,6 @@ def verify(bgp): if verify_vrf_as_import(bgp['vrf'], tmp_afi, bgp['dependent_vrfs']): raise ConfigError(f'Cannot delete VRF instance "{bgp["vrf"]}", ' \ 'unconfigure "import vrf" commands!') - # We can not delete the BGP instance if a L3VNI instance exists - if 'vni' in bgp: - raise ConfigError(f'Cannot delete VRF instance "{bgp["vrf"]}", ' \ - f'unconfigure VNI "{bgp["vni"]}" first!') else: # We are running in the default VRF context, thus we can not delete # our main BGP instance if there are dependent BGP VRF instances. @@ -254,7 +253,11 @@ def verify(bgp): if vrf != 'default': if dict_search('protocols.bgp', vrf_options): raise ConfigError('Cannot delete default BGP instance, ' \ - 'dependent VRF instance(s) exist!') + 'dependent VRF instance(s) exist(s)!') + if 'vni' in vrf_options: + raise ConfigError('Cannot delete default BGP instance, ' \ + 'dependent L3VNI exists!') + return None if 'system_as' not in bgp: @@ -473,6 +476,22 @@ def verify(bgp): if peer_group_as is None or (peer_group_as != 'internal' and peer_group_as != bgp['system_as']): raise ConfigError('route-reflector-client only supported for iBGP peers') + # T5833 not all AFIs are supported for VRF + if 'vrf' in bgp and 'address_family' in peer_config: + unsupported_vrf_afi = { + 'ipv4_flowspec', + 'ipv6_flowspec', + 'ipv4_labeled_unicast', + 'ipv6_labeled_unicast', + 'ipv4_vpn', + 'ipv6_vpn', + } + for afi in peer_config['address_family']: + if afi in unsupported_vrf_afi: + raise ConfigError( + f"VRF is not allowed for address-family '{afi.replace('_', '-')}'" + ) + # Throw an error if a peer group is not configured for allow range for prefix in dict_search('listen.range', bgp) or []: # we can not use dict_search() here as prefix contains dots ... @@ -591,6 +610,13 @@ def generate(bgp): return None def apply(bgp): + if 'deleted' in bgp: + # We need to ensure that the L3VNI is deleted first. + # This is not possible with old config backend + # priority bug + if {'vrf', 'vni'} <= set(bgp): + call('vtysh -c "conf t" -c "vrf {vrf}" -c "no vni {vni}"'.format(**bgp)) + bgp_daemon = 'bgpd' # Save original configuration prior to starting any commit actions diff --git a/src/conf_mode/protocols_pim.py b/src/conf_mode/protocols_pim.py index 09c3be8df..d450d11ca 100755 --- a/src/conf_mode/protocols_pim.py +++ b/src/conf_mode/protocols_pim.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # -# Copyright (C) 2020-2023 VyOS maintainers and contributors +# Copyright (C) 2020-2024 VyOS maintainers and contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 or later as @@ -16,6 +16,7 @@ import os +from ipaddress import IPv4Address from ipaddress import IPv4Network from signal import SIGTERM from sys import exit @@ -32,6 +33,9 @@ from vyos import frr from vyos import airbag airbag.enable() +RESERVED_MC_NET = '224.0.0.0/24' + + def get_config(config=None): if config: conf = config @@ -92,9 +96,15 @@ def verify(pim): if 'interface' not in pim: raise ConfigError('PIM require defined interfaces!') - for interface in pim['interface']: + for interface, interface_config in pim['interface'].items(): verify_interface_exists(interface) + # Check join group in reserved net + if 'igmp' in interface_config and 'join' in interface_config['igmp']: + for join_addr in interface_config['igmp']['join']: + if IPv4Address(join_addr) in IPv4Network(RESERVED_MC_NET): + raise ConfigError(f'Groups within {RESERVED_MC_NET} are reserved and cannot be joined!') + if 'rp' in pim: if 'address' not in pim['rp']: raise ConfigError('PIM rendezvous point needs to be defined!') diff --git a/src/conf_mode/qos.py b/src/conf_mode/qos.py index 3dfb4bab8..ccfc8f6b8 100755 --- a/src/conf_mode/qos.py +++ b/src/conf_mode/qos.py @@ -70,6 +70,22 @@ def get_shaper(qos, interface_config, direction): return (map_vyops_tc[shaper_type], shaper_config) + +def _clean_conf_dict(conf): + """ + Delete empty nodes from config e.g. + match ADDRESS30 { + ip { + source {} + } + } + """ + if isinstance(conf, dict): + return {node: _clean_conf_dict(val) for node, val in conf.items() if val != {} and _clean_conf_dict(val) != {}} + else: + return conf + + def get_config(config=None): if config: conf = config @@ -120,6 +136,13 @@ def get_config(config=None): if 'queue_limit' not in qos['policy'][policy][p_name]['precedence'][precedence]: qos['policy'][policy][p_name]['precedence'][precedence]['queue_limit'] = \ str(int(4 * max_thr)) + # cleanup empty match config + if 'class' in p_config: + for cls, cls_config in p_config['class'].items(): + if 'match' in cls_config: + cls_config['match'] = _clean_conf_dict(cls_config['match']) + if cls_config['match'] == {}: + del cls_config['match'] return qos diff --git a/src/conf_mode/service_ipoe-server.py b/src/conf_mode/service_ipoe-server.py index 11e950782..28b7fb03c 100755 --- a/src/conf_mode/service_ipoe-server.py +++ b/src/conf_mode/service_ipoe-server.py @@ -66,7 +66,7 @@ def verify(ipoe): raise ConfigError('No IPoE interface configured') for interface, iface_config in ipoe['interface'].items(): - verify_interface_exists(interface) + verify_interface_exists(interface, warning_only=True) if 'client_subnet' in iface_config and 'vlan' in iface_config: raise ConfigError('Option "client-subnet" and "vlan" are mutually exclusive, ' 'use "client-ip-pool" instead!') diff --git a/src/conf_mode/service_pppoe-server.py b/src/conf_mode/service_pppoe-server.py index b9d174933..c95f976d3 100755 --- a/src/conf_mode/service_pppoe-server.py +++ b/src/conf_mode/service_pppoe-server.py @@ -84,12 +84,29 @@ def verify_pado_delay(pppoe): pado_delay = pppoe['pado_delay'] delays_without_sessions = pado_delay['delays_without_sessions'] + if 'disable' in delays_without_sessions: + raise ConfigError( + 'Number of sessions must be specified for "pado-delay disable"' + ) + if len(delays_without_sessions) > 1: raise ConfigError( f'Cannot add more then ONE pado-delay without sessions, ' f'but {len(delays_without_sessions)} were set' ) + if 'disable' in [delay[0] for delay in pado_delay['delays_with_sessions']]: + # need to sort delays by sessions to verify if there is no delay + # for sessions after disabling + sorted_pado_delay = sorted(pado_delay['delays_with_sessions'], key=lambda k_v: k_v[1]) + last_delay = sorted_pado_delay[-1] + + if last_delay[0] != 'disable': + raise ConfigError( + f'Cannot add pado-delay after disabled sessions, but ' + f'"pado-delay {last_delay[0]} sessions {last_delay[1]}" was set' + ) + def verify(pppoe): if not pppoe: return None @@ -105,7 +122,7 @@ def verify(pppoe): # Check is interface exists in the system for interface in pppoe['interface']: - verify_interface_exists(interface) + verify_interface_exists(interface, warning_only=True) return None diff --git a/src/conf_mode/system_host-name.py b/src/conf_mode/system_host-name.py index 8975cadb6..3f245f166 100755 --- a/src/conf_mode/system_host-name.py +++ b/src/conf_mode/system_host-name.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # -# Copyright (C) 2018-2023 VyOS maintainers and contributors +# Copyright (C) 2018-2024 VyOS maintainers and contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 or later as @@ -22,6 +22,7 @@ import vyos.hostsd_client from vyos.base import Warning from vyos.config import Config +from vyos.configdict import leaf_node_changed from vyos.ifconfig import Section from vyos.template import is_ip from vyos.utils.process import cmd @@ -37,6 +38,7 @@ default_config_data = { 'domain_search': [], 'nameserver': [], 'nameservers_dhcp_interfaces': {}, + 'snmpd_restart_reqired': False, 'static_host_mapping': {} } @@ -52,6 +54,10 @@ def get_config(config=None): hosts['hostname'] = conf.return_value(['system', 'host-name']) + base = ['system'] + if leaf_node_changed(conf, base + ['host-name']) or leaf_node_changed(conf, base + ['domain-name']): + hosts['snmpd_restart_reqired'] = True + # This may happen if the config is not loaded yet, # e.g. if run by cloud-init if not hosts['hostname']: @@ -171,7 +177,7 @@ def apply(config): call("systemctl restart rsyslog.service") # If SNMP is running, restart it too - if process_named_running('snmpd'): + if process_named_running('snmpd') and config['snmpd_restart_reqired']: call('systemctl restart snmpd.service') return None diff --git a/src/conf_mode/system_ip.py b/src/conf_mode/system_ip.py index b945b51f2..2a0bda91a 100755 --- a/src/conf_mode/system_ip.py +++ b/src/conf_mode/system_ip.py @@ -81,11 +81,6 @@ def apply(opt): value = '0' if (tmp != None) else '1' write_file('/proc/sys/net/ipv4/conf/all/forwarding', value) - # enable/disable IPv4 directed broadcast forwarding - tmp = dict_search('disable_directed_broadcast', opt) - value = '0' if (tmp != None) else '1' - write_file('/proc/sys/net/ipv4/conf/all/bc_forwarding', value) - # configure multipath tmp = dict_search('multipath.ignore_unreachable_nexthops', opt) value = '1' if (tmp != None) else '0' diff --git a/src/conf_mode/vrf.py b/src/conf_mode/vrf.py index 1fc813189..8d8c234c0 100755 --- a/src/conf_mode/vrf.py +++ b/src/conf_mode/vrf.py @@ -130,11 +130,6 @@ def get_config(config=None): tmp = {'policy' : {'route-map' : conf.get_config_dict(['policy', 'route-map'], get_first_key=True)}} - # L3VNI setup is done via vrf_vni.py as it must be de-configured (on node - # deletetion prior to the BGP process. Tell the Jinja2 template no VNI - # setup is needed - vrf.update({'no_vni' : ''}) - # Merge policy dict into "regular" config dict vrf = dict_merge(tmp, vrf) return vrf @@ -315,6 +310,20 @@ def apply(vrf): for chain, rule in nftables_rules.items(): cmd(f'nft flush chain inet vrf_zones {chain}') + # Return default ip rule values + if 'name' not in vrf: + for afi in ['-4', '-6']: + # move lookup local to pref 0 (from 32765) + if not has_rule(afi, 0, 'local'): + call(f'ip {afi} rule add pref 0 from all lookup local') + if has_rule(afi, 32765, 'local'): + call(f'ip {afi} rule del pref 32765 table local') + + if has_rule(afi, 1000, 'l3mdev'): + call(f'ip {afi} rule del pref 1000 l3mdev protocol kernel') + if has_rule(afi, 2000, 'l3mdev'): + call(f'ip {afi} rule del pref 2000 l3mdev unreachable') + # Apply FRR filters zebra_daemon = 'zebra' # Save original configuration prior to starting any commit actions diff --git a/src/conf_mode/vrf_vni.py b/src/conf_mode/vrf_vni.py deleted file mode 100644 index 8dab164d7..000000000 --- a/src/conf_mode/vrf_vni.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python3 -# -# Copyright (C) 2023-2024 VyOS maintainers and contributors -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License version 2 or later as -# published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. - -from sys import argv -from sys import exit - -from vyos.config import Config -from vyos.template import render_to_string -from vyos import ConfigError -from vyos import frr -from vyos import airbag -airbag.enable() - -def get_config(config=None): - if config: - conf = config - else: - conf = Config() - - vrf_name = None - if len(argv) > 1: - vrf_name = argv[1] - else: - return None - - # Using duplicate L3VNIs makes no sense - it's also forbidden in FRR, - # thus VyOS CLI must deny this, too. Instead of getting only the dict for - # the requested VRF and den comparing it with depenent VRfs to not have any - # duplicate we will just grad ALL VRFs by default but only render/apply - # the configuration for the requested VRF - that makes the code easier and - # hopefully less error prone - vrf = conf.get_config_dict(['vrf'], key_mangling=('-', '_'), - no_tag_node_value_mangle=True, - get_first_key=True) - - # Store name of VRF we are interested in for FRR config rendering - vrf.update({'only_vrf' : vrf_name}) - - return vrf - -def verify(vrf): - if not vrf: - return - - if len(argv) < 2: - raise ConfigError('VRF parameter not specified when valling vrf_vni.py') - - if 'name' in vrf: - vni_ids = [] - for name, vrf_config in vrf['name'].items(): - # VRF VNI (Virtual Network Identifier) must be unique on the system - if 'vni' in vrf_config: - if vrf_config['vni'] in vni_ids: - raise ConfigError(f'VRF "{name}" VNI is not unique!') - vni_ids.append(vrf_config['vni']) - - return None - -def generate(vrf): - if not vrf: - return - - vrf['new_frr_config'] = render_to_string('frr/zebra.vrf.route-map.frr.j2', vrf) - return None - -def apply(vrf): - frr_daemon = 'zebra' - - # add configuration to FRR - frr_cfg = frr.FRRConfig() - frr_cfg.load_configuration(frr_daemon) - # There is only one VRF inside the dict as we read only one in get_config() - if vrf and 'only_vrf' in vrf: - vrf_name = vrf['only_vrf'] - frr_cfg.modify_section(f'^vrf {vrf_name}', stop_pattern='^exit-vrf', remove_stop_mark=True) - if vrf and 'new_frr_config' in vrf: - frr_cfg.add_before(frr.default_add_before, vrf['new_frr_config']) - frr_cfg.commit_configuration(frr_daemon) - - return None - -if __name__ == '__main__': - try: - c = get_config() - verify(c) - generate(c) - apply(c) - except ConfigError as e: - print(e) - exit(1) |