diff options
author | Ansible Core Team <info@ansible.com> | 2020-03-09 09:40:26 +0000 |
---|---|---|
committer | Ansible Core Team <info@ansible.com> | 2020-03-09 09:40:26 +0000 |
commit | 5c9a9974c09c041a3bddca744af41fea7e51835f (patch) | |
tree | 34a57228f4e4a2963c0f08fb1f6048ad38c744cf | |
parent | 29ae7a227426a46250a232a5f05d6cc62e9299d6 (diff) | |
download | ansible-5c9a9974c09c041a3bddca744af41fea7e51835f.tar.gz |
Migrated to frr.frr
19 files changed, 0 insertions, 2421 deletions
diff --git a/lib/ansible/module_utils/network/frr/frr.py b/lib/ansible/module_utils/network/frr/frr.py deleted file mode 100644 index 30b3b268d8..0000000000 --- a/lib/ansible/module_utils/network/frr/frr.py +++ /dev/null @@ -1,40 +0,0 @@ -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - -import json - -from ansible.module_utils.connection import Connection, ConnectionError -from ansible.module_utils._text import to_text - - -def get_capabilities(module): - if hasattr(module, '_frr_capabilities'): - return module._frr_capabilities - try: - capabilities = Connection(module._socket_path).get_capabilities() - except ConnectionError as exc: - module.fail_json(msg=to_text(exc, errors='surrogate_then_replace')) - module._frr_capabilities = json.loads(capabilities) - return module._frr_capabilities - - -def run_commands(module, commands, check_rc=True): - connection = get_connection(module) - try: - return connection.run_commands(commands=commands, check_rc=check_rc) - except ConnectionError as exc: - module.fail_json(msg=to_text(exc)) - - -def get_connection(module): - if hasattr(module, '_frr_connection'): - return module._frr_connection - - capabilities = get_capabilities(module) - network_api = capabilities.get('network_api') - if network_api == 'cliconf': - module._frr_connection = Connection(module._socket_path) - else: - module.fail_json(msg='Invalid connection type %s' % network_api) - - return module._frr_connection diff --git a/lib/ansible/module_utils/network/frr/providers/cli/config/base.py b/lib/ansible/module_utils/network/frr/providers/cli/config/base.py deleted file mode 100644 index eade249a09..0000000000 --- a/lib/ansible/module_utils/network/frr/providers/cli/config/base.py +++ /dev/null @@ -1,77 +0,0 @@ -# -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -# -from ansible.module_utils.six import iteritems -from ansible.module_utils.network.common.utils import to_list -from ansible.module_utils.network.common.config import NetworkConfig - - -class ConfigBase(object): - - argument_spec = {} - - mutually_exclusive = [] - - identifier = () - - def __init__(self, **kwargs): - self.values = {} - self._rendered_configuration = {} - self.active_configuration = None - - for item in self.identifier: - self.values[item] = kwargs.pop(item) - - for key, value in iteritems(kwargs): - if key in self.argument_spec: - setattr(self, key, value) - - for key, value in iteritems(self.argument_spec): - if value.get('default'): - if not getattr(self, key, None): - setattr(self, key, value.get('default')) - - def __getattr__(self, key): - if key in self.argument_spec: - return self.values.get(key) - - def __setattr__(self, key, value): - if key in self.argument_spec: - if key in self.identifier: - raise TypeError('cannot set value') - elif value is not None: - self.values[key] = value - else: - super(ConfigBase, self).__setattr__(key, value) - - def context_config(self, cmd): - if 'context' not in self._rendered_configuration: - self._rendered_configuration['context'] = list() - self._rendered_configuration['context'].extend(to_list(cmd)) - - def global_config(self, cmd): - if 'global' not in self._rendered_configuration: - self._rendered_configuration['global'] = list() - self._rendered_configuration['global'].extend(to_list(cmd)) - - def get_rendered_configuration(self): - config = list() - for section in ('context', 'global'): - config.extend(self._rendered_configuration.get(section, [])) - return config - - def set_active_configuration(self, config): - self.active_configuration = config - - def render(self, config=None): - raise NotImplementedError - - def get_section(self, config, section): - if config is not None: - netcfg = NetworkConfig(indent=1, contents=config) - try: - config = netcfg.get_block_config(to_list(section)) - except ValueError: - config = None - return config diff --git a/lib/ansible/module_utils/network/frr/providers/cli/config/bgp/address_family.py b/lib/ansible/module_utils/network/frr/providers/cli/config/bgp/address_family.py deleted file mode 100644 index 7627cc3a7c..0000000000 --- a/lib/ansible/module_utils/network/frr/providers/cli/config/bgp/address_family.py +++ /dev/null @@ -1,136 +0,0 @@ -# -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -# -import re - -from ansible.module_utils.six import iteritems -from ansible.module_utils.network.common.utils import to_list -from ansible.module_utils.network.frr.providers.providers import CliProvider -from ansible.module_utils.network.frr.providers.cli.config.bgp.neighbors import AFNeighbors - - -class AddressFamily(CliProvider): - - def render(self, config=None): - commands = list() - safe_list = list() - - router_context = 'router bgp %s' % self.get_value('config.bgp_as') - context_config = None - - for item in self.get_value('config.address_family'): - context = 'address-family %s %s' % (item['afi'], item['safi']) - context_commands = list() - - if config: - context_path = [router_context, context] - context_config = self.get_config_context(config, context_path, indent=1) - - for key, value in iteritems(item): - if value is not None: - meth = getattr(self, '_render_%s' % key, None) - if meth: - resp = meth(item, context_config) - if resp: - context_commands.extend(to_list(resp)) - - if context_commands: - commands.append(context) - commands.extend(context_commands) - commands.append('exit-address-family') - - safe_list.append(context) - - if self.params['operation'] == 'replace': - if config: - resp = self._negate_config(config, safe_list) - commands.extend(resp) - - return commands - - def _negate_config(self, config, safe_list=None): - commands = list() - matches = re.findall(r'(address-family .+)$', config, re.M) - for item in set(matches).difference(safe_list): - commands.append('no %s' % item) - return commands - - def _render_auto_summary(self, item, config=None): - cmd = 'auto-summary' - if item['auto_summary'] is False: - cmd = 'no %s' % cmd - if not config or cmd not in config: - return cmd - - def _render_synchronization(self, item, config=None): - cmd = 'synchronization' - if item['synchronization'] is False: - cmd = 'no %s' % cmd - if not config or cmd not in config: - return cmd - - def _render_networks(self, item, config=None): - commands = list() - safe_list = list() - - for entry in item['networks']: - network = entry['prefix'] - if entry['masklen']: - network = '%s/%s' % (entry['prefix'], entry['masklen']) - safe_list.append(network) - - cmd = 'network %s' % network - - if entry['route_map']: - cmd += ' route-map %s' % entry['route_map'] - - if not config or cmd not in config: - commands.append(cmd) - - if self.params['operation'] == 'replace': - if config: - matches = re.findall(r'network (\S+)', config, re.M) - for entry in set(matches).difference(safe_list): - commands.append('no network %s' % entry) - - return commands - - def _render_redistribute(self, item, config=None): - commands = list() - safe_list = list() - - for entry in item['redistribute']: - option = entry['protocol'] - - cmd = 'redistribute %s' % entry['protocol'] - - if entry['id'] and entry['protocol'] in ('ospf', 'table'): - cmd += ' %s' % entry['id'] - option += ' %s' % entry['id'] - - if entry['metric']: - cmd += ' metric %s' % entry['metric'] - - if entry['route_map']: - cmd += ' route-map %s' % entry['route_map'] - - if not config or cmd not in config: - commands.append(cmd) - - safe_list.append(option) - - if self.params['operation'] == 'replace': - if config: - matches = re.findall(r'redistribute (\S+)(?:\s*)(\d*)', config, re.M) - for i in range(0, len(matches)): - matches[i] = ' '.join(matches[i]).strip() - for entry in set(matches).difference(safe_list): - commands.append('no redistribute %s' % entry) - - return commands - - def _render_neighbors(self, item, config): - """ generate bgp neighbor configuration - """ - return AFNeighbors(self.params).render(config, nbr_list=item['neighbors']) diff --git a/lib/ansible/module_utils/network/frr/providers/cli/config/bgp/neighbors.py b/lib/ansible/module_utils/network/frr/providers/cli/config/bgp/neighbors.py deleted file mode 100644 index bd3267f211..0000000000 --- a/lib/ansible/module_utils/network/frr/providers/cli/config/bgp/neighbors.py +++ /dev/null @@ -1,183 +0,0 @@ -# -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -# -import re - -from ansible.module_utils.six import iteritems -from ansible.module_utils.network.common.utils import to_list -from ansible.module_utils.network.frr.providers.providers import CliProvider - - -class Neighbors(CliProvider): - - def render(self, config=None, nbr_list=None): - commands = list() - safe_list = list() - if not nbr_list: - nbr_list = self.get_value('config.neighbors') - - for item in nbr_list: - neighbor_commands = list() - context = 'neighbor %s' % item['neighbor'] - cmd = '%s remote-as %s' % (context, item['remote_as']) - - if not config or cmd not in config: - neighbor_commands.append(cmd) - - for key, value in iteritems(item): - if value is not None: - meth = getattr(self, '_render_%s' % key, None) - if meth: - resp = meth(item, config) - if resp: - neighbor_commands.extend(to_list(resp)) - - commands.extend(neighbor_commands) - safe_list.append(context) - - if self.params['operation'] == 'replace': - if config and safe_list: - commands.extend(self._negate_config(config, safe_list)) - - return commands - - def _negate_config(self, config, safe_list=None): - commands = list() - matches = re.findall(r'(neighbor \S+)', config, re.M) - for item in set(matches).difference(safe_list): - commands.append('no %s' % item) - return commands - - def _render_advertisement_interval(self, item, config=None): - cmd = 'neighbor %s advertisement-interval %s' % (item['neighbor'], item['advertisement_interval']) - if not config or cmd not in config: - return cmd - - def _render_local_as(self, item, config=None): - cmd = 'neighbor %s local-as %s' % (item['neighbor'], item['local_as']) - if not config or cmd not in config: - return cmd - - def _render_port(self, item, config=None): - cmd = 'neighbor %s port %s' % (item['neighbor'], item['port']) - if not config or cmd not in config: - return cmd - - def _render_description(self, item, config=None): - cmd = 'neighbor %s description %s' % (item['neighbor'], item['description']) - if not config or cmd not in config: - return cmd - - def _render_enabled(self, item, config=None): - cmd = 'neighbor %s shutdown' % item['neighbor'] - if item['enabled'] is True: - cmd = 'no %s' % cmd - if not config or cmd not in config: - return cmd - - def _render_update_source(self, item, config=None): - cmd = 'neighbor %s update-source %s' % (item['neighbor'], item['update_source']) - if not config or cmd not in config: - return cmd - - def _render_password(self, item, config=None): - cmd = 'neighbor %s password %s' % (item['neighbor'], item['password']) - if not config or cmd not in config: - return cmd - - def _render_ebgp_multihop(self, item, config=None): - cmd = 'neighbor %s ebgp-multihop %s' % (item['neighbor'], item['ebgp_multihop']) - if not config or cmd not in config: - return cmd - - def _render_peer_group(self, item, config=None): - cmd = 'neighbor %s peer-group %s' % (item['neighbor'], item['peer_group']) - if not config or cmd not in config: - return cmd - - def _render_timers(self, item, config): - """generate bgp timer related configuration - """ - keepalive = item['timers']['keepalive'] - holdtime = item['timers']['holdtime'] - neighbor = item['neighbor'] - - if keepalive and holdtime: - cmd = 'neighbor %s timers %s %s' % (neighbor, keepalive, holdtime) - if not config or cmd not in config: - return cmd - else: - raise ValueError("required both options for timers: keepalive and holdtime") - - -class AFNeighbors(CliProvider): - - def render(self, config=None, nbr_list=None): - commands = list() - if not nbr_list: - return - - for item in nbr_list: - neighbor_commands = list() - for key, value in iteritems(item): - if value is not None: - meth = getattr(self, '_render_%s' % key, None) - if meth: - resp = meth(item, config) - if resp: - neighbor_commands.extend(to_list(resp)) - - commands.extend(neighbor_commands) - - return commands - - def _render_route_reflector_client(self, item, config=None): - cmd = 'neighbor %s route-reflector-client' % item['neighbor'] - if item['route_reflector_client'] is False: - if not config or cmd in config: - cmd = 'no %s' % cmd - return cmd - elif not config or cmd not in config: - return cmd - - def _render_route_server_client(self, item, config=None): - cmd = 'neighbor %s route-server-client' % item['neighbor'] - if item['route_server_client'] is False: - if not config or cmd in config: - cmd = 'no %s' % cmd - return cmd - elif not config or cmd not in config: - return cmd - - def _render_remove_private_as(self, item, config=None): - cmd = 'neighbor %s remove-private-AS' % item['neighbor'] - if item['remove_private_as'] is False: - if not config or cmd in config: - cmd = 'no %s' % cmd - return cmd - elif not config or cmd not in config: - return cmd - - def _render_next_hop_self(self, item, config=None): - cmd = 'neighbor %s activate' % item['neighbor'] - if item['next_hop_self'] is False: - if not config or cmd in config: - cmd = 'no %s' % cmd - return cmd - elif not config or cmd not in config: - return cmd - - def _render_activate(self, item, config=None): - cmd = 'neighbor %s activate' % item['neighbor'] - if item['activate'] is False: - if not config or cmd in config: - cmd = 'no %s' % cmd - return cmd - elif not config or cmd not in config: - return cmd - - def _render_maximum_prefix(self, item, config=None): - cmd = 'neighbor %s maximum-prefix %s' % (item['neighbor'], item['maximum_prefix']) - if not config or cmd not in config: - return cmd diff --git a/lib/ansible/module_utils/network/frr/providers/cli/config/bgp/process.py b/lib/ansible/module_utils/network/frr/providers/cli/config/bgp/process.py deleted file mode 100644 index bacdf6ee6b..0000000000 --- a/lib/ansible/module_utils/network/frr/providers/cli/config/bgp/process.py +++ /dev/null @@ -1,137 +0,0 @@ -# -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -# -import re - -from ansible.module_utils.six import iteritems -from ansible.module_utils.network.common.utils import to_list -from ansible.module_utils.network.frr.providers.providers import register_provider -from ansible.module_utils.network.frr.providers.providers import CliProvider -from ansible.module_utils.network.frr.providers.cli.config.bgp.neighbors import Neighbors -from ansible.module_utils.network.frr.providers.cli.config.bgp.address_family import AddressFamily - -REDISTRIBUTE_PROTOCOLS = frozenset(['ospf', 'ospf6', 'eigrp', 'isis', 'table', - 'static', 'connected', 'sharp', 'nhrp', 'kernel', 'babel', 'rip']) - - -@register_provider('frr', 'frr_bgp') -class Provider(CliProvider): - - def render(self, config=None): - commands = list() - - existing_as = None - if config: - match = re.search(r'router bgp (\d+)', config, re.M) - if match: - existing_as = match.group(1) - - operation = self.params['operation'] - - context = None - - if self.params['config']: - context = 'router bgp %s' % self.get_value('config.bgp_as') - - if operation == 'delete': - if existing_as: - commands.append('no router bgp %s' % existing_as) - elif context: - commands.append('no %s' % context) - - else: - self._validate_input(config) - if operation == 'replace': - if existing_as and int(existing_as) != self.get_value('config.bgp_as'): - commands.append('no router bgp %s' % existing_as) - config = None - - elif operation == 'override': - if existing_as: - commands.append('no router bgp %s' % existing_as) - config = None - - context_commands = list() - - for key, value in iteritems(self.get_value('config')): - if value is not None: - meth = getattr(self, '_render_%s' % key, None) - if meth: - resp = meth(config) - if resp: - context_commands.extend(to_list(resp)) - - if context and context_commands: - commands.append(context) - commands.extend(context_commands) - commands.append('exit') - return commands - - def _render_router_id(self, config=None): - cmd = 'bgp router-id %s' % self.get_value('config.router_id') - if not config or cmd not in config: - return cmd - - def _render_log_neighbor_changes(self, config=None): - cmd = 'bgp log-neighbor-changes' - log_neighbor_changes = self.get_value('config.log_neighbor_changes') - if log_neighbor_changes is True: - if not config or cmd not in config: - return cmd - elif log_neighbor_changes is False: - if config and cmd in config: - return 'no %s' % cmd - - def _render_networks(self, config=None): - commands = list() - safe_list = list() - - for entry in self.get_value('config.networks'): - network = entry['prefix'] - if entry['masklen']: - network = '%s/%s' % (entry['prefix'], entry['masklen']) - safe_list.append(network) - - cmd = 'network %s' % network - - if entry['route_map']: - cmd += ' route-map %s' % entry['route_map'] - - if not config or cmd not in config: - commands.append(cmd) - - if self.params['operation'] == 'replace': - if config: - matches = re.findall(r'network (\S+)', config, re.M) - for entry in set(matches).difference(safe_list): - commands.append('no network %s' % entry) - - return commands - - def _render_neighbors(self, config): - """ generate bgp neighbor configuration - """ - return Neighbors(self.params).render(config) - - def _render_address_family(self, config): - """ generate address-family configuration - """ - return AddressFamily(self.params).render(config) - - def _validate_input(self, config): - def device_has_AF(config): - return re.search(r'address-family (?:.*)', config) - - address_family = self.get_value('config.address_family') - root_networks = self.get_value('config.networks') - operation = self.params['operation'] - - if root_networks and operation == 'replace': - if address_family: - for item in address_family: - if item['networks']: - raise ValueError('operation is replace but provided both root level networks and networks under %s %s address family' - % (item['afi'], item['safi'])) - if config and device_has_AF(config): - raise ValueError('operation is replace and device has one or more address family activated but root level network(s) provided') diff --git a/lib/ansible/module_utils/network/frr/providers/module.py b/lib/ansible/module_utils/network/frr/providers/module.py deleted file mode 100644 index 073837c8d3..0000000000 --- a/lib/ansible/module_utils/network/frr/providers/module.py +++ /dev/null @@ -1,62 +0,0 @@ -# -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -# -from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.connection import Connection -from ansible.module_utils.network.frr.providers import providers -from ansible.module_utils._text import to_text - - -class NetworkModule(AnsibleModule): - - fail_on_missing_provider = True - - def __init__(self, connection=None, *args, **kwargs): - super(NetworkModule, self).__init__(*args, **kwargs) - - if connection is None: - connection = Connection(self._socket_path) - - self.connection = connection - - @property - def provider(self): - if not hasattr(self, '_provider'): - capabilities = self.from_json(self.connection.get_capabilities()) - - network_os = capabilities['device_info']['network_os'] - network_api = capabilities['network_api'] - - if network_api == 'cliconf': - connection_type = 'network_cli' - - cls = providers.get(network_os, self._name.split('.')[-1], connection_type) - - if not cls: - msg = 'unable to find suitable provider for network os %s' % network_os - if self.fail_on_missing_provider: - self.fail_json(msg=msg) - else: - self.warn(msg) - - obj = cls(self.params, self.connection, self.check_mode) - - setattr(self, '_provider', obj) - - return getattr(self, '_provider') - - def get_facts(self, subset=None): - try: - self.provider.get_facts(subset) - except Exception as exc: - self.fail_json(msg=to_text(exc)) - - def edit_config(self, config_filter=None): - current_config = self.connection.get_config(flags=config_filter) - try: - commands = self.provider.edit_config(current_config) - changed = bool(commands) - return {'commands': commands, 'changed': changed} - except Exception as exc: - self.fail_json(msg=to_text(exc)) diff --git a/lib/ansible/module_utils/network/frr/providers/providers.py b/lib/ansible/module_utils/network/frr/providers/providers.py deleted file mode 100644 index a466b033d9..0000000000 --- a/lib/ansible/module_utils/network/frr/providers/providers.py +++ /dev/null @@ -1,120 +0,0 @@ -# -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -# -import json - -from threading import RLock - -from ansible.module_utils.six import itervalues -from ansible.module_utils.network.common.utils import to_list -from ansible.module_utils.network.common.config import NetworkConfig - - -_registered_providers = {} -_provider_lock = RLock() - - -def register_provider(network_os, module_name): - def wrapper(cls): - _provider_lock.acquire() - try: - if network_os not in _registered_providers: - _registered_providers[network_os] = {} - for ct in cls.supported_connections: - if ct not in _registered_providers[network_os]: - _registered_providers[network_os][ct] = {} - for item in to_list(module_name): - for entry in itervalues(_registered_providers[network_os]): - entry[item] = cls - finally: - _provider_lock.release() - return cls - return wrapper - - -def get(network_os, module_name, connection_type): - network_os_providers = _registered_providers.get(network_os) - if network_os_providers is None: - raise ValueError('unable to find a suitable provider for this module') - if connection_type not in network_os_providers: - raise ValueError('provider does not support this connection type') - elif module_name not in network_os_providers[connection_type]: - raise ValueError('could not find a suitable provider for this module') - return network_os_providers[connection_type][module_name] - - -class ProviderBase(object): - - supported_connections = () - - def __init__(self, params, connection=None, check_mode=False): - self.params = params - self.connection = connection - self.check_mode = check_mode - - @property - def capabilities(self): - if not hasattr(self, '_capabilities'): - resp = self.from_json(self.connection.get_capabilities()) - setattr(self, '_capabilities', resp) - return getattr(self, '_capabilities') - - def get_value(self, path): - params = self.params.copy() - for key in path.split('.'): - params = params[key] - return params - - def get_facts(self, subset=None): - raise NotImplementedError(self.__class__.__name__) - - def edit_config(self): - raise NotImplementedError(self.__class__.__name__) - - -class CliProvider(ProviderBase): - - supported_connections = ('network_cli',) - - @property - def capabilities(self): - if not hasattr(self, '_capabilities'): - resp = self.from_json(self.connection.get_capabilities()) - setattr(self, '_capabilities', resp) - return getattr(self, '_capabilities') - - def get_config_context(self, config, path, indent=1): - if config is not None: - netcfg = NetworkConfig(indent=indent, contents=config) - try: - config = netcfg.get_block_config(to_list(path)) - except ValueError: - config = None - return config - - def render(self, config=None): - raise NotImplementedError(self.__class__.__name__) - - def cli(self, command): - try: - if not hasattr(self, '_command_output'): - setattr(self, '_command_output', {}) - return self._command_output[command] - except KeyError: - out = self.connection.get(command) - try: - out = json.loads(out) - except ValueError: - pass - self._command_output[command] = out - return out - - def get_facts(self, subset=None): - return self.populate() - - def edit_config(self, config=None): - commands = self.render(config) - if commands and self.check_mode is False: - self.connection.edit_config(commands) - return commands diff --git a/lib/ansible/modules/network/frr/frr_bgp.py b/lib/ansible/modules/network/frr/frr_bgp.py deleted file mode 100644 index 9fe33aa243..0000000000 --- a/lib/ansible/modules/network/frr/frr_bgp.py +++ /dev/null @@ -1,414 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -# - -from __future__ import absolute_import, division, print_function -__metaclass__ = type - - -ANSIBLE_METADATA = {'metadata_version': '1.1', - 'status': ['preview'], - 'supported_by': 'network'} - - -DOCUMENTATION = """ ---- -module: frr_bgp -version_added: "2.8" -author: "Nilashish Chakraborty (@NilashishC)" -short_description: Configure global BGP settings on Free Range Routing(FRR). -description: - - This module provides configuration management of global BGP parameters - on devices running Free Range Routing(FRR). -notes: - - Tested against FRRouting 6.0. -options: - config: - description: - - Specifies the BGP related configuration. - suboptions: - bgp_as: - description: - - Specifies the BGP Autonomous System (AS) number to configure on the device. - type: int - required: true - router_id: - description: - - Configures the BGP routing process router-id value. - default: null - log_neighbor_changes: - description: - - Enable/disable logging neighbor up/down and reset reason. - type: bool - neighbors: - description: - - Specifies BGP neighbor related configurations. - suboptions: - neighbor: - description: - - Neighbor router address. - required: True - remote_as: - description: - - Remote AS of the BGP neighbor to configure. - type: int - required: True - update_source: - description: - - Source of the routing updates. - password: - description: - - Password to authenticate the BGP peer connection. - enabled: - description: - - Administratively shutdown or enable a neighbor. - type: bool - description: - description: - - Neighbor specific description. - ebgp_multihop: - description: - - Specifies the maximum hop count for EBGP neighbors not on directly connected networks. - - The range is from 1 to 255. - type: int - peer_group: - description: - - Name of the peer group that the neighbor is a member of. - timers: - description: - - Specifies BGP neighbor timer related configurations. - suboptions: - keepalive: - description: - - Frequency (in seconds) with which the FRR sends keepalive messages to its peer. - - The range is from 0 to 65535. - type: int - required: True - holdtime: - description: - - Interval (in seconds) after not receiving a keepalive message that FRR declares a peer dead. - - The range is from 0 to 65535. - type: int - required: True - advertisement_interval: - description: - - Minimum interval between sending BGP routing updates for this neighbor. - type: int - local_as: - description: - - The local AS number for the neighbor. - type: int - port: - description: - - The TCP Port number to use for this neighbor. - - The range is from 0 to 65535. - type: int - networks: - description: - - Specify networks to announce via BGP. - - For operation replace, this option is mutually exclusive with networks option under address_family. - - For operation replace, if the device already has an address family activated, this option is not allowed. - suboptions: - prefix: - description: - - Network ID to announce via BGP. - required: True - masklen: - description: - - Subnet mask length for the network to announce(e.g, 8, 16, 24, etc.). - route_map: - description: - - Route map to modify the attributes. - address_family: - description: - - Specifies BGP address family related configurations. - suboptions: - afi: - description: - - Type of address family to configure. - choices: - - ipv4 - - ipv6 - required: True - safi: - description: - - Specifies the type of cast for the address family. - choices: - - flowspec - - unicast - - multicast - - labeled-unicast - default: unicast - redistribute: - description: - - Specifies the redistribute information from another routing protocol. - suboptions: - protocol: - description: - - Specifies the protocol for configuring redistribute information. - choices: ['ospf','ospf6','eigrp','isis','table','static','connected','sharp','nhrp','kernel','babel','rip'] - required: True - id: - description: - - Specifies the instance ID/table ID for this protocol - - Valid for ospf and table - metric: - description: - - Specifies the metric for redistributed routes. - route_map: - description: - - Specifies the route map reference. - networks: - description: - - Specify networks to announce via BGP. - - For operation replace, this option is mutually exclusive with root level networks option. - suboptions: - network: - description: - - Network ID to announce via BGP. - required: True - masklen: - description: - - Subnet mask length for the network to announce(e.g, 8, 16, 24, etc.). - route_map: - description: - - Route map to modify the attributes. - neighbors: - description: - - Specifies BGP neighbor related configurations in Address Family configuration mode. - suboptions: - neighbor: - description: - - Neighbor router address. - required: True - route_reflector_client: - description: - - Specify a neighbor as a route reflector client. - type: bool - route_server_client: - description: - - Specify a neighbor as a route server client. - type: bool - activate: - description: - - Enable the address family for this neighbor. - type: bool - remove_private_as: - description: - - Remove the private AS number from outbound updates. - type: bool - next_hop_self: - description: - - Enable/disable the next hop calculation for this neighbor. - type: bool - maximum_prefix: - description: - - Maximum number of prefixes to accept from this peer. - - The range is from 1 to 4294967295. - type: int - operation: - description: - - Specifies the operation to be performed on the BGP process configured on the device. - - In case of merge, the input configuration will be merged with the existing BGP configuration on the device. - - In case of replace, if there is a diff between the existing configuration and the input configuration, the - existing configuration will be replaced by the input configuration for every option that has the diff. - - In case of override, all the existing BGP configuration will be removed from the device and replaced with - the input configuration. - - In case of delete the existing BGP configuration will be removed from the device. - default: merge - choices: ['merge', 'replace', 'override', 'delete'] -""" - -EXAMPLES = """ -- name: configure global bgp as 64496 - frr_bgp: - config: - bgp_as: 64496 - router_id: 192.0.2.1 - log_neighbor_changes: True - neighbors: - - neighbor: 192.51.100.1 - remote_as: 64497 - timers: - keepalive: 120 - holdtime: 360 - - neighbor: 198.51.100.2 - remote_as: 64498 - networks: - - prefix: 192.0.2.0 - masklen: 24 - route_map: RMAP_1 - - prefix: 198.51.100.0 - masklen: 24 - address_family: - - afi: ipv4 - safi: unicast - redistribute: - - protocol: ospf - id: 223 - metric: 10 - operation: merge - -- name: Configure BGP neighbors - frr_bgp: - config: - bgp_as: 64496 - neighbors: - - neighbor: 192.0.2.10 - remote_as: 64496 - password: ansible - description: IBGP_NBR_1 - timers: - keepalive: 120 - holdtime: 360 - - neighbor: 192.0.2.15 - remote_as: 64496 - description: IBGP_NBR_2 - advertisement_interval: 120 - operation: merge - -- name: Configure BGP neighbors under address family mode - frr_bgp: - config: - bgp_as: 64496 - address_family: - - afi: ipv4 - safi: multicast - neighbors: - - neighbor: 203.0.113.10 - activate: yes - maximum_prefix: 250 - - - neighbor: 192.0.2.15 - activate: yes - route_reflector_client: True - operation: merge - -- name: Configure root-level networks for BGP - frr_bgp: - config: - bgp_as: 64496 - networks: - - prefix: 203.0.113.0 - masklen: 27 - route_map: RMAP_1 - - prefix: 203.0.113.32 - masklen: 27 - route_map: RMAP_2 - operation: merge - -- name: remove bgp as 64496 from config - frr_bgp: - config: - bgp_as: 64496 - operation: delete -""" - -RETURN = """ -commands: - description: The list of configuration mode commands to send to the device - returned: always - type: list - sample: - - router bgp 64496 - - bgp router-id 192.0.2.1 - - neighbor 192.51.100.1 remote-as 64497 - - neighbor 192.51.100.1 timers 120 360 - - neighbor 198.51.100.2 remote-as 64498 - - address-family ipv4 unicast - - redistribute ospf 223 metric 10 - - exit-address-family - - bgp log-neighbor-changes - - network 192.0.2.0/24 route-map RMAP_1 - - network 198.51.100.0/24 - - exit -""" -from ansible.module_utils._text import to_text -from ansible.module_utils.network.frr.providers.module import NetworkModule -from ansible.module_utils.network.frr.providers.cli.config.bgp.process import REDISTRIBUTE_PROTOCOLS - - -def main(): - """ main entry point for module execution - """ - network_spec = { - 'prefix': dict(required=True), - 'masklen': dict(type='int', required=True), - 'route_map': dict(), - } - - redistribute_spec = { - 'protocol': dict(choices=REDISTRIBUTE_PROTOCOLS, required=True), - 'id': dict(), - 'metric': dict(type='int'), - 'route_map': dict(), - } - - timer_spec = { - 'keepalive': dict(type='int', required=True), - 'holdtime': dict(type='int', required=True) - } - - neighbor_spec = { - 'neighbor': dict(required=True), - 'remote_as': dict(type='int', required=True), - 'advertisement_interval': dict(type='int'), - 'local_as': dict(type='int'), - 'port': dict(type='int'), - 'update_source': dict(), - 'password': dict(no_log=True), - 'enabled': dict(type='bool'), - 'description': dict(), - 'ebgp_multihop': dict(type='int'), - 'timers': dict(type='dict', options=timer_spec), - 'peer_group': dict(), - } - - af_neighbor_spec = { - 'neighbor': dict(required=True), - 'activate': dict(type='bool'), - 'remove_private_as': dict(type='bool'), - 'next_hop_self': dict(type='bool'), - 'route_reflector_client': dict(type='bool'), - 'route_server_client': dict(type='bool'), - 'maximum_prefix': dict(type='int') - } - - address_family_spec = { - 'afi': dict(choices=['ipv4', 'ipv6'], required=True), - 'safi': dict(choices=['flowspec', 'labeled-unicast', 'multicast', 'unicast'], default='unicast'), - 'networks': dict(type='list', elements='dict', options=network_spec), - 'redistribute': dict(type='list', elements='dict', options=redistribute_spec), - 'neighbors': dict(type='list', elements='dict', options=af_neighbor_spec), - } - - config_spec = { - 'bgp_as': dict(type='int', required=True), - 'router_id': dict(), - 'log_neighbor_changes': dict(type='bool'), - 'neighbors': dict(type='list', elements='dict', options=neighbor_spec), - 'address_family': dict(type='list', elements='dict', options=address_family_spec), - 'networks': dict(type='list', elements='dict', options=network_spec) - } - - argument_spec = { - 'config': dict(type='dict', options=config_spec), - 'operation': dict(default='merge', choices=['merge', 'replace', 'override', 'delete']) - } - - module = NetworkModule(argument_spec=argument_spec, - supports_check_mode=True) - - try: - result = module.edit_config(config_filter=' bgp') - except Exception as exc: - module.fail_json(msg=to_text(exc)) - - module.exit_json(**result) - - -if __name__ == '__main__': - main() diff --git a/lib/ansible/modules/network/frr/frr_facts.py b/lib/ansible/modules/network/frr/frr_facts.py deleted file mode 100644 index 175584d7be..0000000000 --- a/lib/ansible/modules/network/frr/frr_facts.py +++ /dev/null @@ -1,412 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - -from __future__ import absolute_import, division, print_function -__metaclass__ = type - - -ANSIBLE_METADATA = {'metadata_version': '1.1', - 'status': ['preview'], - 'supported_by': 'network'} - -DOCUMENTATION = """ ---- -module: frr_facts -version_added: "2.8" -author: "Nilashish Chakraborty (@NilashishC)" -short_description: Collect facts from remote devices running Free Range Routing (FRR). -description: - - Collects a base set of device facts from a remote device that - is running FRR. This module prepends all of the - base network fact keys with C(ansible_net_<fact>). The facts - module will always collect a base set of facts from the device - and can enable or disable collection of additional facts. -notes: - - Tested against FRR 6.0. -options: - gather_subset: - description: - - When supplied, this argument restricts the facts collected - to a given subset. - - Possible values for this argument include - C(all), C(hardware), C(config), and C(interfaces). - - Specify a list of values to include a larger subset. - - Use a value with an initial C(!) to collect all facts except that subset. - required: false - default: '!config' -""" - -EXAMPLES = """ -- name: Collect all facts from the device - frr_facts: - gather_subset: all - -- name: Collect only the config and default facts - frr_facts: - gather_subset: - - config - -- name: Collect the config and hardware facts - frr_facts: - gather_subset: - - config - - hardware - -- name: Do not collect hardware facts - frr_facts: - gather_subset: - - "!hardware" -""" - -RETURN = """ -ansible_net_gather_subset: - description: The list of fact subsets collected from the device - returned: always - type: list - -# default -ansible_net_hostname: - description: The configured hostname of the device - returned: always - type: str -ansible_net_version: - description: The FRR version running on the remote device - returned: always - type: str -ansible_net_api: - description: The name of the transport - returned: always - type: str -ansible_net_python_version: - description: The Python version that the Ansible controller is using - returned: always - type: str - -# hardware -ansible_net_mem_stats: - description: The memory statistics fetched from the device - returned: when hardware is configured - type: dict - -# config -ansible_net_config: - description: The current active config from the device - returned: when config is configured - type: str - -# interfaces -ansible_net_all_ipv4_addresses: - description: All IPv4 addresses configured on the device - returned: when interfaces is configured - type: list -ansible_net_all_ipv6_addresses: - description: All IPv6 addresses configured on the device - returned: when interfaces is configured - type: list -ansible_net_interfaces: - description: A hash of all interfaces running on the system - returned: when interfaces is configured - type: dict -ansible_net_mpls_ldp_neighbors: - description: The list of MPLS LDP neighbors from the remote device - returned: when interfaces is configured and LDP daemon is running on the device - type: dict -""" - -import platform -import re - -from ansible.module_utils.network.frr.frr import run_commands, get_capabilities -from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.six import iteritems - - -class FactsBase(object): - - COMMANDS = list() - - def __init__(self, module): - self.module = module - self.facts = dict() - self.responses = None - self._capabilities = get_capabilities(self.module) - - def populate(self): - self.responses = run_commands(self.module, commands=self.COMMANDS, check_rc=False) - - def run(self, cmd): - return run_commands(commands=cmd, check_rc=False) - - def parse_facts(self, pattern, data): - value = None - match = re.search(pattern, data, re.M) - if match: - value = match.group(1) - return value - - -class Default(FactsBase): - - COMMANDS = ['show version'] - - def populate(self): - super(Default, self).populate() - self.facts.update(self.platform_facts()) - - def platform_facts(self): - platform_facts = {} - - resp = self._capabilities - device_info = resp['device_info'] - - platform_facts['system'] = device_info['network_os'] - - for item in ('version', 'hostname'): - val = device_info.get('network_os_%s' % item) - if val: - platform_facts[item] = val - - platform_facts['api'] = resp['network_api'] - platform_facts['python_version'] = platform.python_version() - - return platform_facts - - -class Hardware(FactsBase): - - COMMANDS = ['show memory'] - - def _parse_daemons(self, data): - match = re.search(r'Memory statistics for (\w+)', data, re.M) - if match: - return match.group(1) - - def gather_memory_facts(self, data): - mem_details = data.split('\n\n') - mem_stats = {} - mem_counters = { - 'total_heap_allocated': r'Total heap allocated:(?:\s*)(.*)', - 'holding_block_headers': r'Holding block headers:(?:\s*)(.*)', - 'used_small_blocks': r'Used small blocks:(?:\s*)(.*)', - 'used_ordinary_blocks': r'Used ordinary blocks:(?:\s*)(.*)', - 'free_small_blocks': r'Free small blocks:(?:\s*)(.*)', - 'free_ordinary_blocks': r'Free ordinary blocks:(?:\s*)(.*)', - 'ordinary_blocks': r'Ordinary blocks:(?:\s*)(.*)', - 'small_blocks': r'Small blocks:(?:\s*)(.*)', - 'holding_blocks': r'Holding blocks:(?:\s*)(.*)' - } - - for item in mem_details: - daemon = self._parse_daemons(item) - mem_stats[daemon] = {} - for fact, pattern in iteritems(mem_counters): - mem_stats[daemon][fact] = self.parse_facts(pattern, item) - - return mem_stats - - def populate(self): - super(Hardware, self).populate() - data = self.responses[0] - if data: - self.facts['mem_stats'] = self.gather_memory_facts(data) - - -class Config(FactsBase): - - COMMANDS = ['show running-config'] - - def populate(self): - super(Config, self).populate() - data = self.responses[0] - if data: - data = re.sub(r'^Building configuration...\s+Current configuration:', '', data, flags=re.MULTILINE) - self.facts['config'] = data - - -class Interfaces(FactsBase): - - COMMANDS = ['show interface'] - - def populate(self): - ldp_supported = self._capabilities['supported_protocols']['ldp'] - - if ldp_supported: - self.COMMANDS.append('show mpls ldp discovery') - - super(Interfaces, self).populate() - data = self.responses[0] - - self.facts['all_ipv4_addresses'] = list() - self.facts['all_ipv6_addresses'] = list() - - if data: - interfaces = self.parse_interfaces(data) - self.facts['interfaces'] = self.populate_interfaces(interfaces) - self.populate_ipv4_interfaces(interfaces) - self.populate_ipv6_interfaces(interfaces) - - if ldp_supported: - data = self.responses[1] - if data: - self.facts['mpls_ldp_neighbors'] = self.populate_mpls_ldp_neighbors(data) - - def parse_interfaces(self, data): - parsed = dict() - key = '' - for line in data.split('\n'): - if len(line) == 0: - continue - elif line[0] == ' ': - parsed[key] += '\n%s' % line - else: - match = re.match(r'^Interface (\S+)', line) - if match: - key = match.group(1) - parsed[key] = line - return parsed - - def populate_interfaces(self, interfaces): - facts = dict() - counters = { - 'description': r'Description: (.+)', - 'macaddress': r'HWaddr: (\S+)', - 'type': r'Type: (\S+)', - 'vrf': r'vrf: (\S+)', - 'mtu': r'mtu (\d+)', - 'bandwidth': r'bandwidth (\d+)', - 'lineprotocol': r'line protocol is (\S+)', - 'operstatus': r'^(?:.+) is (.+),' - } - - for key, value in iteritems(interfaces): - intf = dict() - for fact, pattern in iteritems(counters): - intf[fact] = self.parse_facts(pattern, value) - facts[key] = intf - return facts - - def populate_ipv4_interfaces(self, data): - for key, value in data.items(): - self.facts['interfaces'][key]['ipv4'] = list() - primary_address = addresses = [] - primary_address = re.findall(r'inet (\S+) broadcast (?:\S+)(?:\s{2,})', value, re.M) - addresses = re.findall(r'inet (\S+) broadcast (?:\S+)(?:\s+)secondary', value, re.M) - if len(primary_address) == 0: - continue - addresses.append(primary_address[0]) - for address in addresses: - addr, subnet = address.split("/") - ipv4 = dict(address=addr.strip(), subnet=subnet.strip()) - self.add_ip_address(addr.strip(), 'ipv4') - self.facts['interfaces'][key]['ipv4'].append(ipv4) - - def populate_ipv6_interfaces(self, data): - for key, value in data.items(): - self.facts['interfaces'][key]['ipv6'] = list() - addresses = re.findall(r'inet6 (\S+)', value, re.M) - for address in addresses: - addr, subnet = address.split("/") - ipv6 = dict(address=addr.strip(), subnet=subnet.strip()) - self.add_ip_address(addr.strip(), 'ipv6') - self.facts['interfaces'][key]['ipv6'].append(ipv6) - - def add_ip_address(self, address, family): - if family == 'ipv4': - self.facts['all_ipv4_addresses'].append(address) - else: - self.facts['all_ipv6_addresses'].append(address) - - def populate_mpls_ldp_neighbors(self, data): - facts = {} - entries = data.splitlines() - for x in entries: - if x.startswith('AF'): - continue - x = x.split() - if len(x) > 0: - ldp = {} - ldp['neighbor'] = x[1] - ldp['source'] = x[3] - facts[ldp['source']] = [] - facts[ldp['source']].append(ldp) - - return facts - - -FACT_SUBSETS = dict( - default=Default, - hardware=Hardware, - config=Config, - interfaces=Interfaces -) - -VALID_SUBSETS = frozenset(FACT_SUBSETS.keys()) - - -def main(): - """main entry point for module execution - """ - argument_spec = dict( - gather_subset=dict(default=['!config'], type='list') - ) - - module = AnsibleModule(argument_spec=argument_spec, - supports_check_mode=True) - - gather_subset = module.params['gather_subset'] - - runable_subsets = set() - exclude_subsets = set() - - for subset in gather_subset: - if subset == 'all': - runable_subsets.update(VALID_SUBSETS) - continue - - if subset.startswith('!'): - subset = subset[1:] - if subset == 'all': - exclude_subsets.update(VALID_SUBSETS) - continue - exclude = True - else: - exclude = False - - if subset not in VALID_SUBSETS: - module.fail_json(msg='Subset must be one of [%s], got %s' % (', '.join(VALID_SUBSETS), subset)) - - if exclude: - exclude_subsets.add(subset) - else: - runable_subsets.add(subset) - - if not runable_subsets: - runable_subsets.update(VALID_SUBSETS) - - runable_subsets.difference_update(exclude_subsets) - runable_subsets.add('default') - - facts = dict() - facts['gather_subset'] = list(runable_subsets) - - instances = list() - for key in runable_subsets: - instances.append(FACT_SUBSETS[key](module)) - - for inst in instances: - inst.populate() - facts.update(inst.facts) - - ansible_facts = dict() - for key, value in iteritems(facts): - key = 'ansible_net_%s' % key - ansible_facts[key] = value - - module.exit_json(ansible_facts=ansible_facts) - - -if __name__ == '__main__': - main() diff --git a/lib/ansible/plugins/cliconf/frr.py b/lib/ansible/plugins/cliconf/frr.py deleted file mode 100644 index 6ba20ff8a4..0000000000 --- a/lib/ansible/plugins/cliconf/frr.py +++ /dev/null @@ -1,211 +0,0 @@ -# -# (c) 2018 Red Hat Inc. -# -# This file is part of Ansible -# -# Ansible is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. -# -from __future__ import (absolute_import, division, print_function) -__metaclass__ = type - -DOCUMENTATION = """ ---- -author: Ansible Networking Team -cliconf: frr -short_description: Use frr cliconf to run command on Free Range Routing platform -description: - - This frr plugin provides low level abstraction apis for - sending and receiving CLI commands from FRR network devices. -version_added: "2.8" -""" - -import re -import json - -from ansible.errors import AnsibleConnectionFailure -from ansible.module_utils._text import to_text -from ansible.module_utils.common._collections_compat import Mapping -from ansible.module_utils.network.common.config import NetworkConfig, dumps -from ansible.module_utils.network.common.utils import to_list -from ansible.plugins.cliconf import CliconfBase, enable_mode - - -class Cliconf(CliconfBase): - - def get_supported_protocols(self): - supported_protocols = {} - protocols = ['bgp', 'isis', 'ospf', 'ldp', 'ospf6', 'pim', 'rip', 'ripm', 'zebra'] - daemons = self.get('show daemons') - data = to_text(daemons, errors='surrogate_or_strict').strip() - - for item in protocols: - supported_protocols[item] = True if item in data else False - return supported_protocols - - def get_device_info(self): - device_info = {} - - device_info['network_os'] = 'frr' - reply = self.get('show version') - data = to_text(reply, errors='surrogate_or_strict').strip() - - match = re.search(r'FRRouting (\S+) \((\S+)\)', data) - if match: - device_info['network_os_version'] = match.group(1) - if match.group(2): - device_info['network_os_hostname'] = match.group(2) - - return device_info - - def get_option_values(self): - return { - 'format': ['text'], - 'diff_match': ['line', 'strict', 'exact', 'none'], - 'diff_replace': ['line', 'block'], - 'output': [] - } - - def get_device_operations(self): - return { - 'supports_diff_replace': False, - 'supports_commit': False, - 'supports_rollback': False, - 'supports_defaults': False, - 'supports_onbox_diff': False, - 'supports_commit_comment': False, - 'supports_multiline_delimiter': False, - 'supports_diff_match': False, - 'supports_diff_ignore_lines': False, - 'supports_generate_diff': True, - 'supports_replace': False - } - - def get_capabilities(self): - result = super(Cliconf, self).get_capabilities() - result['rpc'] += ['get_diff', 'run_commands'] - result['device_operations'] = self.get_device_operations() - result['supported_protocols'] = self.get_supported_protocols() - result.update(self.get_option_values()) - return json.dumps(result) - - def get_diff(self, candidate=None, running=None, diff_match='line', diff_ignore_lines=None, path=None, diff_replace='line'): - - diff = {} - device_operations = self.get_device_operations() - option_values = self.get_option_values() - - if candidate is None and device_operations['supports_generate_diff']: - raise ValueError("candidate configuration is required to generate diff") - - if diff_match not in option_values['diff_match']: - raise ValueError("'match' value %s in invalid, valid values are %s" % ( - diff_match, ', '.join(option_values['diff_match']))) - - if diff_replace not in option_values['diff_replace']: - raise ValueError("'replace' value %s in invalid, valid values are %s" % ( - diff_replace, ', '.join(option_values['diff_replace']))) - - # prepare candidate configuration - candidate_obj = NetworkConfig(indent=1) - candidate_obj.load(candidate) - - if running and diff_match != 'none': - # running configuration - running_obj = NetworkConfig(indent=1, contents=running, ignore_lines=diff_ignore_lines) - configdiffobjs = candidate_obj.difference(running_obj, path=path, match=diff_match, replace=diff_replace) - - else: - configdiffobjs = candidate_obj.items - - diff['config_diff'] = dumps(configdiffobjs, 'commands') if configdiffobjs else '' - return diff - - @enable_mode - def get_config(self, source='running', flags=None, format=None): - if source not in ('running', 'startup'): - raise ValueError("fetching configuration from %s is not supported" % source) - - if format: - raise ValueError("'format' value %s is not supported for get_config" % format) - - if not flags: - flags = [] - if source == 'running': - cmd = 'show running-config ' - else: - cmd = 'show startup-config ' - - cmd += ' '.join(to_list(flags)) - cmd = cmd.strip() - - return self.send_command(cmd) - - @enable_mode - def edit_config(self, candidate=None, commit=True, replace=None, comment=None): - resp = {} - operations = self.get_device_operations() - self.check_edit_config_capability(operations, candidate, commit, replace, comment) - - results = [] - requests = [] - if commit: - self.send_command('configure terminal') - for line in to_list(candidate): - if not isinstance(line, Mapping): - line = {'command': line} - - cmd = line['command'] - if cmd != 'end' and cmd[0] != '!': - results.append(self.send_command(**line)) - requests.append(cmd) - - self.send_command('end') - else: - raise ValueError('check mode is not supported') - - resp['request'] = requests - resp['response'] = results - return resp - - def get(self, command=None, prompt=None, answer=None, sendonly=False, output=None, newline=True, check_all=False): - if not command: - raise ValueError('must provide value of command to execute') - if output: - raise ValueError("'output' value %s is not supported for get" % output) - - return self.send_command(command=command, prompt=prompt, answer=answer, sendonly=sendonly, newline=newline, check_all=check_all) - - def run_commands(self, commands=None, check_rc=True): - if commands is None: - raise ValueError("'commands' value is required") - - responses = list() - for cmd in to_list(commands): - if not isinstance(cmd, Mapping): - cmd = {'command': cmd} - - output = cmd.pop('output', None) - if output: - raise ValueError("'output' value %s is not supported for run_commands" % output) - - try: - out = self.send_command(**cmd) - except AnsibleConnectionFailure as e: - if check_rc: - raise - out = getattr(e, 'err', to_text(e)) - - responses.append(out) - - return responses diff --git a/lib/ansible/plugins/terminal/frr.py b/lib/ansible/plugins/terminal/frr.py deleted file mode 100644 index 937e0809d2..0000000000 --- a/lib/ansible/plugins/terminal/frr.py +++ /dev/null @@ -1,60 +0,0 @@ -# -# (c) 2018 Red Hat Inc. -# -# This file is part of Ansible -# -# Ansible is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. -# -from __future__ import (absolute_import, division, print_function) -__metaclass__ = type - -import re - -from ansible.errors import AnsibleConnectionFailure -from ansible.plugins.terminal import TerminalBase - - -class TerminalModule(TerminalBase): - - terminal_stdout_re = [ - re.compile(br"[\r\n]?[\w\+\-\.:\/\[\]]+(?:\([^\)]+\)){0,3}(?:[>#]) ?$") - ] - - terminal_stderr_re = [ - re.compile(br"% Command incomplete", re.I), - re.compile(br"% Unknown command", re.I), - re.compile(br"(?:\S+) instance is already running", re.I), - re.compile(br"% (?:Create|Specify) .* first", re.I), - re.compile(br"(?:\S+) is not running", re.I), - re.compile(br"% Can't find .*", re.I), - re.compile(br"invalid input", re.I), - re.compile(br"connection timed out", re.I), - re.compile(br"[^\r\n]+ not found"), - ] - - def on_open_shell(self): - try: - self._exec_cli_command(b'terminal length 0') - except AnsibleConnectionFailure: - raise AnsibleConnectionFailure('unable to set terminal parameters') - - def on_become(self, passwd=None): - # NOTE: For FRR, enable password only takes effect when telnetting to individual daemons - # vtysh will always drop into enable mode since it runs as a privileged process - pass - - def on_unbecome(self): - # NOTE: For FRR, enable password only takes effect when telnetting to individual daemons - # vtysh will always drop into enable mode since it runs as a privileged process - pass diff --git a/test/sanity/ignore.txt b/test/sanity/ignore.txt index eac7e6f06b..25f26df9e7 100644 --- a/test/sanity/ignore.txt +++ b/test/sanity/ignore.txt @@ -325,20 +325,6 @@ lib/ansible/module_utils/network/fortimanager/fortimanager.py future-import-boil lib/ansible/module_utils/network/fortimanager/fortimanager.py metaclass-boilerplate lib/ansible/module_utils/network/fortios/fortios.py future-import-boilerplate lib/ansible/module_utils/network/fortios/fortios.py metaclass-boilerplate -lib/ansible/module_utils/network/frr/frr.py future-import-boilerplate -lib/ansible/module_utils/network/frr/frr.py metaclass-boilerplate -lib/ansible/module_utils/network/frr/providers/cli/config/base.py future-import-boilerplate -lib/ansible/module_utils/network/frr/providers/cli/config/base.py metaclass-boilerplate -lib/ansible/module_utils/network/frr/providers/cli/config/bgp/address_family.py future-import-boilerplate -lib/ansible/module_utils/network/frr/providers/cli/config/bgp/address_family.py metaclass-boilerplate -lib/ansible/module_utils/network/frr/providers/cli/config/bgp/neighbors.py future-import-boilerplate -lib/ansible/module_utils/network/frr/providers/cli/config/bgp/neighbors.py metaclass-boilerplate -lib/ansible/module_utils/network/frr/providers/cli/config/bgp/process.py future-import-boilerplate -lib/ansible/module_utils/network/frr/providers/cli/config/bgp/process.py metaclass-boilerplate -lib/ansible/module_utils/network/frr/providers/module.py future-import-boilerplate -lib/ansible/module_utils/network/frr/providers/module.py metaclass-boilerplate -lib/ansible/module_utils/network/frr/providers/providers.py future-import-boilerplate -lib/ansible/module_utils/network/frr/providers/providers.py metaclass-boilerplate lib/ansible/module_utils/network/ftd/common.py future-import-boilerplate lib/ansible/module_utils/network/ftd/common.py metaclass-boilerplate lib/ansible/module_utils/network/ftd/configuration.py future-import-boilerplate @@ -5054,15 +5040,6 @@ lib/ansible/modules/network/fortios/fortios_wireless_controller_wtp.py validate- lib/ansible/modules/network/fortios/fortios_wireless_controller_wtp_group.py validate-modules:parameter-list-no-elements lib/ansible/modules/network/fortios/fortios_wireless_controller_wtp_profile.py validate-modules:doc-choices-do-not-match-spec lib/ansible/modules/network/fortios/fortios_wireless_controller_wtp_profile.py validate-modules:parameter-list-no-elements -lib/ansible/modules/network/frr/frr_bgp.py validate-modules:doc-elements-mismatch -lib/ansible/modules/network/frr/frr_bgp.py validate-modules:doc-missing-type -lib/ansible/modules/network/frr/frr_bgp.py validate-modules:doc-required-mismatch -lib/ansible/modules/network/frr/frr_bgp.py validate-modules:invalid-ansiblemodule-schema -lib/ansible/modules/network/frr/frr_bgp.py validate-modules:nonexistent-parameter-documented -lib/ansible/modules/network/frr/frr_bgp.py validate-modules:parameter-type-not-in-doc -lib/ansible/modules/network/frr/frr_bgp.py validate-modules:undocumented-parameter -lib/ansible/modules/network/frr/frr_facts.py validate-modules:parameter-list-no-elements -lib/ansible/modules/network/frr/frr_facts.py validate-modules:parameter-type-not-in-doc lib/ansible/modules/network/icx/icx_command.py validate-modules:parameter-list-no-elements lib/ansible/modules/network/icx/icx_config.py validate-modules:parameter-list-no-elements lib/ansible/modules/network/icx/icx_facts.py validate-modules:parameter-list-no-elements diff --git a/test/units/modules/network/frr/fixtures/frr_bgp_config b/test/units/modules/network/frr/fixtures/frr_bgp_config deleted file mode 100644 index eeecbe7ae6..0000000000 --- a/test/units/modules/network/frr/fixtures/frr_bgp_config +++ /dev/null @@ -1,24 +0,0 @@ -! -router bgp 64496 - bgp router-id 192.0.2.1 - bgp log-neighbor-changes - neighbor 192.51.100.1 remote-as 64496 - neighbor 192.51.100.1 timers 120 360 - neighbor 198.51.100.3 remote-as 64498 - neighbor 2.2.2.2 remote-as 500 - neighbor 2.2.2.2 description EBGP_PEER - ! - address-family ipv4 unicast - network 192.0.1.0/24 route-map RMAP_1 - network 198.51.100.0/24 route-map RMAP_2 - redistribute static metric 100 - redistribute eigrp metric 10 route-map RMAP_3 - neighbor 2.2.2.2 remove-private-AS - neighbor 2.2.2.2 maximum-prefix 100 - exit-address-family - ! - address-family ipv4 multicast - network 10.0.0.0/8 route-map RMAP_1 - network 20.0.0.0/8 route-map RMAP_2 - exit-address-family -! diff --git a/test/units/modules/network/frr/fixtures/frr_facts_show_interface b/test/units/modules/network/frr/fixtures/frr_facts_show_interface deleted file mode 100644 index 62f08881f5..0000000000 --- a/test/units/modules/network/frr/fixtures/frr_facts_show_interface +++ /dev/null @@ -1,36 +0,0 @@ -Interface eth0 is up, line protocol is up - Link ups: 0 last: (never) - Link downs: 0 last: (never) - vrf: Default-IP-Routing-Table - index 2 metric 0 mtu 1450 speed 0 - flags: <UP,BROADCAST,RUNNING,MULTICAST> - Type: Ethernet - HWaddr: fa:16:3e:d4:32:b2 - bandwidth 4048 Mbps - inet 192.168.1.8/24 broadcast 192.168.1.255 - inet6 fe80::f816:3eff:fed4:32b2/64 - Interface Type Other -Interface eth1 is up, line protocol is up - Link ups: 0 last: (never) - Link downs: 0 last: (never) - vrf: Default-IP-Routing-Table - Description: Secondary Interface - index 3 metric 0 mtu 1500 speed 0 - flags: <UP,BROADCAST,RUNNING,MULTICAST> - Type: Ethernet - HWaddr: fa:16:3e:95:88:f7 - inet 192.168.1.21/24 broadcast 192.168.1.255 - inet 192.168.1.19/24 broadcast 192.168.1.255 secondary - inet 192.168.1.18/24 broadcast 192.168.1.255 secondary - inet6 fe80::f816:3eff:fe95:88f7/64 - inet6 3ffe:506::1/48 - inet6 3ffe:504::1/48 - Interface Type Other -Interface lo is up, line protocol is up - Link ups: 0 last: (never) - Link downs: 0 last: (never) - vrf: Default-IP-Routing-Table - index 1 metric 0 mtu 65536 speed 0 - flags: <UP,LOOPBACK,RUNNING> - Type: Loopback - Interface Type Other diff --git a/test/units/modules/network/frr/fixtures/frr_facts_show_memory b/test/units/modules/network/frr/fixtures/frr_facts_show_memory deleted file mode 100644 index d64a9a4c5c..0000000000 --- a/test/units/modules/network/frr/fixtures/frr_facts_show_memory +++ /dev/null @@ -1,82 +0,0 @@ -Memory statistics for zebra: -System allocator statistics: - Total heap allocated: 4200 KiB - Holding block headers: 0 bytes - Used small blocks: 0 bytes - Used ordinary blocks: 2927 KiB - Free small blocks: 2096 bytes - Free ordinary blocks: 1273 KiB - Ordinary blocks: 14 - Small blocks: 60 - Holding blocks: 0 -(see system documentation for 'mallinfo' for meaning) ---- qmem libfrr --- -Buffer : 18 24 448 -Buffer data : 1 4120 4120 -Host config : 4 (variably sized) 96 -Command Tokens : 3162 72 228128 -Command Token Text : 2362 (variably sized) 77344 -Command Token Help : 2362 (variably sized) 56944 -Command Argument : 2 (variably sized) 48 -Command Argument Name : 534 (variably sized) 12912 -FRR POSIX Thread : 28 (variably sized) 2016 -POSIX synchronization primitives: 28 (variably sized) 1344 -Graph : 24 8 576 -Graph Node : 3744 32 150112 -Hash : 2495 (variably sized) 119880 -Hash Bucket : 778 32 31296 -Hash Index : 1248 (variably sized) 363040 -Hook entry : 12 48 672 -Interface : 3 248 744 -Connected : 8 40 320 -Informational Link Parameters : 1 96 104 -Link List : 43 40 1720 -Link Node : 1308 24 31456 -Logging : 1 80 88 -Temporary memory : 23 (variably sized) 42584 -Nexthop : 27 112 3256 -NetNS Context : 2 (variably sized) 128 -NetNS Name : 1 18 24 -Priority queue : 15 32 600 -Priority queue data : 15 256 3960 -Prefix : 12 48 672 -Privilege information : 2 (variably sized) 80 -Stream : 36 (variably sized) 591264 -Stream FIFO : 28 64 2016 -Route table : 14 48 784 -Route node : 43 (variably sized) 4920 -Thread : 51 176 9384 -Thread master : 59 (variably sized) 251016 -Thread Poll Info : 30 8192 246000 -Thread stats : 52 64 3744 -Vector : 7543 16 181432 -Vector index : 7543 (variably sized) 246776 -VRF : 1 184 184 -VRF bit-map : 28 8 672 -VTY : 6 (variably sized) 19440 -Work queue : 2 (variably sized) 224 -Work queue name string : 1 22 24 -Redistribution instance IDs : 1 2 24 ---- qmem Label Manager --- -Label Manager Chunk : 1 16 24 ---- qmem zebra --- -ZEBRA VRF : 1 656 664 -Route Entry : 27 80 2392 -RIB destination : 19 48 1080 -RIB table info : 4 16 96 -Nexthop tracking object : 2 200 400 -Zebra Name Space : 1 312 312 -PTM BFD process registration table.: 3 32 120 ---- qmem Table Manager --- - -Memory statistics for ripd: -System allocator statistics: - Total heap allocated: 936 KiB - Holding block headers: 0 bytes - Used small blocks: 0 bytes - Used ordinary blocks: 901 KiB - Free small blocks: 1504 bytes - Free ordinary blocks: 35 KiB - Ordinary blocks: 4 - Small blocks: 44 - Holding blocks: 0 diff --git a/test/units/modules/network/frr/fixtures/frr_facts_show_version b/test/units/modules/network/frr/fixtures/frr_facts_show_version deleted file mode 100644 index daec039dfc..0000000000 --- a/test/units/modules/network/frr/fixtures/frr_facts_show_version +++ /dev/null @@ -1,16 +0,0 @@ -FRRouting 6.0 (rtr1). -Copyright 1996-2005 Kunihiro Ishiguro, et al. -configured with: - '--build=x86_64-redhat-linux-gnu' '--host=x86_64-redhat-linux-gnu' '--program-prefix=' - '--disable-dependency-tracking' '--prefix=/usr' '--exec-prefix=/usr' '--bindir=/usr/bin' - '--sysconfdir=/etc' '--datadir=/usr/share' '--includedir=/usr/include' '--libdir=/usr/lib64' - '--libexecdir=/usr/libexec' '--localstatedir=/var' '--sharedstatedir=/var/lib' '--mandir=/usr/share/man' - '--infodir=/usr/share/info' '--sbindir=/usr/lib/frr' '--sysconfdir=/etc/frr' '--localstatedir=/var/run/frr' - '--disable-static' '--disable-werror' '--enable-irdp' '--enable-multipath=256' '--enable-vtysh' - '--enable-ospfclient' '--enable-ospfapi' '--enable-rtadv' '--enable-ldpd' '--enable-pimd' - '--enable-pbrd' '--enable-nhrpd' '--enable-eigrpd' '--enable-babeld' '--enable-user=frr' - '--enable-group=frr' '--enable-vty-group=frrvty' '--enable-fpm' '--enable-watchfrr' '--disable-bgp-vnc' - '--enable-isisd' '--enable-systemd' '--disable-rpki' '--enable-bfdd' 'build_alias=x86_64-redhat-linux-gnu' - 'host_alias=x86_64-redhat-linux-gnu' 'PKG_CONFIG_PATH=:/usr/lib64/pkgconfig:/usr/share/pkgconfig' - 'CFLAGS=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong - --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic' 'LDFLAGS=-Wl,-z,relro ' diff --git a/test/units/modules/network/frr/frr_module.py b/test/units/modules/network/frr/frr_module.py deleted file mode 100644 index b14d1fdb26..0000000000 --- a/test/units/modules/network/frr/frr_module.py +++ /dev/null @@ -1,75 +0,0 @@ -# -*- coding: utf-8 -*- -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -# - -from __future__ import (absolute_import, division, print_function) -__metaclass__ = type - -import os -import json - -from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase - - -fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') -fixture_data = {} - - -def load_fixture(name): - path = os.path.join(fixture_path, name) - - if path in fixture_data: - return fixture_data[path] - - with open(path) as f: - data = f.read() - - try: - data = json.loads(data) - except Exception: - pass - - fixture_data[path] = data - return data - - -class TestFrrModule(ModuleTestCase): - - def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False): - - self.load_fixtures(commands) - - if failed: - result = self.failed() - self.assertTrue(result['failed'], result) - else: - result = self.changed(changed) - self.assertEqual(result['changed'], changed, result) - - if commands is not None: - if sort: - self.assertEqual(sorted(commands), sorted(result['commands']), result['commands']) - else: - self.assertEqual(commands, result['commands'], result['commands']) - - return result - - def failed(self): - with self.assertRaises(AnsibleFailJson) as exc: - self.module.main() - - result = exc.exception.args[0] - self.assertTrue(result['failed'], result) - return result - - def changed(self, changed=False): - with self.assertRaises(AnsibleExitJson) as exc: - self.module.main() - - result = exc.exception.args[0] - self.assertEqual(result['changed'], changed, result) - return result - - def load_fixtures(self, commands=None): - pass diff --git a/test/units/modules/network/frr/test_frr_bgp.py b/test/units/modules/network/frr/test_frr_bgp.py deleted file mode 100644 index 878c8fc99a..0000000000 --- a/test/units/modules/network/frr/test_frr_bgp.py +++ /dev/null @@ -1,199 +0,0 @@ -# -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) -# - -from __future__ import (absolute_import, division, print_function) -__metaclass__ = type - -from ansible.module_utils.network.frr.providers.cli.config.bgp.process import Provider -from ansible.modules.network.frr import frr_bgp -from .frr_module import TestFrrModule, load_fixture - - -class TestFrrBgpModule(TestFrrModule): - module = frr_bgp - - def setUp(self): - super(TestFrrBgpModule, self).setUp() - self._bgp_config = load_fixture('frr_bgp_config') - - def test_frr_bgp(self): - obj = Provider(params=dict(config=dict(bgp_as=64496, router_id='192.0.2.2', networks=None, - address_family=None), operation='merge')) - commands = obj.render(self._bgp_config) - self.assertEqual(commands, ['router bgp 64496', 'bgp router-id 192.0.2.2', 'exit']) - - def test_frr_bgp_idempotent(self): - obj = Provider(params=dict(config=dict(bgp_as=64496, router_id='192.0.2.1', networks=None, - address_family=None), operation='merge')) - commands = obj.render(self._bgp_config) - self.assertEqual(commands, []) - - def test_frr_bgp_remove(self): - obj = Provider(params=dict(config=dict(bgp_as=64496, networks=None, - address_family=None), operation='delete')) - commands = obj.render(self._bgp_config) - self.assertEqual(commands, ['no router bgp 64496']) - - def test_frr_bgp_neighbor(self): - obj = Provider(params=dict(config=dict(bgp_as=64496, neighbors=[dict(neighbor='192.51.100.2', remote_as=64496)], - networks=None, address_family=None), - operation='merge')) - commands = obj.render(self._bgp_config) - self.assertEqual(commands, ['router bgp 64496', 'neighbor 192.51.100.2 remote-as 64496', 'exit']) - - def test_frr_bgp_neighbor_idempotent(self): - obj = Provider(params=dict(config=dict(bgp_as=64496, neighbors=[dict(neighbor='192.51.100.1', remote_as=64496, - timers=dict(keepalive=120, holdtime=360))], - networks=None, address_family=None), - operation='merge')) - commands = obj.render(self._bgp_config) - self.assertEqual(commands, []) - - def test_frr_bgp_network(self): - obj = Provider(params=dict(config=dict(bgp_as=64496, networks=[dict(prefix='192.0.2.0', masklen=24, route_map='RMAP_1')], - address_family=None), - operation='merge')) - commands = obj.render(self._bgp_config) - self.assertEqual(sorted(commands), sorted(['router bgp 64496', 'network 192.0.2.0/24 route-map RMAP_1', 'exit'])) - - def test_frr_bgp_network_idempotent(self): - obj = Provider(params=dict(config=dict(bgp_as=64496, networks=[dict(prefix='192.0.1.0', masklen=24, route_map='RMAP_1'), - dict(prefix='198.51.100.0', masklen=24, route_map='RMAP_2')], - address_family=None), - operation='merge')) - commands = obj.render(self._bgp_config) - self.assertEqual(commands, []) - - def test_frr_bgp_address_family_redistribute(self): - rd_1 = dict(protocol='ospf', id='233', metric=90, route_map=None) - - config = dict(bgp_as=64496, address_family=[dict(afi='ipv4', safi='unicast', redistribute=[rd_1])], - networks=None) - - obj = Provider(params=dict(config=config, operation='merge')) - - commands = obj.render(self._bgp_config) - cmd = ['router bgp 64496', 'address-family ipv4 unicast', 'redistribute ospf 233 metric 90', - 'exit-address-family', 'exit'] - self.assertEqual(sorted(commands), sorted(cmd)) - - def test_frr_bgp_address_family_redistribute_idempotent(self): - rd_1 = dict(protocol='eigrp', metric=10, route_map='RMAP_3', id=None) - rd_2 = dict(protocol='static', metric=100, id=None, route_map=None) - - config = dict(bgp_as=64496, address_family=[dict(afi='ipv4', safi='unicast', redistribute=[rd_1, rd_2])], - networks=None) - - obj = Provider(params=dict(config=config, operation='merge')) - - commands = obj.render(self._bgp_config) - self.assertEqual(commands, []) - - def test_frr_bgp_address_family_neighbors(self): - af_nbr_1 = dict(neighbor='192.51.100.1', maximum_prefix=35, activate=True) - af_nbr_2 = dict(neighbor='192.51.100.3', route_reflector_client=True, activate=True) - - config = dict(bgp_as=64496, address_family=[dict(afi='ipv4', safi='multicast', neighbors=[af_nbr_1, af_nbr_2])], - networks=None) - - obj = Provider(params=dict(config=config, operation='merge')) - - commands = obj.render(self._bgp_config) - cmd = ['router bgp 64496', 'address-family ipv4 multicast', 'neighbor 192.51.100.1 activate', - 'neighbor 192.51.100.1 maximum-prefix 35', 'neighbor 192.51.100.3 activate', - 'neighbor 192.51.100.3 route-reflector-client', 'exit-address-family', 'exit'] - self.assertEqual(sorted(commands), sorted(cmd)) - - def test_frr_bgp_address_family_neighbors_idempotent(self): - af_nbr_1 = dict(neighbor='2.2.2.2', remove_private_as=True, maximum_prefix=100) - - config = dict(bgp_as=64496, address_family=[dict(afi='ipv4', safi='unicast', neighbors=[af_nbr_1])], - networks=None) - - obj = Provider(params=dict(config=config, operation='merge')) - - commands = obj.render(self._bgp_config) - self.assertEqual(commands, []) - - def test_frr_bgp_address_family_networks(self): - net = dict(prefix='1.0.0.0', masklen=8, route_map='RMAP_1') - net2 = dict(prefix='192.168.1.0', masklen=24, route_map='RMAP_2') - - config = dict(bgp_as=64496, address_family=[dict(afi='ipv4', safi='multicast', networks=[net, net2])], - networks=None) - - obj = Provider(params=dict(config=config, operation='merge')) - - commands = obj.render(self._bgp_config) - cmd = ['router bgp 64496', 'address-family ipv4 multicast', 'network 1.0.0.0/8 route-map RMAP_1', - 'network 192.168.1.0/24 route-map RMAP_2', 'exit-address-family', 'exit'] - self.assertEqual(sorted(commands), sorted(cmd)) - - def test_frr_bgp_address_family_networks_idempotent(self): - net = dict(prefix='10.0.0.0', masklen=8, route_map='RMAP_1') - net2 = dict(prefix='20.0.0.0', masklen=8, route_map='RMAP_2') - - config = dict(bgp_as=64496, address_family=[dict(afi='ipv4', safi='multicast', networks=[net, net2])], - networks=None) - - obj = Provider(params=dict(config=config, operation='merge')) - - commands = obj.render(self._bgp_config) - self.assertEqual(commands, []) - - def test_frr_bgp_operation_override(self): - net_1 = dict(prefix='1.0.0.0', masklen=8, route_map='RMAP_1') - net_2 = dict(prefix='192.168.1.0', masklen=24, route_map='RMAP_2') - nbr_1 = dict(neighbor='192.51.100.1', remote_as=64496, advertisement_interval=120) - nbr_2 = dict(neighbor='192.51.100.3', remote_as=64496, timers=dict(keepalive=300, holdtime=360)) - af_nbr_1 = dict(neighbor='192.51.100.1', maximum_prefix=35) - af_nbr_2 = dict(neighbor='192.51.100.3', route_reflector_client=True) - - af_1 = dict(afi='ipv4', safi='unicast', neighbors=[af_nbr_1, af_nbr_2]) - af_2 = dict(afi='ipv4', safi='multicast', networks=[net_1, net_2]) - config = dict(bgp_as=64496, neighbors=[nbr_1, nbr_2], address_family=[af_1, af_2], networks=None) - - obj = Provider(params=dict(config=config, operation='override')) - commands = obj.render(self._bgp_config) - - cmd = ['no router bgp 64496', 'router bgp 64496', 'neighbor 192.51.100.1 remote-as 64496', - 'neighbor 192.51.100.1 advertisement-interval 120', 'neighbor 192.51.100.3 remote-as 64496', - 'neighbor 192.51.100.3 timers 300 360', 'address-family ipv4 unicast', - 'neighbor 192.51.100.1 maximum-prefix 35', 'neighbor 192.51.100.3 route-reflector-client', 'exit-address-family', - 'address-family ipv4 multicast', 'network 1.0.0.0/8 route-map RMAP_1', 'network 192.168.1.0/24 route-map RMAP_2', - 'exit-address-family', 'exit'] - - self.assertEqual(sorted(commands), sorted(cmd)) - - def test_frr_bgp_operation_replace(self): - rd = dict(protocol='ospf', id=223, metric=110, route_map=None) - net = dict(prefix='10.0.0.0', masklen=8, route_map='RMAP_1') - net2 = dict(prefix='20.0.0.0', masklen=8, route_map='RMAP_2') - - af_1 = dict(afi='ipv4', safi='unicast', redistribute=[rd]) - af_2 = dict(afi='ipv4', safi='multicast', networks=[net, net2]) - - config = dict(bgp_as=64496, address_family=[af_1, af_2], networks=None) - obj = Provider(params=dict(config=config, operation='replace')) - commands = obj.render(self._bgp_config) - - cmd = ['router bgp 64496', 'address-family ipv4 unicast', 'redistribute ospf 223 metric 110', 'no redistribute eigrp', - 'no redistribute static', 'exit-address-family', 'exit'] - - self.assertEqual(sorted(commands), sorted(cmd)) - - def test_frr_bgp_operation_replace_with_new_as(self): - rd = dict(protocol='ospf', id=223, metric=110, route_map=None) - - af_1 = dict(afi='ipv4', safi='unicast', redistribute=[rd]) - - config = dict(bgp_as=64497, address_family=[af_1], networks=None) - obj = Provider(params=dict(config=config, operation='replace')) - commands = obj.render(self._bgp_config) - - cmd = ['no router bgp 64496', 'router bgp 64497', 'address-family ipv4 unicast', 'redistribute ospf 223 metric 110', - 'exit-address-family', 'exit'] - - self.assertEqual(sorted(commands), sorted(cmd)) diff --git a/test/units/modules/network/frr/test_frr_facts.py b/test/units/modules/network/frr/test_frr_facts.py deleted file mode 100644 index 8e15311c4c..0000000000 --- a/test/units/modules/network/frr/test_frr_facts.py +++ /dev/null @@ -1,114 +0,0 @@ -# (c) 2019, Ansible by Red Hat, inc -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) - -from __future__ import (absolute_import, division, print_function) -__metaclass__ = type - -from units.compat.mock import patch -from ansible.modules.network.frr import frr_facts -from units.modules.utils import set_module_args -from .frr_module import TestFrrModule, load_fixture - - -class TestFrrFactsModule(TestFrrModule): - - module = frr_facts - - def setUp(self): - super(TestFrrFactsModule, self).setUp() - self.mock_run_commands = patch('ansible.modules.network.frr.frr_facts.run_commands') - self.run_commands = self.mock_run_commands.start() - - self.mock_get_capabilities = patch('ansible.modules.network.frr.frr_facts.get_capabilities') - self.get_capabilities = self.mock_get_capabilities.start() - self.get_capabilities.return_value = { - 'device_info': { - 'network_os': 'frr', - 'network_os_hostname': 'rtr1', - 'network_os_version': '6.0', - }, - 'supported_protocols': { - 'ldp': False - }, - 'network_api': 'cliconf' - } - - def tearDown(self): - super(TestFrrFactsModule, self).tearDown() - self.mock_run_commands.stop() - self.mock_get_capabilities.stop() - - def load_fixtures(self, commands=None): - def load_from_file(*args, **kwargs): - commands = kwargs['commands'] - output = list() - - for command in commands: - filename = str(command).split(' | ')[0].replace(' ', '_') - output.append(load_fixture('frr_facts_%s' % filename)) - return output - - self.run_commands.side_effect = load_from_file - - def test_frr_facts_default(self): - set_module_args(dict(gather_subset='default')) - result = self.execute_module() - self.assertEqual( - result['ansible_facts']['ansible_net_hostname'], 'rtr1' - ) - self.assertEqual( - result['ansible_facts']['ansible_net_version'], '6.0' - ) - self.assertEqual( - result['ansible_facts']['ansible_net_system'], 'frr' - ) - - def test_frr_facts_interfaces(self): - set_module_args(dict(gather_subset='interfaces')) - result = self.execute_module() - self.assertEqual( - result['ansible_facts']['ansible_net_interfaces']['eth0']['macaddress'], 'fa:16:3e:d4:32:b2' - ) - self.assertEqual( - result['ansible_facts']['ansible_net_interfaces']['eth1']['macaddress'], 'fa:16:3e:95:88:f7' - ) - self.assertEqual( - result['ansible_facts']['ansible_net_interfaces']['eth0']['ipv4'], [{"address": "192.168.1.8", - "subnet": "24"}] - ) - self.assertEqual( - result['ansible_facts']['ansible_net_interfaces']['eth0']['ipv6'], [{"address": "fe80::f816:3eff:fed4:32b2", - "subnet": "64"}] - ) - self.assertEqual( - sorted(result['ansible_facts']['ansible_net_all_ipv4_addresses']), sorted(["192.168.1.19", - "192.168.1.18", - "192.168.1.21", - "192.168.1.8"]) - ) - self.assertEqual( - sorted(result['ansible_facts']['ansible_net_all_ipv6_addresses']), sorted(["fe80::f816:3eff:fe95:88f7", - "3ffe:506::1", - "3ffe:504::1", - "fe80::f816:3eff:fed4:32b2"]) - ) - - def test_frr_facts_hardware(self): - set_module_args(dict(gather_subset='hardware')) - result = self.execute_module() - - self.assertEqual( - result['ansible_facts']['ansible_net_mem_stats']["zebra"]['total_heap_allocated'], '4200 KiB' - ) - - self.assertEqual( - result['ansible_facts']['ansible_net_mem_stats']["ripd"]['total_heap_allocated'], '936 KiB' - ) - - self.assertEqual( - result['ansible_facts']['ansible_net_mem_stats']["ripd"]['used_ordinary_blocks'], '901 KiB' - ) - - self.assertEqual( - result['ansible_facts']['ansible_net_mem_stats']["ripd"]['holding_block_headers'], '0 bytes' - ) |