Page MenuHomeVyOS Platform

No OneTemporary

Size
92 KB
Referenced Files
None
Subscribers
None
diff --git a/python/vyos/frr.py b/python/vyos/frr.py
index e5253350a..a8f115d9a 100644
--- a/python/vyos/frr.py
+++ b/python/vyos/frr.py
@@ -1,531 +1,536 @@
# Copyright 2020 VyOS maintainers and contributors <maintainers@vyos.io>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
r"""
A Library for interracting with the FRR daemon suite.
It supports simple configuration manipulation and loading using the official tools
supplied with FRR (vtysh and frr-reload)
All configuration management and manipulation is done using strings and regex.
Example Usage
#####
# Reading configuration from frr:
```
>>> original_config = get_configuration()
>>> repr(original_config)
'!\nfrr version 7.3.1\nfrr defaults traditional\nhostname debian\n......
```
# Modify a configuration section:
```
>>> new_bgp_section = 'router bgp 65000\n neighbor 192.0.2.1 remote-as 65000\n'
>>> modified_config = replace_section(original_config, new_bgp_section, replace_re=r'router bgp \d+')
>>> repr(modified_config)
'............router bgp 65000\n neighbor 192.0.2.1 remote-as 65000\n...........'
```
Remove a configuration section:
```
>>> modified_config = remove_section(original_config, r'router ospf')
```
Test the new configuration:
```
>>> try:
>>> mark_configuration(modified configuration)
>>> except ConfigurationNotValid as e:
>>> print('resulting configuration is not valid')
>>> sys.exit(1)
```
Apply the new configuration:
```
>>> try:
>>> replace_configuration(modified_config)
>>> except CommitError as e:
>>> print('Exception while commiting the supplied configuration')
>>> print(e)
>>> exit(1)
```
"""
import tempfile
import re
from vyos import util
from vyos.util import chown
from vyos.util import cmd
import logging
from logging.handlers import SysLogHandler
import os
LOG = logging.getLogger(__name__)
DEBUG = os.path.exists('/tmp/vyos.frr.debug')
if DEBUG:
LOG.setLevel(logging.DEBUG)
ch = SysLogHandler(address='/dev/log')
ch2 = logging.StreamHandler()
LOG.addHandler(ch)
LOG.addHandler(ch2)
_frr_daemons = ['zebra', 'bgpd', 'fabricd', 'isisd', 'ospf6d', 'ospfd', 'pbrd',
'pimd', 'ripd', 'ripngd', 'sharpd', 'staticd', 'vrrpd', 'ldpd',
'bfdd']
path_vtysh = '/usr/bin/vtysh'
path_frr_reload = '/usr/lib/frr/frr-reload.py'
path_config = '/run/frr'
default_add_before = r'(ip prefix-list .*|route-map .*|line vty|end)'
class FrrError(Exception):
pass
class ConfigurationNotValid(FrrError):
"""
The configuratioin supplied to vtysh is not valid
"""
pass
class CommitError(FrrError):
"""
Commiting the supplied configuration failed to commit by a unknown reason
see commit error and/or run mark_configuration on the specified configuration
to se error generated
used by: reload_configuration()
"""
pass
class ConfigSectionNotFound(FrrError):
"""
Removal of configuration failed because it is not existing in the supplied configuration
"""
pass
def get_configuration(daemon=None, marked=False):
""" Get current running FRR configuration
daemon: Collect only configuration for the specified FRR daemon,
supplying daemon=None retrieves the complete configuration
marked: Mark the configuration with "end" tags
return: string containing the running configuration from frr
"""
if daemon and daemon not in _frr_daemons:
raise ValueError(f'The specified daemon type is not supported {repr(daemon)}')
cmd = f"{path_vtysh} -c 'show run'"
if daemon:
cmd += f' -d {daemon}'
output, code = util.popen(cmd, stderr=util.STDOUT)
if code:
raise OSError(code, output)
config = output.replace('\r', '')
# Remove first header lines from FRR config
config = config.split("\n", 3)[-1]
# Mark the configuration with end tags
if marked:
config = mark_configuration(config)
return config
def mark_configuration(config):
""" Add end marks and Test the configuration for syntax faults
If the configuration is valid a marked version of the configuration is returned,
or else it failes with a ConfigurationNotValid Exception
config: The configuration string to mark/test
return: The marked configuration from FRR
"""
output, code = util.popen(f"{path_vtysh} -m -f -", stderr=util.STDOUT, input=config)
if code == 2:
raise ConfigurationNotValid(str(output))
elif code:
raise OSError(code, output)
config = output.replace('\r', '')
return config
def reload_configuration(config, daemon=None):
""" Execute frr-reload with the new configuration
This will try to reapply the supplied configuration inside FRR.
The configuration needs to be a complete configuration from the integrated config or
from a daemon.
config: The configuration to apply
daemon: Apply the conigutaion to the specified FRR daemon,
supplying daemon=None applies to the integrated configuration
return: None
"""
if daemon and daemon not in _frr_daemons:
raise ValueError(f'The specified daemon type is not supported {repr(daemon)}')
f = tempfile.NamedTemporaryFile('w')
f.write(config)
f.flush()
LOG.debug(f'reload_configuration: Reloading config using temporary file: {f.name}')
cmd = f'{path_frr_reload} --reload'
if daemon:
cmd += f' --daemon {daemon}'
if DEBUG:
cmd += f' --debug --stdout'
cmd += f' {f.name}'
LOG.debug(f'reload_configuration: Executing command against frr-reload: "{cmd}"')
output, code = util.popen(cmd, stderr=util.STDOUT)
f.close()
for i, e in enumerate(output.split('\n')):
LOG.debug(f'frr-reload output: {i:3} {e}')
if code == 1:
raise CommitError('FRR configuration failed while running commit. Please ' \
'enable debugging to examine logs.\n\n\n' \
'To enable debugging run: "touch /tmp/vyos.frr.debug" ' \
'and "sudo systemctl stop vyos-configd"')
elif code:
raise OSError(code, output)
return output
def save_configuration():
""" T3217: Save FRR configuration to /run/frr/config/frr.conf """
return cmd(f'{path_vtysh} -n -w')
def execute(command):
""" Run commands inside vtysh
command: str containing commands to execute inside a vtysh session
"""
if not isinstance(command, str):
raise ValueError(f'command needs to be a string: {repr(command)}')
cmd = f"{path_vtysh} -c '{command}'"
output, code = util.popen(cmd, stderr=util.STDOUT)
if code:
raise OSError(code, output)
config = output.replace('\r', '')
return config
def configure(lines, daemon=False):
""" run commands inside config mode vtysh
lines: list or str conaining commands to execute inside a configure session
only one command executed on each configure()
Executing commands inside a subcontext uses the list to describe the context
ex: ['router bgp 6500', 'neighbor 192.0.2.1 remote-as 65000']
return: None
"""
if isinstance(lines, str):
lines = [lines]
elif not isinstance(lines, list):
raise ValueError('lines needs to be string or list of commands')
if daemon and daemon not in _frr_daemons:
raise ValueError(f'The specified daemon type is not supported {repr(daemon)}')
cmd = f'{path_vtysh}'
if daemon:
cmd += f' -d {daemon}'
cmd += " -c 'configure terminal'"
for x in lines:
cmd += f" -c '{x}'"
output, code = util.popen(cmd, stderr=util.STDOUT)
if code == 1:
raise ConfigurationNotValid(f'Configuration FRR failed: {repr(output)}')
elif code:
raise OSError(code, output)
config = output.replace('\r', '')
return config
def _replace_section(config, replacement, replace_re, before_re):
r"""Replace a section of FRR config
config: full original configuration
replacement: replacement configuration section
replace_re: The regex to replace
example: ^router bgp \d+$.?*^!$
this will replace everything between ^router bgp X$ and ^!$
before_re: When replace_re is not existant, the config will be added before this tag
example: ^line vty$
return: modified configuration as a text file
"""
# DEPRECATED, this is replaced by a new implementation
# Check if block is configured, remove the existing instance else add a new one
if re.findall(replace_re, config, flags=re.MULTILINE | re.DOTALL):
# Section is in the configration, replace it
return re.sub(replace_re, replacement, config, count=1,
flags=re.MULTILINE | re.DOTALL)
if before_re:
if not re.findall(before_re, config, flags=re.MULTILINE | re.DOTALL):
raise ConfigSectionNotFound(f"Config section {before_re} not found in config")
# If no section is in the configuration, add it before the line vty line
return re.sub(before_re, rf'{replacement}\n\g<1>', config, count=1,
flags=re.MULTILINE | re.DOTALL)
raise ConfigSectionNotFound(f"Config section {replacement} not found in config")
def replace_section(config, replacement, from_re, to_re=r'!', before_re=r'line vty'):
r"""Replace a section of FRR config
config: full original configuration
replacement: replacement configuration section
from_re: Regex for the start of section matching
example: 'router bgp \d+'
to_re: Regex for stop of section matching
default: '!'
example: '!' or 'end'
before_re: When from_re/to_re does not return a match, the config will
be added before this tag
default: ^line vty$
startline and endline tags will be automatically added to the resulting from_re/to_re and before_re regex'es
"""
# DEPRECATED, this is replaced by a new implementation
return _replace_section(config, replacement, replace_re=rf'^{from_re}$.*?^{to_re}$', before_re=rf'^({before_re})$')
def remove_section(config, from_re, to_re='!'):
# DEPRECATED, this is replaced by a new implementation
return _replace_section(config, '', replace_re=rf'^{from_re}$.*?^{to_re}$', before_re=None)
def _find_first_block(config, start_pattern, stop_pattern, start_at=0):
'''Find start and stop line numbers for a config block
config: (list) A list conaining the configuration that is searched
start_pattern: (raw-str) The pattern searched for a a start of block tag
stop_pattern: (raw-str) The pattern searched for to signify the end of the block
start_at: (int) The index to start searching at in the <config>
Returns:
None: No complete block could be found
set(int, int): A complete block found between the line numbers returned in the set
The object <config> is searched from the start for the regex <start_pattern> until the first match is found.
On a successful match it continues the search for the regex <stop_pattern> until it is found.
After a successful run a set is returned containing the start and stop line numbers.
'''
LOG.debug(f'_find_first_block: find start={repr(start_pattern)} stop={repr(stop_pattern)} start_at={start_at}')
_start = None
for i, element in enumerate(config[start_at:], start=start_at):
# LOG.debug(f'_find_first_block: running line {i:3} "{element}"')
if not _start:
if not re.match(start_pattern, element):
LOG.debug(f'_find_first_block: no match {i:3} "{element}"')
continue
_start = i
LOG.debug(f'_find_first_block: Found start {i:3} "{element}"')
continue
if not re.match(stop_pattern, element):
LOG.debug(f'_find_first_block: no match {i:3} "{element}"')
continue
LOG.debug(f'_find_first_block: Found stop {i:3} "{element}"')
return (_start, i)
LOG.debug('_find_first_block: exit start={repr(start_pattern)} stop={repr(stop_pattern)} start_at={start_at}')
return None
def _find_first_element(config, pattern, start_at=0):
'''Find the first element that matches the current pattern in config
config: (list) A list containing the configuration that is searched
start_pattern: (raw-str) The pattern searched for
start_at: (int) The index to start searching at in the <config>
return: Line index of the line containing the searched pattern
TODO: for now it returns -1 on a no-match because 0 also returns as False
TODO: that means that we can not use False matching to tell if its
'''
LOG.debug(f'_find_first_element: find start="{pattern}" start_at={start_at}')
for i, element in enumerate(config[start_at:], start=0):
if re.match(pattern + '$', element):
LOG.debug(f'_find_first_element: Found stop {i:3} "{element}"')
return i
LOG.debug(f'_find_first_element: no match {i:3} "{element}"')
LOG.debug(f'_find_first_element: Did not find any match, exiting')
return -1
def _find_elements(config, pattern, start_at=0):
'''Find all instances of pattern and return a list containing all element indexes
config: (list) A list containing the configuration that is searched
start_pattern: (raw-str) The pattern searched for
start_at: (int) The index to start searching at in the <config>
return: A list of line indexes containing the searched pattern
TODO: refactor this to return a generator instead
'''
return [i for i, element in enumerate(config[start_at:], start=0) if re.match(pattern + '$', element)]
class FRRConfig:
'''Main FRR Configuration manipulation object
Using this object the user could load, manipulate and commit the configuration to FRR
'''
def __init__(self, config=[]):
self.imported_config = ''
if isinstance(config, list):
self.config = config.copy()
self.original_config = config.copy()
elif isinstance(config, str):
self.config = config.split('\n')
self.original_config = self.config.copy()
else:
raise ValueError(
'The config element needs to be a string or list type object')
if config:
LOG.debug(f'__init__: frr library initiated with initial config')
for i, e in enumerate(self.config):
LOG.debug(f'__init__: initial {i:3} {e}')
def load_configuration(self, daemon=None):
'''Load the running configuration from FRR into the config object
daemon: str with name of the FRR Daemon to load configuration from or
None to load the consolidated config
Using this overwrites the current loaded config objects and replaces the original loaded config
'''
self.imported_config = get_configuration(daemon=daemon)
if daemon:
LOG.debug(f'load_configuration: Configuration loaded from FRR daemon {daemon}')
else:
LOG.debug(f'load_configuration: Configuration loaded from FRR integrated config')
self.original_config = self.imported_config.split('\n')
self.config = self.original_config.copy()
for i, e in enumerate(self.imported_config.split('\n')):
LOG.debug(f'load_configuration: loaded {i:3} {e}')
return
def test_configuration(self):
'''Test the current configuration against FRR
This will exception if FRR failes to load the current configuration object
'''
LOG.debug('test_configation: Testing configuration')
mark_configuration('\n'.join(self.config))
def commit_configuration(self, daemon=None):
- '''Commit the current configuration to FRR
- daemon: str with name of the FRR daemon to commit to or
- None to use the consolidated config
+ '''
+ Commit the current configuration to FRR daemon: str with name of the
+ FRR daemon to commit to or None to use the consolidated config.
+
+ Configuration is automatically saved after apply
'''
LOG.debug('commit_configuration: Commiting configuration')
for i, e in enumerate(self.config):
LOG.debug(f'commit_configuration: new_config {i:3} {e}')
# https://github.com/FRRouting/frr/issues/10132
# https://github.com/FRRouting/frr/issues/10133
count = 0
count_max = 5
while count < count_max:
count += 1
try:
reload_configuration('\n'.join(self.config), daemon=daemon)
break
except:
# we just need to re-try the commit of the configuration
# for the listed FRR issues above
pass
if count >= count_max:
raise ConfigurationNotValid(f'Config commit retry counter ({count_max}) exceeded')
+ # Save configuration to /run/frr/config/frr.conf
+ save_configuration()
+
def modify_section(self, start_pattern, replacement='!', stop_pattern=r'\S+', remove_stop_mark=False, count=0):
if isinstance(replacement, str):
replacement = replacement.split('\n')
elif not isinstance(replacement, list):
return ValueError("The replacement element needs to be a string or list type object")
LOG.debug(f'modify_section: starting search for {repr(start_pattern)} until {repr(stop_pattern)}')
_count = 0
_next_start = 0
while True:
if count and count <= _count:
# Break out of the loop after specified amount of matches
LOG.debug(f'modify_section: reached limit ({_count}), exiting loop at line {_next_start}')
break
# While searching, always assume that the user wants to search for the exact pattern he entered
# To be more specific the user needs a override, eg. a "pattern.*"
_w = _find_first_block(
self.config, start_pattern+'$', stop_pattern, start_at=_next_start)
if not _w:
# Reached the end, no more elements to remove
LOG.debug(f'modify_section: No more config sections found, exiting')
break
start_element, end_element = _w
LOG.debug(f'modify_section: found match between {start_element} and {end_element}')
for i, e in enumerate(self.config[start_element:end_element+1 if remove_stop_mark else end_element],
start=start_element):
LOG.debug(f'modify_section: remove {i:3} {e}')
del self.config[start_element:end_element +
1 if remove_stop_mark else end_element]
if replacement:
# Append the replacement config at the current position
for i, e in enumerate(replacement, start=start_element):
LOG.debug(f'modify_section: add {i:3} {e}')
self.config[start_element:start_element] = replacement
_count += 1
_next_start = start_element + len(replacement)
return _count
def add_before(self, before_pattern, addition):
'''Add config block before this element in the configuration'''
if isinstance(addition, str):
addition = addition.split('\n')
elif not isinstance(addition, list):
return ValueError("The replacement element needs to be a string or list type object")
start = _find_first_element(self.config, before_pattern)
if start < 0:
return False
for i, e in enumerate(addition, start=start):
LOG.debug(f'add_before: add {i:3} {e}')
self.config[start:start] = addition
return True
def __str__(self):
return '\n'.join(self.config)
def __repr__(self):
return f'frr({repr(str(self))})'
diff --git a/src/conf_mode/policy.py b/src/conf_mode/policy.py
index 5f9fcab9f..e251396c7 100755
--- a/src/conf_mode/policy.py
+++ b/src/conf_mode/policy.py
@@ -1,220 +1,217 @@
#!/usr/bin/env python3
#
# Copyright (C) 2021 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 exit
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.template import render_to_string
from vyos.util import dict_search
from vyos import ConfigError
from vyos import frr
from vyos import airbag
airbag.enable()
def routing_policy_find(key, dictionary):
# Recursively traverse a dictionary and extract the value assigned to
# a given key as generator object. This is made for routing policies,
# thus also import/export is checked
for k, v in dictionary.items():
if k == key:
if isinstance(v, dict):
for a, b in v.items():
if a in ['import', 'export']:
yield b
else:
yield v
elif isinstance(v, dict):
for result in routing_policy_find(key, v):
yield result
elif isinstance(v, list):
for d in v:
if isinstance(d, dict):
for result in routing_policy_find(key, d):
yield result
def get_config(config=None):
if config:
conf = config
else:
conf = Config()
base = ['policy']
policy = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True,
no_tag_node_value_mangle=True)
# We also need some additional information from the config, prefix-lists
# and route-maps for instance. They will be used in verify().
#
# XXX: one MUST always call this without the key_mangling() option! See
# vyos.configverify.verify_common_route_maps() for more information.
tmp = conf.get_config_dict(['protocols'], key_mangling=('-', '_'),
no_tag_node_value_mangle=True)
# Merge policy dict into "regular" config dict
policy = dict_merge(tmp, policy)
return policy
def verify(policy):
if not policy:
return None
for policy_type in ['access_list', 'access_list6', 'as_path_list',
'community_list', 'extcommunity_list', 'large_community_list',
'prefix_list', 'prefix_list6', 'route_map']:
# Bail out early and continue with next policy type
if policy_type not in policy:
continue
# instance can be an ACL name/number, prefix-list name or route-map name
for instance, instance_config in policy[policy_type].items():
# If no rule was found within the instance ... sad, but we can leave
# early as nothing needs to be verified
if 'rule' not in instance_config:
continue
# human readable instance name (hypen instead of underscore)
policy_hr = policy_type.replace('_', '-')
for rule, rule_config in instance_config['rule'].items():
mandatory_error = f'must be specified for "{policy_hr} {instance} rule {rule}"!'
if 'action' not in rule_config:
raise ConfigError(f'Action {mandatory_error}')
if policy_type == 'access_list':
if 'source' not in rule_config:
raise ConfigError(f'A source {mandatory_error}')
if int(instance) in range(100, 200) or int(instance) in range(2000, 2700):
if 'destination' not in rule_config:
raise ConfigError(f'A destination {mandatory_error}')
if policy_type == 'access_list6':
if 'source' not in rule_config:
raise ConfigError(f'A source {mandatory_error}')
if policy_type in ['as_path_list', 'community_list', 'extcommunity_list',
'large_community_list']:
if 'regex' not in rule_config:
raise ConfigError(f'A regex {mandatory_error}')
if policy_type in ['prefix_list', 'prefix_list6']:
if 'prefix' not in rule_config:
raise ConfigError(f'A prefix {mandatory_error}')
# route-maps tend to be a bit more complex so they get their own verify() section
if 'route_map' in policy:
for route_map, route_map_config in policy['route_map'].items():
if 'rule' not in route_map_config:
continue
for rule, rule_config in route_map_config['rule'].items():
# Specified community-list must exist
tmp = dict_search('match.community.community_list', rule_config)
if tmp and tmp not in policy.get('community_list', []):
raise ConfigError(f'community-list {tmp} does not exist!')
# Specified extended community-list must exist
tmp = dict_search('match.extcommunity', rule_config)
if tmp and tmp not in policy.get('extcommunity_list', []):
raise ConfigError(f'extcommunity-list {tmp} does not exist!')
# Specified large-community-list must exist
tmp = dict_search('match.large_community.large_community_list', rule_config)
if tmp and tmp not in policy.get('large_community_list', []):
raise ConfigError(f'large-community-list {tmp} does not exist!')
# Specified prefix-list must exist
tmp = dict_search('match.ip.address.prefix_list', rule_config)
if tmp and tmp not in policy.get('prefix_list', []):
raise ConfigError(f'prefix-list {tmp} does not exist!')
# Specified prefix-list must exist
tmp = dict_search('match.ipv6.address.prefix_list', rule_config)
if tmp and tmp not in policy.get('prefix_list6', []):
raise ConfigError(f'prefix-list6 {tmp} does not exist!')
# When routing protocols are active some use prefix-lists, route-maps etc.
# to apply the systems routing policy to the learned or redistributed routes.
# When the "routing policy" changes and policies, route-maps etc. are deleted,
# it is our responsibility to verify that the policy can not be deleted if it
# is used by any routing protocol
if 'protocols' in policy:
for policy_type in ['access_list', 'access_list6', 'as_path_list', 'community_list',
'extcommunity_list', 'large_community_list', 'prefix_list', 'route_map']:
if policy_type in policy:
for policy_name in list(set(routing_policy_find(policy_type, policy['protocols']))):
found = False
if policy_name in policy[policy_type]:
found = True
# BGP uses prefix-list for selecting both an IPv4 or IPv6 AFI related
# list - we need to go the extra mile here and check both prefix-lists
if policy_type == 'prefix_list' and 'prefix_list6' in policy and policy_name in policy['prefix_list6']:
found = True
if not found:
tmp = policy_type.replace('_','-')
raise ConfigError(f'Can not delete {tmp} "{policy_name}", still in use!')
return None
def generate(policy):
if not policy:
return None
policy['new_frr_config'] = render_to_string('frr/policy.frr.tmpl', policy)
return None
def apply(policy):
bgp_daemon = 'bgpd'
zebra_daemon = 'zebra'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(bgp_daemon)
frr_cfg.modify_section(r'^bgp as-path access-list .*')
frr_cfg.modify_section(r'^bgp community-list .*')
frr_cfg.modify_section(r'^bgp extcommunity-list .*')
frr_cfg.modify_section(r'^bgp large-community-list .*')
frr_cfg.modify_section(r'^route-map .*', stop_pattern='^exit', remove_stop_mark=True)
if 'new_frr_config' in policy:
frr_cfg.add_before(frr.default_add_before, policy['new_frr_config'])
frr_cfg.commit_configuration(bgp_daemon)
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
frr_cfg.modify_section(r'^access-list .*')
frr_cfg.modify_section(r'^ipv6 access-list .*')
frr_cfg.modify_section(r'^ip prefix-list .*')
frr_cfg.modify_section(r'^ipv6 prefix-list .*')
frr_cfg.modify_section(r'^route-map .*', stop_pattern='^exit', remove_stop_mark=True)
if 'new_frr_config' in policy:
frr_cfg.add_before(frr.default_add_before, policy['new_frr_config'])
frr_cfg.commit_configuration(zebra_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/protocols_bgp.py b/src/conf_mode/protocols_bgp.py
index 359bfff76..b88f0c4ef 100755
--- a/src/conf_mode/protocols_bgp.py
+++ b/src/conf_mode/protocols_bgp.py
@@ -1,318 +1,315 @@
#!/usr/bin/env python3
#
# Copyright (C) 2020-2021 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/>.
import os
from sys import exit
from sys import argv
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.configverify import verify_prefix_list
from vyos.configverify import verify_route_map
from vyos.configverify import verify_vrf
from vyos.template import is_ip
from vyos.template import is_interface
from vyos.template import render_to_string
from vyos.util import dict_search
from vyos.validate import is_addr_assigned
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 = None
if len(argv) > 1:
vrf = argv[1]
base_path = ['protocols', 'bgp']
# 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)
# Assign the name of our VRF context. This MUST be done before the return
# statement below, else on deletion we will delete the default instance
# instead of the VRF instance.
if vrf: bgp.update({'vrf' : vrf})
if not conf.exists(base):
bgp.update({'deleted' : ''})
if not vrf:
# We are running in the default VRF context, thus we can not delete
# our main BGP instance if there are dependent BGP VRF instances.
bgp['dependent_vrfs'] = conf.get_config_dict(['vrf', 'name'],
key_mangling=('-', '_'), get_first_key=True, no_tag_node_value_mangle=True)
return bgp
# We also need some additional information from the config, prefix-lists
# and route-maps for instance. They will be used in verify().
#
# XXX: one MUST always call this without the key_mangling() option! See
# vyos.configverify.verify_common_route_maps() for more information.
tmp = conf.get_config_dict(['policy'])
# Merge policy dict into "regular" config dict
bgp = dict_merge(tmp, bgp)
return bgp
def verify_remote_as(peer_config, bgp_config):
if 'remote_as' in peer_config:
return peer_config['remote_as']
if 'peer_group' in peer_config:
peer_group_name = peer_config['peer_group']
tmp = dict_search(f'peer_group.{peer_group_name}.remote_as', bgp_config)
if tmp: return tmp
if 'interface' in peer_config:
if 'remote_as' in peer_config['interface']:
return peer_config['interface']['remote_as']
if 'peer_group' in peer_config['interface']:
peer_group_name = peer_config['interface']['peer_group']
tmp = dict_search(f'peer_group.{peer_group_name}.remote_as', bgp_config)
if tmp: return tmp
if 'v6only' in peer_config['interface']:
if 'remote_as' in peer_config['interface']['v6only']:
return peer_config['interface']['v6only']['remote_as']
return None
def verify(bgp):
if not bgp or 'deleted' in bgp:
if 'dependent_vrfs' in bgp:
for vrf, vrf_options in bgp['dependent_vrfs'].items():
if dict_search('protocols.bgp', vrf_options) != None:
raise ConfigError('Cannot delete default BGP instance, ' \
'dependent VRF instance(s) exist!')
return None
if 'local_as' not in bgp:
raise ConfigError('BGP local-as number must be defined!')
# Common verification for both peer-group and neighbor statements
for neighbor in ['neighbor', 'peer_group']:
# bail out early if there is no neighbor or peer-group statement
# this also saves one indention level
if neighbor not in bgp:
continue
for peer, peer_config in bgp[neighbor].items():
# Only regular "neighbor" statement can have a peer-group set
# Check if the configure peer-group exists
if 'peer_group' in peer_config:
peer_group = peer_config['peer_group']
if 'peer_group' not in bgp or peer_group not in bgp['peer_group']:
raise ConfigError(f'Specified peer-group "{peer_group}" for '\
f'neighbor "{neighbor}" does not exist!')
if 'local_as' in peer_config:
if len(peer_config['local_as']) > 1:
raise ConfigError(f'Only one local-as number can be specified for peer "{peer}"!')
# Neighbor local-as override can not be the same as the local-as
# we use for this BGP instane!
asn = list(peer_config['local_as'].keys())[0]
if asn == bgp['local_as']:
raise ConfigError('Cannot have local-as same as BGP AS number')
# ttl-security and ebgp-multihop can't be used in the same configration
if 'ebgp_multihop' in peer_config and 'ttl_security' in peer_config:
raise ConfigError('You can not set both ebgp-multihop and ttl-security hops')
# Check if neighbor has both override capability and strict capability match configured at the same time.
if 'override_capability' in peer_config and 'strict_capability_match' in peer_config:
raise ConfigError(f'Neighbor "{peer}" cannot have both override-capability and strict-capability-match configured at the same time!')
# Check spaces in the password
if 'password' in peer_config and ' ' in peer_config['password']:
raise ConfigError('Whitespace is not allowed in passwords!')
# Some checks can/must only be done on a neighbor and not a peer-group
if neighbor == 'neighbor':
# remote-as must be either set explicitly for the neighbor
# or for the entire peer-group
if not verify_remote_as(peer_config, bgp):
raise ConfigError(f'Neighbor "{peer}" remote-as must be set!')
# Only checks for ipv4 and ipv6 neighbors
# Check if neighbor address is assigned as system interface address
if is_ip(peer) and is_addr_assigned(peer):
raise ConfigError(f'Can not configure a local address as neighbor "{peer}"')
elif is_interface(peer):
if 'peer_group' in peer_config:
raise ConfigError(f'peer-group must be set under the interface node of "{peer}"')
if 'remote_as' in peer_config:
raise ConfigError(f'remote-as must be set under the interface node of "{peer}"')
for afi in ['ipv4_unicast', 'ipv4_multicast', 'ipv4_labeled_unicast', 'ipv4_flowspec',
'ipv6_unicast', 'ipv6_multicast', 'ipv6_labeled_unicast', 'ipv6_flowspec',
'l2vpn_evpn']:
# Bail out early if address family is not configured
if 'address_family' not in peer_config or afi not in peer_config['address_family']:
continue
# Check if neighbor has both ipv4 unicast and ipv4 labeled unicast configured at the same time.
if 'ipv4_unicast' in peer_config['address_family'] and 'ipv4_labeled_unicast' in peer_config['address_family']:
raise ConfigError(f'Neighbor "{peer}" cannot have both ipv4-unicast and ipv4-labeled-unicast configured at the same time!')
# Check if neighbor has both ipv6 unicast and ipv6 labeled unicast configured at the same time.
if 'ipv6_unicast' in peer_config['address_family'] and 'ipv6_labeled_unicast' in peer_config['address_family']:
raise ConfigError(f'Neighbor "{peer}" cannot have both ipv6-unicast and ipv6-labeled-unicast configured at the same time!')
afi_config = peer_config['address_family'][afi]
# Validate if configured Prefix list exists
if 'prefix_list' in afi_config:
for tmp in ['import', 'export']:
if tmp not in afi_config['prefix_list']:
# bail out early
continue
if afi == 'ipv4_unicast':
verify_prefix_list(afi_config['prefix_list'][tmp], bgp)
elif afi == 'ipv6_unicast':
verify_prefix_list(afi_config['prefix_list'][tmp], bgp, version='6')
if 'route_map' in afi_config:
for tmp in ['import', 'export']:
if tmp in afi_config['route_map']:
verify_route_map(afi_config['route_map'][tmp], bgp)
if 'route_reflector_client' in afi_config:
if 'remote_as' in peer_config and peer_config['remote_as'] != 'internal' and peer_config['remote_as'] != bgp['local_as']:
raise ConfigError('route-reflector-client only supported for iBGP peers')
else:
if 'peer_group' in peer_config:
peer_group_as = dict_search(f'peer_group.{peer_group}.remote_as', bgp)
if peer_group_as != None and peer_group_as != 'internal' and peer_group_as != bgp['local_as']:
raise ConfigError('route-reflector-client only supported for iBGP peers')
# 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 ...
if 'peer_group' not in bgp['listen']['range'][prefix]:
raise ConfigError(f'Listen range for prefix "{prefix}" has no peer group configured.')
peer_group = bgp['listen']['range'][prefix]['peer_group']
if 'peer_group' not in bgp or peer_group not in bgp['peer_group']:
raise ConfigError(f'Peer-group "{peer_group}" for listen range "{prefix}" does not exist!')
if not verify_remote_as(bgp['listen']['range'][prefix], bgp):
raise ConfigError(f'Peer-group "{peer_group}" requires remote-as to be set!')
# Throw an error if the global administrative distance parameters aren't all filled out.
if dict_search('parameters.distance.global', bgp) != None:
for key in ['external', 'internal', 'local']:
if dict_search(f'parameters.distance.global.{key}', bgp) == None:
raise ConfigError('Missing mandatory configuration option for '\
f'global administrative distance {key}!')
# Address Family specific validation
if 'address_family' in bgp:
for afi, afi_config in bgp['address_family'].items():
if 'distance' in afi_config:
# Throw an error if the address family specific administrative
# distance parameters aren't all filled out.
for key in ['external', 'internal', 'local']:
if key not in afi_config['distance']:
raise ConfigError('Missing mandatory configuration option for '\
f'{afi} administrative distance {key}!')
if afi in ['ipv4_unicast', 'ipv6_unicast']:
if 'import' in afi_config and 'vrf' in afi_config['import']:
# Check if VRF exists
verify_vrf(afi_config['import']['vrf'])
# FRR error: please unconfigure vpn to vrf commands before
# using import vrf commands
if 'vpn' in afi_config['import'] or dict_search('export.vpn', afi_config) != None:
raise ConfigError('Please unconfigure VPN to VRF commands before '\
'using "import vrf" commands!')
# Verify that the export/import route-maps do exist
for export_import in ['export', 'import']:
tmp = dict_search(f'route_map.vpn.{export_import}', afi_config)
if tmp: verify_route_map(tmp, bgp)
if afi in ['l2vpn_evpn'] and 'vrf' not in bgp:
# Some L2VPN EVPN AFI options are only supported under VRF
if 'vni' in afi_config:
for vni, vni_config in afi_config['vni'].items():
if 'rd' in vni_config:
raise ConfigError('VNI route-distinguisher is only supported under EVPN VRF')
if 'route_target' in vni_config:
raise ConfigError('VNI route-target is only supported under EVPN VRF')
return None
def generate(bgp):
if not bgp or 'deleted' in bgp:
return None
bgp['protocol'] = 'bgp' # required for frr/vrf.route-map.frr.tmpl
bgp['frr_zebra_config'] = render_to_string('frr/vrf.route-map.frr.tmpl', bgp)
bgp['frr_bgpd_config'] = render_to_string('frr/bgpd.frr.tmpl', bgp)
return None
def apply(bgp):
bgp_daemon = 'bgpd'
zebra_daemon = 'zebra'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
frr_cfg.modify_section(r'(\s+)?ip protocol bgp route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
if 'frr_zebra_config' in bgp:
frr_cfg.add_before(frr.default_add_before, bgp['frr_zebra_config'])
frr_cfg.commit_configuration(zebra_daemon)
# Generate empty helper string which can be ammended to FRR commands, it
# will be either empty (default VRF) or contain the "vrf <name" statement
vrf = ''
if 'vrf' in bgp:
vrf = ' vrf ' + bgp['vrf']
frr_cfg.load_configuration(bgp_daemon)
frr_cfg.modify_section(f'^router bgp \d+{vrf}', stop_pattern='^exit', remove_stop_mark=True)
if 'frr_bgpd_config' in bgp:
frr_cfg.add_before(frr.default_add_before, bgp['frr_bgpd_config'])
frr_cfg.commit_configuration(bgp_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/protocols_isis.py b/src/conf_mode/protocols_isis.py
index 0011e6fbf..9b4b215de 100755
--- a/src/conf_mode/protocols_isis.py
+++ b/src/conf_mode/protocols_isis.py
@@ -1,252 +1,250 @@
#!/usr/bin/env python3
#
# Copyright (C) 2020-2021 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/>.
import os
from sys import exit
from sys import argv
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.configdict import node_changed
from vyos.configverify import verify_common_route_maps
from vyos.configverify import verify_interface_exists
from vyos.ifconfig import Interface
from vyos.util import dict_search
from vyos.util import get_interface_config
from vyos.template import render_to_string
from vyos.xml import defaults
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 = None
if len(argv) > 1:
vrf = argv[1]
base_path = ['protocols', 'isis']
# eqivalent of the C foo ? 'a' : 'b' statement
base = vrf and ['vrf', 'name', vrf, 'protocols', 'isis'] or base_path
isis = conf.get_config_dict(base, key_mangling=('-', '_'),
get_first_key=True)
# Assign the name of our VRF context. This MUST be done before the return
# statement below, else on deletion we will delete the default instance
# instead of the VRF instance.
if vrf: isis['vrf'] = vrf
# FRR has VRF support for different routing daemons. As interfaces belong
# to VRFs - or the global VRF, we need to check for changed interfaces so
# that they will be properly rendered for the FRR config. Also this eases
# removal of interfaces from the running configuration.
interfaces_removed = node_changed(conf, base + ['interface'])
if interfaces_removed:
isis['interface_removed'] = list(interfaces_removed)
# Bail out early if configuration tree does not exist
if not conf.exists(base):
isis.update({'deleted' : ''})
return isis
# We have gathered the dict representation of the CLI, but there are default
# options which we need to update into the dictionary retrived.
# XXX: Note that we can not call defaults(base), as defaults does not work
# on an instance of a tag node. As we use the exact same CLI definition for
# both the non-vrf and vrf version this is absolutely safe!
default_values = defaults(base_path)
# merge in default values
isis = dict_merge(default_values, isis)
# We also need some additional information from the config, prefix-lists
# and route-maps for instance. They will be used in verify().
#
# XXX: one MUST always call this without the key_mangling() option! See
# vyos.configverify.verify_common_route_maps() for more information.
tmp = conf.get_config_dict(['policy'])
# Merge policy dict into "regular" config dict
isis = dict_merge(tmp, isis)
return isis
def verify(isis):
# bail out early - looks like removal from running config
if not isis or 'deleted' in isis:
return None
if 'net' not in isis:
raise ConfigError('Network entity is mandatory!')
# last byte in IS-IS area address must be 0
tmp = isis['net'].split('.')
if int(tmp[-1]) != 0:
raise ConfigError('Last byte of IS-IS network entity title must always be 0!')
verify_common_route_maps(isis)
# If interface not set
if 'interface' not in isis:
raise ConfigError('Interface used for routing updates is mandatory!')
for interface in isis['interface']:
verify_interface_exists(interface)
# Interface MTU must be >= configured lsp-mtu
mtu = Interface(interface).get_mtu()
area_mtu = isis['lsp_mtu']
# Recommended maximum PDU size = interface MTU - 3 bytes
recom_area_mtu = mtu - 3
if mtu < int(area_mtu) or int(area_mtu) > recom_area_mtu:
raise ConfigError(f'Interface {interface} has MTU {mtu}, ' \
f'current area MTU is {area_mtu}! \n' \
f'Recommended area lsp-mtu {recom_area_mtu} or less ' \
'(calculated on MTU size).')
if 'vrf' in isis:
# If interface specific options are set, we must ensure that the
# interface is bound to our requesting VRF. Due to the VyOS
# priorities the interface is bound to the VRF after creation of
# the VRF itself, and before any routing protocol is configured.
vrf = isis['vrf']
tmp = get_interface_config(interface)
if 'master' not in tmp or tmp['master'] != vrf:
raise ConfigError(f'Interface {interface} is not a member of VRF {vrf}!')
# If md5 and plaintext-password set at the same time
for password in ['area_password', 'domain_password']:
if password in isis:
if {'md5', 'plaintext_password'} <= set(isis[password]):
tmp = password.replace('_', '-')
raise ConfigError(f'Can use either md5 or plaintext-password for {tmp}!')
# If one param from delay set, but not set others
if 'spf_delay_ietf' in isis:
required_timers = ['holddown', 'init_delay', 'long_delay', 'short_delay', 'time_to_learn']
exist_timers = []
for elm_timer in required_timers:
if elm_timer in isis['spf_delay_ietf']:
exist_timers.append(elm_timer)
exist_timers = set(required_timers).difference(set(exist_timers))
if len(exist_timers) > 0:
raise ConfigError('All types of spf-delay must be configured. Missing: ' + ', '.join(exist_timers).replace('_', '-'))
# If Redistribute set, but level don't set
if 'redistribute' in isis:
proc_level = isis.get('level','').replace('-','_')
for afi in ['ipv4', 'ipv6']:
if afi not in isis['redistribute']:
continue
for proto, proto_config in isis['redistribute'][afi].items():
if 'level_1' not in proto_config and 'level_2' not in proto_config:
raise ConfigError(f'Redistribute level-1 or level-2 should be specified in ' \
f'"protocols isis {process} redistribute {afi} {proto}"!')
for redistr_level, redistr_config in proto_config.items():
if proc_level and proc_level != 'level_1_2' and proc_level != redistr_level:
raise ConfigError(f'"protocols isis {process} redistribute {afi} {proto} {redistr_level}" ' \
f'can not be used with \"protocols isis {process} level {proc_level}\"')
# Segment routing checks
if dict_search('segment_routing.global_block', isis):
high_label_value = dict_search('segment_routing.global_block.high_label_value', isis)
low_label_value = dict_search('segment_routing.global_block.low_label_value', isis)
# If segment routing global block high value is blank, throw error
if (low_label_value and not high_label_value) or (high_label_value and not low_label_value):
raise ConfigError('Segment routing global block requires both low and high value!')
# If segment routing global block low value is higher than the high value, throw error
if int(low_label_value) > int(high_label_value):
raise ConfigError('Segment routing global block low value must be lower than high value')
if dict_search('segment_routing.local_block', isis):
high_label_value = dict_search('segment_routing.local_block.high_label_value', isis)
low_label_value = dict_search('segment_routing.local_block.low_label_value', isis)
# If segment routing local block high value is blank, throw error
if (low_label_value and not high_label_value) or (high_label_value and not low_label_value):
raise ConfigError('Segment routing local block requires both high and low value!')
# If segment routing local block low value is higher than the high value, throw error
if int(low_label_value) > int(high_label_value):
raise ConfigError('Segment routing local block low value must be lower than high value')
return None
def generate(isis):
if not isis or 'deleted' in isis:
return None
isis['protocol'] = 'isis' # required for frr/vrf.route-map.frr.tmpl
isis['frr_zebra_config'] = render_to_string('frr/vrf.route-map.frr.tmpl', isis)
isis['frr_isisd_config'] = render_to_string('frr/isisd.frr.tmpl', isis)
return None
def apply(isis):
isis_daemon = 'isisd'
zebra_daemon = 'zebra'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
frr_cfg.modify_section('(\s+)?ip protocol isis route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
if 'frr_zebra_config' in isis:
frr_cfg.add_before(frr.default_add_before, isis['frr_zebra_config'])
frr_cfg.commit_configuration(zebra_daemon)
# Generate empty helper string which can be ammended to FRR commands, it
# will be either empty (default VRF) or contain the "vrf <name" statement
vrf = ''
if 'vrf' in isis:
vrf = ' vrf ' + isis['vrf']
frr_cfg.load_configuration(isis_daemon)
frr_cfg.modify_section(f'^router isis VyOS{vrf}', stop_pattern='^exit', remove_stop_mark=True)
for key in ['interface', 'interface_removed']:
if key not in isis:
continue
for interface in isis[key]:
frr_cfg.modify_section(f'^interface {interface}{vrf}', stop_pattern='^exit', remove_stop_mark=True)
if 'frr_isisd_config' in isis:
frr_cfg.add_before(frr.default_add_before, isis['frr_isisd_config'])
frr_cfg.commit_configuration(isis_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/protocols_ospf.py b/src/conf_mode/protocols_ospf.py
index 255560e19..9d1fb48e4 100755
--- a/src/conf_mode/protocols_ospf.py
+++ b/src/conf_mode/protocols_ospf.py
@@ -1,247 +1,244 @@
#!/usr/bin/env python3
#
# Copyright (C) 2021 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/>.
import os
from sys import exit
from sys import argv
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.configdict import node_changed
from vyos.configverify import verify_common_route_maps
from vyos.configverify import verify_route_map
from vyos.configverify import verify_interface_exists
from vyos.template import render_to_string
from vyos.util import dict_search
from vyos.util import get_interface_config
from vyos.xml import defaults
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 = None
if len(argv) > 1:
vrf = argv[1]
base_path = ['protocols', 'ospf']
# eqivalent of the C foo ? 'a' : 'b' statement
base = vrf and ['vrf', 'name', vrf, 'protocols', 'ospf'] or base_path
ospf = conf.get_config_dict(base, key_mangling=('-', '_'),
get_first_key=True)
# Assign the name of our VRF context. This MUST be done before the return
# statement below, else on deletion we will delete the default instance
# instead of the VRF instance.
if vrf: ospf['vrf'] = vrf
# FRR has VRF support for different routing daemons. As interfaces belong
# to VRFs - or the global VRF, we need to check for changed interfaces so
# that they will be properly rendered for the FRR config. Also this eases
# removal of interfaces from the running configuration.
interfaces_removed = node_changed(conf, base + ['interface'])
if interfaces_removed:
ospf['interface_removed'] = list(interfaces_removed)
# Bail out early if configuration tree does not exist
if not conf.exists(base):
ospf.update({'deleted' : ''})
return ospf
# We have gathered the dict representation of the CLI, but there are default
# options which we need to update into the dictionary retrived.
# XXX: Note that we can not call defaults(base), as defaults does not work
# on an instance of a tag node. As we use the exact same CLI definition for
# both the non-vrf and vrf version this is absolutely safe!
default_values = defaults(base_path)
# We have to cleanup the default dict, as default values could enable features
# which are not explicitly enabled on the CLI. Example: default-information
# originate comes with a default metric-type of 2, which will enable the
# entire default-information originate tree, even when not set via CLI so we
# need to check this first and probably drop that key.
if dict_search('default_information.originate', ospf) is None:
del default_values['default_information']
if dict_search('area.area_type.nssa', ospf) is None:
del default_values['area']['area_type']['nssa']
if 'mpls_te' not in ospf:
del default_values['mpls_te']
for protocol in ['bgp', 'connected', 'isis', 'kernel', 'rip', 'static', 'table']:
# table is a tagNode thus we need to clean out all occurances for the
# default values and load them in later individually
if protocol == 'table':
del default_values['redistribute']['table']
continue
if dict_search(f'redistribute.{protocol}', ospf) is None:
del default_values['redistribute'][protocol]
# XXX: T2665: we currently have no nice way for defaults under tag nodes,
# clean them out and add them manually :(
del default_values['neighbor']
del default_values['area']['virtual_link']
del default_values['interface']
# merge in remaining default values
ospf = dict_merge(default_values, ospf)
if 'neighbor' in ospf:
default_values = defaults(base + ['neighbor'])
for neighbor in ospf['neighbor']:
ospf['neighbor'][neighbor] = dict_merge(default_values, ospf['neighbor'][neighbor])
if 'area' in ospf:
default_values = defaults(base + ['area', 'virtual-link'])
for area, area_config in ospf['area'].items():
if 'virtual_link' in area_config:
for virtual_link in area_config['virtual_link']:
ospf['area'][area]['virtual_link'][virtual_link] = dict_merge(
default_values, ospf['area'][area]['virtual_link'][virtual_link])
if 'interface' in ospf:
for interface in ospf['interface']:
# We need to reload the defaults on every pass b/c of
# hello-multiplier dependency on dead-interval
default_values = defaults(base + ['interface'])
# If hello-multiplier is set, we need to remove the default from
# dead-interval.
if 'hello_multiplier' in ospf['interface'][interface]:
del default_values['dead_interval']
ospf['interface'][interface] = dict_merge(default_values,
ospf['interface'][interface])
if 'redistribute' in ospf and 'table' in ospf['redistribute']:
default_values = defaults(base + ['redistribute', 'table'])
for table in ospf['redistribute']['table']:
ospf['redistribute']['table'][table] = dict_merge(default_values,
ospf['redistribute']['table'][table])
# We also need some additional information from the config, prefix-lists
# and route-maps for instance. They will be used in verify().
#
# XXX: one MUST always call this without the key_mangling() option! See
# vyos.configverify.verify_common_route_maps() for more information.
tmp = conf.get_config_dict(['policy'])
# Merge policy dict into "regular" config dict
ospf = dict_merge(tmp, ospf)
return ospf
def verify(ospf):
if not ospf:
return None
verify_common_route_maps(ospf)
# As we can have a default-information route-map, we need to validate it!
route_map_name = dict_search('default_information.originate.route_map', ospf)
if route_map_name: verify_route_map(route_map_name, ospf)
if 'interface' in ospf:
for interface, interface_config in ospf['interface'].items():
verify_interface_exists(interface)
# One can not use dead-interval and hello-multiplier at the same
# time. FRR will only activate the last option set via CLI.
if {'hello_multiplier', 'dead_interval'} <= set(interface_config):
raise ConfigError(f'Can not use hello-multiplier and dead-interval ' \
f'concurrently for {interface}!')
# One can not use the "network <prefix> area <id>" command and an
# per interface area assignment at the same time. FRR will error
# out using: "Please remove all network commands first."
if 'area' in ospf and 'area' in interface_config:
for area, area_config in ospf['area'].items():
if 'network' in area_config:
raise ConfigError('Can not use OSPF interface area and area ' \
'network configuration at the same time!')
if 'vrf' in ospf:
# If interface specific options are set, we must ensure that the
# interface is bound to our requesting VRF. Due to the VyOS
# priorities the interface is bound to the VRF after creation of
# the VRF itself, and before any routing protocol is configured.
vrf = ospf['vrf']
tmp = get_interface_config(interface)
if 'master' not in tmp or tmp['master'] != vrf:
raise ConfigError(f'Interface {interface} is not a member of VRF {vrf}!')
return None
def generate(ospf):
if not ospf or 'deleted' in ospf:
return None
ospf['protocol'] = 'ospf' # required for frr/vrf.route-map.frr.tmpl
ospf['frr_zebra_config'] = render_to_string('frr/vrf.route-map.frr.tmpl', ospf)
ospf['frr_ospfd_config'] = render_to_string('frr/ospfd.frr.tmpl', ospf)
return None
def apply(ospf):
ospf_daemon = 'ospfd'
zebra_daemon = 'zebra'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
frr_cfg.modify_section('(\s+)?ip protocol ospf route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
if 'frr_zebra_config' in ospf:
frr_cfg.add_before(frr.default_add_before, ospf['frr_zebra_config'])
frr_cfg.commit_configuration(zebra_daemon)
# Generate empty helper string which can be ammended to FRR commands, it
# will be either empty (default VRF) or contain the "vrf <name" statement
vrf = ''
if 'vrf' in ospf:
vrf = ' vrf ' + ospf['vrf']
frr_cfg.load_configuration(ospf_daemon)
frr_cfg.modify_section(f'^router ospf{vrf}', stop_pattern='^exit', remove_stop_mark=True)
for key in ['interface', 'interface_removed']:
if key not in ospf:
continue
for interface in ospf[key]:
frr_cfg.modify_section(f'^interface {interface}{vrf}', stop_pattern='^exit', remove_stop_mark=True)
if 'frr_ospfd_config' in ospf:
frr_cfg.add_before(frr.default_add_before, ospf['frr_ospfd_config'])
frr_cfg.commit_configuration(ospf_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/protocols_ospfv3.py b/src/conf_mode/protocols_ospfv3.py
index 5d6ca7169..f1e490f48 100755
--- a/src/conf_mode/protocols_ospfv3.py
+++ b/src/conf_mode/protocols_ospfv3.py
@@ -1,118 +1,116 @@
#!/usr/bin/env python3
#
# Copyright (C) 2021 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/>.
import os
from sys import exit
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.configdict import node_changed
from vyos.configverify import verify_common_route_maps
from vyos.template import render_to_string
from vyos.ifconfig import Interface
from vyos.xml import defaults
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()
base = ['protocols', 'ospfv3']
ospfv3 = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True)
# FRR has VRF support for different routing daemons. As interfaces belong
# to VRFs - or the global VRF, we need to check for changed interfaces so
# that they will be properly rendered for the FRR config. Also this eases
# removal of interfaces from the running configuration.
interfaces_removed = node_changed(conf, base + ['interface'])
if interfaces_removed:
ospfv3['interface_removed'] = list(interfaces_removed)
# Bail out early if configuration tree does not exist
if not conf.exists(base):
ospfv3.update({'deleted' : ''})
return ospfv3
# We also need some additional information from the config, prefix-lists
# and route-maps for instance. They will be used in verify().
#
# XXX: one MUST always call this without the key_mangling() option! See
# vyos.configverify.verify_common_route_maps() for more information.
tmp = conf.get_config_dict(['policy'])
# Merge policy dict into "regular" config dict
ospfv3 = dict_merge(tmp, ospfv3)
return ospfv3
def verify(ospfv3):
if not ospfv3:
return None
verify_common_route_maps(ospfv3)
if 'interface' in ospfv3:
for ifname, if_config in ospfv3['interface'].items():
if 'ifmtu' in if_config:
mtu = Interface(ifname).get_mtu()
if int(if_config['ifmtu']) > int(mtu):
raise ConfigError(f'OSPFv3 ifmtu can not exceed physical MTU of "{mtu}"')
return None
def generate(ospfv3):
if not ospfv3 or 'deleted' in ospfv3:
return None
ospfv3['new_frr_config'] = render_to_string('frr/ospf6d.frr.tmpl', ospfv3)
return None
def apply(ospfv3):
ospf6_daemon = 'ospf6d'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
frr_cfg.load_configuration(ospf6_daemon)
frr_cfg.modify_section('^router ospf6', stop_pattern='^exit', remove_stop_mark=True)
for key in ['interface', 'interface_removed']:
if key not in ospfv3:
continue
for interface in ospfv3[key]:
frr_cfg.modify_section(f'^interface {interface}', stop_pattern='^exit', remove_stop_mark=True)
if 'new_frr_config' in ospfv3:
frr_cfg.add_before(frr.default_add_before, ospfv3['new_frr_config'])
frr_cfg.commit_configuration(ospf6_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/protocols_rip.py b/src/conf_mode/protocols_rip.py
index 96df41bdb..300f56489 100755
--- a/src/conf_mode/protocols_rip.py
+++ b/src/conf_mode/protocols_rip.py
@@ -1,147 +1,144 @@
#!/usr/bin/env python3
#
# Copyright (C) 2021 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/>.
import os
from sys import exit
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.configdict import node_changed
from vyos.configverify import verify_common_route_maps
from vyos.configverify import verify_access_list
from vyos.configverify import verify_prefix_list
from vyos.util import dict_search
from vyos.xml import defaults
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()
base = ['protocols', 'rip']
rip = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True)
# FRR has VRF support for different routing daemons. As interfaces belong
# to VRFs - or the global VRF, we need to check for changed interfaces so
# that they will be properly rendered for the FRR config. Also this eases
# removal of interfaces from the running configuration.
interfaces_removed = node_changed(conf, base + ['interface'])
if interfaces_removed:
rip['interface_removed'] = list(interfaces_removed)
# Bail out early if configuration tree does not exist
if not conf.exists(base):
rip.update({'deleted' : ''})
return rip
# We have gathered the dict representation of the CLI, but there are default
# options which we need to update into the dictionary retrived.
default_values = defaults(base)
# merge in remaining default values
rip = dict_merge(default_values, rip)
# We also need some additional information from the config, prefix-lists
# and route-maps for instance. They will be used in verify().
#
# XXX: one MUST always call this without the key_mangling() option! See
# vyos.configverify.verify_common_route_maps() for more information.
tmp = conf.get_config_dict(['policy'])
# Merge policy dict into "regular" config dict
rip = dict_merge(tmp, rip)
return rip
def verify(rip):
if not rip:
return None
verify_common_route_maps(rip)
acl_in = dict_search('distribute_list.access_list.in', rip)
if acl_in: verify_access_list(acl_in, rip)
acl_out = dict_search('distribute_list.access_list.out', rip)
if acl_out: verify_access_list(acl_out, rip)
prefix_list_in = dict_search('distribute_list.prefix-list.in', rip)
if prefix_list_in: verify_prefix_list(prefix_list_in, rip)
prefix_list_out = dict_search('distribute_list.prefix_list.out', rip)
if prefix_list_out: verify_prefix_list(prefix_list_out, rip)
if 'interface' in rip:
for interface, interface_options in rip['interface'].items():
if 'authentication' in interface_options:
if {'md5', 'plaintext_password'} <= set(interface_options['authentication']):
raise ConfigError('Can not use both md5 and plaintext-password at the same time!')
if 'split_horizon' in interface_options:
if {'disable', 'poison_reverse'} <= set(interface_options['split_horizon']):
raise ConfigError(f'You can not have "split-horizon poison-reverse" enabled ' \
f'with "split-horizon disable" for "{interface}"!')
def generate(rip):
if not rip or 'deleted' in rip:
return None
rip['new_frr_config'] = render_to_string('frr/ripd.frr.tmpl', rip)
return None
def apply(rip):
rip_daemon = 'ripd'
zebra_daemon = 'zebra'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
frr_cfg.modify_section('^ip protocol rip route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
frr_cfg.commit_configuration(zebra_daemon)
frr_cfg.load_configuration(rip_daemon)
frr_cfg.modify_section('^key chain \S+', stop_pattern='^exit', remove_stop_mark=True)
frr_cfg.modify_section('^router rip', stop_pattern='^exit', remove_stop_mark=True)
for key in ['interface', 'interface_removed']:
if key not in rip:
continue
for interface in rip[key]:
frr_cfg.modify_section(f'^interface {interface}', stop_pattern='^exit', remove_stop_mark=True)
if 'new_frr_config' in rip:
frr_cfg.add_before(frr.default_add_before, rip['new_frr_config'])
frr_cfg.commit_configuration(rip_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/protocols_ripng.py b/src/conf_mode/protocols_ripng.py
index d46a2216c..d9b8c0b30 100755
--- a/src/conf_mode/protocols_ripng.py
+++ b/src/conf_mode/protocols_ripng.py
@@ -1,132 +1,129 @@
#!/usr/bin/env python3
#
# Copyright (C) 2021 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/>.
import os
from sys import exit
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.configverify import verify_common_route_maps
from vyos.configverify import verify_access_list
from vyos.configverify import verify_prefix_list
from vyos.util import dict_search
from vyos.xml import defaults
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()
base = ['protocols', 'ripng']
ripng = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True)
# Bail out early if configuration tree does not exist
if not conf.exists(base):
return ripng
# We have gathered the dict representation of the CLI, but there are default
# options which we need to update into the dictionary retrived.
default_values = defaults(base)
# merge in remaining default values
ripng = dict_merge(default_values, ripng)
# We also need some additional information from the config, prefix-lists
# and route-maps for instance. They will be used in verify().
#
# XXX: one MUST always call this without the key_mangling() option! See
# vyos.configverify.verify_common_route_maps() for more information.
tmp = conf.get_config_dict(['policy'])
# Merge policy dict into "regular" config dict
ripng = dict_merge(tmp, ripng)
return ripng
def verify(ripng):
if not ripng:
return None
verify_common_route_maps(ripng)
acl_in = dict_search('distribute_list.access_list.in', ripng)
if acl_in: verify_access_list(acl_in, ripng, version='6')
acl_out = dict_search('distribute_list.access_list.out', ripng)
if acl_out: verify_access_list(acl_out, ripng, version='6')
prefix_list_in = dict_search('distribute_list.prefix_list.in', ripng)
if prefix_list_in: verify_prefix_list(prefix_list_in, ripng, version='6')
prefix_list_out = dict_search('distribute_list.prefix_list.out', ripng)
if prefix_list_out: verify_prefix_list(prefix_list_out, ripng, version='6')
if 'interface' in ripng:
for interface, interface_options in ripng['interface'].items():
if 'authentication' in interface_options:
if {'md5', 'plaintext_password'} <= set(interface_options['authentication']):
raise ConfigError('Can not use both md5 and plaintext-password at the same time!')
if 'split_horizon' in interface_options:
if {'disable', 'poison_reverse'} <= set(interface_options['split_horizon']):
raise ConfigError(f'You can not have "split-horizon poison-reverse" enabled ' \
f'with "split-horizon disable" for "{interface}"!')
def generate(ripng):
if not ripng:
ripng['new_frr_config'] = ''
return None
ripng['new_frr_config'] = render_to_string('frr/ripngd.frr.tmpl', ripng)
return None
def apply(ripng):
ripng_daemon = 'ripngd'
zebra_daemon = 'zebra'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
frr_cfg.modify_section('^ipv6 protocol ripng route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
frr_cfg.commit_configuration(zebra_daemon)
frr_cfg.load_configuration(ripng_daemon)
frr_cfg.modify_section('key chain \S+', stop_pattern='^exit', remove_stop_mark=True)
frr_cfg.modify_section('interface \S+', stop_pattern='^exit', remove_stop_mark=True)
frr_cfg.modify_section('^router ripng', stop_pattern='^exit', remove_stop_mark=True)
if 'new_frr_config' in ripng:
frr_cfg.add_before(frr.default_add_before, ripng['new_frr_config'])
frr_cfg.commit_configuration(ripng_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/protocols_rpki.py b/src/conf_mode/protocols_rpki.py
index dadd8d6f4..4bd4e8650 100755
--- a/src/conf_mode/protocols_rpki.py
+++ b/src/conf_mode/protocols_rpki.py
@@ -1,111 +1,108 @@
#!/usr/bin/env python3
#
# Copyright (C) 2021 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/>.
import os
from sys import exit
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.template import render_to_string
from vyos.util import dict_search
from vyos.xml import defaults
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()
base = ['protocols', 'rpki']
rpki = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True)
# Bail out early if configuration tree does not exist
if not conf.exists(base):
rpki.update({'deleted' : ''})
return rpki
# We have gathered the dict representation of the CLI, but there are default
# options which we need to update into the dictionary retrived.
default_values = defaults(base)
rpki = dict_merge(default_values, rpki)
return rpki
def verify(rpki):
if not rpki:
return None
if 'cache' in rpki:
preferences = []
for peer, peer_config in rpki['cache'].items():
for mandatory in ['port', 'preference']:
if mandatory not in peer_config:
raise ConfigError(f'RPKI cache "{peer}" {mandatory} must be defined!')
if 'preference' in peer_config:
preference = peer_config['preference']
if preference in preferences:
raise ConfigError(f'RPKI cache with preference {preference} already configured!')
preferences.append(preference)
if 'ssh' in peer_config:
files = ['private_key_file', 'public_key_file', 'known_hosts_file']
for file in files:
if file not in peer_config['ssh']:
raise ConfigError('RPKI+SSH requires username, public/private ' \
'keys and known-hosts file to be defined!')
filename = peer_config['ssh'][file]
if not os.path.exists(filename):
raise ConfigError(f'RPKI SSH {file.replace("-","-")} "{filename}" does not exist!')
return None
def generate(rpki):
if not rpki:
return
rpki['new_frr_config'] = render_to_string('frr/rpki.frr.tmpl', rpki)
return None
def apply(rpki):
bgp_daemon = 'bgpd'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
frr_cfg.load_configuration(bgp_daemon)
frr_cfg.modify_section('^rpki')
if 'new_frr_config' in rpki:
frr_cfg.add_before(frr.default_add_before, rpki['new_frr_config'])
frr_cfg.commit_configuration(bgp_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/protocols_static.py b/src/conf_mode/protocols_static.py
index 5cfe37655..c1e427b16 100755
--- a/src/conf_mode/protocols_static.py
+++ b/src/conf_mode/protocols_static.py
@@ -1,130 +1,127 @@
#!/usr/bin/env python3
#
# Copyright (C) 2021 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/>.
import os
from sys import exit
from sys import argv
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.configdict import get_dhcp_interfaces
from vyos.configverify import verify_common_route_maps
from vyos.configverify import verify_vrf
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 = None
if len(argv) > 1:
vrf = argv[1]
base_path = ['protocols', 'static']
# eqivalent of the C foo ? 'a' : 'b' statement
base = vrf and ['vrf', 'name', vrf, 'protocols', 'static'] or base_path
static = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True)
# Assign the name of our VRF context
if vrf: static['vrf'] = vrf
# We also need some additional information from the config, prefix-lists
# and route-maps for instance. They will be used in verify().
#
# XXX: one MUST always call this without the key_mangling() option! See
# vyos.configverify.verify_common_route_maps() for more information.
tmp = conf.get_config_dict(['policy'])
# Merge policy dict into "regular" config dict
static = dict_merge(tmp, static)
# T3680 - get a list of all interfaces currently configured to use DHCP
tmp = get_dhcp_interfaces(conf, vrf)
if tmp: static['dhcp'] = tmp
return static
def verify(static):
verify_common_route_maps(static)
for route in ['route', 'route6']:
# if there is no route(6) key in the dictionary we can immediately
# bail out early
if route not in static:
continue
# When leaking routes to other VRFs we must ensure that the destination
# VRF exists
for prefix, prefix_options in static[route].items():
# both the interface and next-hop CLI node can have a VRF subnode,
# thus we check this using a for loop
for type in ['interface', 'next_hop']:
if type in prefix_options:
for interface, interface_config in prefix_options[type].items():
verify_vrf(interface_config)
return None
def generate(static):
if not static:
return None
static['new_frr_config'] = render_to_string('frr/staticd.frr.tmpl', static)
return None
def apply(static):
static_daemon = 'staticd'
zebra_daemon = 'zebra'
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
frr_cfg.modify_section(r'^ip protocol static route-map [-a-zA-Z0-9.]+', '')
frr_cfg.commit_configuration(zebra_daemon)
frr_cfg.load_configuration(static_daemon)
if 'vrf' in static:
vrf = static['vrf']
frr_cfg.modify_section(f'^vrf {vrf}', stop_pattern='^exit', remove_stop_mark=True)
else:
frr_cfg.modify_section(r'^ip route .*')
frr_cfg.modify_section(r'^ipv6 route .*')
if 'new_frr_config' in static:
frr_cfg.add_before(frr.default_add_before, static['new_frr_config'])
frr_cfg.commit_configuration(static_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/vrf_vni.py b/src/conf_mode/vrf_vni.py
index a357f30dd..680d79826 100755
--- a/src/conf_mode/vrf_vni.py
+++ b/src/conf_mode/vrf_vni.py
@@ -1,68 +1,65 @@
#!/usr/bin/env python3
#
# Copyright (C) 2020-2021 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()
frr_daemon = 'zebra'
def get_config(config=None):
if config:
conf = config
else:
conf = Config()
base = ['vrf']
vrf = conf.get_config_dict(base, get_first_key=True)
return vrf
def verify(vrf):
return None
def generate(vrf):
vrf['new_frr_config'] = render_to_string('frr/vrf-vni.frr.tmpl', vrf)
return None
def apply(vrf):
# add configuration to FRR
frr_cfg = frr.FRRConfig()
frr_cfg.load_configuration(frr_daemon)
frr_cfg.modify_section(f'^vrf .+', '')
if 'new_frr_config' in vrf:
frr_cfg.add_before(frr.default_add_before, vrf['new_frr_config'])
frr_cfg.commit_configuration(frr_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)

File Metadata

Mime Type
text/x-diff
Expires
Sat, Sep 26, 10:58 AM (1 d, 13 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4284977
Default Alt Text
(92 KB)

Event Timeline