diff --git a/plugins/module_utils/network/vyos/facts/static_routes/static_routes.py b/plugins/module_utils/network/vyos/facts/static_routes/static_routes.py index 615b3c2b..6149bdb4 100644 --- a/plugins/module_utils/network/vyos/facts/static_routes/static_routes.py +++ b/plugins/module_utils/network/vyos/facts/static_routes/static_routes.py @@ -1,167 +1,168 @@ # # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The vyos static_routes fact class It is in this file the configuration is collected from the device for a given resource, parsed, and the facts tree is populated based on the configuration. """ from __future__ import absolute_import, division, print_function __metaclass__ = type from copy import deepcopy from re import M, findall, search from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.static_routes.static_routes import ( Static_routesArgs, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.utils import ( get_route_type, ) class Static_routesFacts(object): """The vyos static_routes fact class""" def __init__(self, module, subspec="config", options="options"): self._module = module self.argument_spec = Static_routesArgs.argument_spec spec = deepcopy(self.argument_spec) if subspec: if options: facts_argument_spec = spec[subspec][options] else: facts_argument_spec = spec[subspec] else: facts_argument_spec = spec self.generated_spec = utils.generate_dict(facts_argument_spec) def get_device_data(self, connection): return connection.get_config() def populate_facts(self, connection, ansible_facts, data=None): """Populate the facts for static_routes :param connection: the device connection :param ansible_facts: Facts dictionary :param data: previously collected conf :rtype: dictionary :returns: facts """ if not data: data = self.get_device_data(connection) # typically data is populated from the current device configuration # data = connection.get('show running-config | section ^interface') # using mock data instead objs = [] r_v4 = [] r_v6 = [] af = [] - static_routes = findall(r"set protocols static route(6)? (\S+)", data, M) + static_routes = findall(r"set protocols static (?:interface-)?route(6)? (\S+)", data, M) if static_routes: for route in set(static_routes): route_regex = r" %s .+$" % route[1] cfg = findall(route_regex, data, M) sr = self.render_config(cfg) sr["dest"] = route[1].strip("'") afi = self.get_afi(sr["dest"]) if afi == "ipv4": r_v4.append(sr) else: r_v6.append(sr) if r_v4: afi_v4 = {"afi": "ipv4", "routes": r_v4} af.append(afi_v4) if r_v6: afi_v6 = {"afi": "ipv6", "routes": r_v6} af.append(afi_v6) config = {"address_families": af} if config: objs.append(config) ansible_facts["ansible_network_resources"].pop("static_routes", None) facts = {} if objs: facts["static_routes"] = [] params = utils.validate_config(self.argument_spec, {"config": objs}) for cfg in params["config"]: facts["static_routes"].append(utils.remove_empties(cfg)) ansible_facts["ansible_network_resources"].update(facts) return ansible_facts def render_config(self, conf): """ Render config as dictionary structure and delete keys from spec for null values :param spec: The facts tree, generated from the argspec :param conf: The configuration :rtype: dictionary :returns: The generated config """ next_hops_conf = "\n".join(filter(lambda x: ("next-hop" in x or "interface" in x), conf)) blackhole_conf = "\n".join(filter(lambda x: ("blackhole" in x), conf)) routes_dict = { "blackhole_config": self.parse_blackhole(blackhole_conf), "next_hops": self.parse_next_hop(next_hops_conf), } return routes_dict def parse_blackhole(self, conf): blackhole = None if conf: distance = search(r"^.*blackhole distance (.\S+)", conf, M) bh = conf.find("blackhole") if distance is not None: blackhole = {} value = distance.group(1).strip("'") blackhole["distance"] = int(value) elif bh: blackhole = {} blackhole["type"] = "blackhole" return blackhole def get_afi(self, address): route_type = get_route_type(address) if route_type == "route": return "ipv4" elif route_type == "route6": return "ipv6" def parse_next_hop(self, conf): nh_list = None if conf: # Each hop is keyed on what identifies it on the device: the gateway address # for "next-hop X ..." lines, the interface name for "interface X ..." lines # (or "next-hop-interface X ..." for VyOS 1.3 interface-route). hops = {} for line in conf.splitlines(): match = search( - r"\s(next-hop-interface|next-hop|interface) '?([^'\s]+)'?(.*)$", line + r"\s(next-hop-interface|next-hop|interface) '?([^'\s]+)'?(.*)$", + line, ) if not match: continue kind, name, rest = match.groups() if kind == "next-hop": hop = hops.setdefault((kind, name), {"forward_router_address": name}) interface = search(r"\binterface '?([^'\s]+)", rest) if interface: hop["interface"] = interface.group(1) else: hop = hops.setdefault(("interface", name), {"interface": name}) distance = search(r"\bdistance '?(\d+)", rest) if distance: hop["admin_distance"] = int(distance.group(1)) if search(r"\bdisable\b", rest): hop["enabled"] = False nh_list = list(hops.values()) return nh_list diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_static_routes_legacy_interface_config.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_static_routes_legacy_interface_config.cfg new file mode 100644 index 00000000..6dc564a2 --- /dev/null +++ b/tests/unit/modules/network/vyos/fixtures/vyos_static_routes_legacy_interface_config.cfg @@ -0,0 +1,2 @@ +set protocols static interface-route 10.0.0.0/8 next-hop-interface eth0 distance '20' +set protocols static interface-route 10.0.0.0/8 next-hop-interface eth1 disable diff --git a/tests/unit/modules/network/vyos/test_vyos_static_routes.py b/tests/unit/modules/network/vyos/test_vyos_static_routes.py index f74ffc26..19547f8c 100644 --- a/tests/unit/modules/network/vyos/test_vyos_static_routes.py +++ b/tests/unit/modules/network/vyos/test_vyos_static_routes.py @@ -1,312 +1,383 @@ # (c) 2016 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 . # Make coding more python3-ish from __future__ import absolute_import, division, print_function __metaclass__ = type from unittest.mock import patch from ansible_collections.vyos.vyos.plugins.modules import vyos_static_routes from ansible_collections.vyos.vyos.tests.unit.modules.utils import set_module_args from .vyos_module import TestVyosModule, load_fixture class TestVyosStaticRoutesModule(TestVyosModule): module = vyos_static_routes def setUp(self): super(TestVyosStaticRoutesModule, self).setUp() self.mock_get_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.network.Config.get_config", ) self.get_config = self.mock_get_config.start() self.mock_load_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.network.Config.load_config", ) self.load_config = self.mock_load_config.start() self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection", ) self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_execute_show_command = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.static_routes.static_routes.Static_routesFacts.get_device_data", ) self.execute_show_command = self.mock_execute_show_command.start() self.mock_get_os_version = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.static_routes.static_routes.get_os_version", ) self.test_version = "1.3" self.get_os_version = self.mock_get_os_version.start() self.get_os_version.return_value = self.test_version def tearDown(self): super(TestVyosStaticRoutesModule, self).tearDown() self.mock_get_resource_connection_config.stop() self.mock_get_resource_connection_facts.stop() self.mock_get_config.stop() self.mock_load_config.stop() self.mock_execute_show_command.stop() def load_fixtures(self, commands=None, filename=None): def load_from_file(*args, **kwargs): - return load_fixture("vyos_static_routes_config.cfg") + return load_fixture(filename or "vyos_static_routes_config.cfg") self.execute_show_command.side_effect = load_from_file def test_vyos_static_routes_merged(self): set_module_args( dict( config=[ dict( address_families=[ dict( afi="ipv4", routes=[ dict( dest="192.0.2.48/28", next_hops=[ dict( forward_router_address="192.0.2.9", admin_distance=10, ), dict( forward_router_address="192.0.2.10", interface="eth0", ), ], ), ], ), ], ), ], state="merged", ), ) commands = [ "set protocols static route 192.0.2.48/28", "set protocols static route 192.0.2.48/28 next-hop '192.0.2.9'", "set protocols static route 192.0.2.48/28 next-hop 192.0.2.9 distance '10'", "set protocols static route 192.0.2.48/28 next-hop '192.0.2.10'", "set protocols static interface-route 192.0.2.48/28 next-hop-interface 'eth0'", ] self.execute_module(changed=True, commands=commands) def test_vyos_static_routes_merged_idempotent(self): set_module_args( dict( config=[ dict( address_families=[ dict( afi="ipv4", routes=[ dict( dest="192.0.2.32/28", next_hops=[ dict(forward_router_address="192.0.2.9"), dict(forward_router_address="192.0.2.10"), ], ), ], ), ], ), ], state="merged", ), ) self.execute_module(changed=False, commands=[]) def test_vyos_static_routes_replaced(self): set_module_args( dict( config=[ dict( address_families=[ dict( afi="ipv4", routes=[ dict( dest="192.0.2.48/28", next_hops=[ dict( forward_router_address="192.0.2.9", interface="eth0", ), dict( forward_router_address="192.0.2.10", admin_distance=10, ), ], ), ], ), ], ), ], state="replaced", ), ) commands = [ "set protocols static route 192.0.2.48/28", "set protocols static route 192.0.2.48/28 next-hop '192.0.2.9'", "set protocols static interface-route 192.0.2.48/28 next-hop-interface 'eth0'", "set protocols static route 192.0.2.48/28 next-hop '192.0.2.10'", "set protocols static route 192.0.2.48/28 next-hop 192.0.2.10 distance '10'", ] self.execute_module(changed=True, commands=commands) def test_vyos_static_routes_replaced_idempotent(self): set_module_args( dict( config=[ dict( address_families=[ dict( afi="ipv4", routes=[ dict( dest="192.0.2.32/28", next_hops=[ dict(forward_router_address="192.0.2.9"), dict(forward_router_address="192.0.2.10"), ], ), ], ), ], ), ], state="replaced", ), ) self.execute_module(changed=False, commands=[]) def test_vyos_static_routes_overridden(self): set_module_args( dict( config=[ dict( address_families=[ dict( afi="ipv4", routes=[ dict( dest="192.0.2.48/28", next_hops=[ dict(forward_router_address="192.0.2.9"), dict(forward_router_address="192.0.2.10"), ], ), ], ), ], ), ], state="overridden", ), ) commands = [ "delete protocols static route 192.0.2.32/28", "set protocols static route 192.0.2.48/28", "set protocols static route 192.0.2.48/28 next-hop '192.0.2.9'", "set protocols static route 192.0.2.48/28 next-hop '192.0.2.10'", ] self.execute_module(changed=True, commands=commands) def test_vyos_static_routes_overridden_idempotent(self): set_module_args( dict( config=[ dict( address_families=[ dict( afi="ipv4", routes=[ dict( dest="192.0.2.32/28", next_hops=[ dict(forward_router_address="192.0.2.9"), dict(forward_router_address="192.0.2.10"), ], ), ], ), ], ), ], state="overridden", ), ) self.execute_module(changed=False, commands=[]) def test_vyos_static_routes_deleted(self): set_module_args( dict( config=[dict(address_families=[dict(afi="ipv4")])], state="deleted", ), ) commands = ["delete protocols static route"] self.execute_module(changed=True, commands=commands) def test_vyos_static_routes_merged_interface_next_hops(self): set_module_args( dict( config=[ dict( address_families=[ dict( afi="ipv4", routes=[ dict( dest="10.0.0.0/8", next_hops=[ dict(interface="eth3", admin_distance=30), dict(interface="eth4", enabled=False), ], ), ], ), ], ), ], state="merged", ), ) commands = [ "set protocols static route 10.0.0.0/8", "set protocols static interface-route 10.0.0.0/8 next-hop-interface 'eth3'", "set protocols static interface-route 10.0.0.0/8 next-hop-interface eth3 distance '30'", "set protocols static interface-route 10.0.0.0/8 next-hop-interface 'eth4'", "set protocols static interface-route 10.0.0.0/8 next-hop-interface eth4 'disable'", ] self.execute_module(changed=True, commands=commands) + + def _legacy_interface_route(self, next_hops): + return [ + dict( + address_families=[ + dict(afi="ipv4", routes=[dict(dest="10.0.0.0/8", next_hops=next_hops)]), + ], + ), + ] + + def test_vyos_static_routes_rendered_interface_next_hops(self): + set_module_args( + dict( + config=self._legacy_interface_route( + [ + dict(interface="eth3", admin_distance=30), + dict(interface="eth4", enabled=False), + ], + ), + state="rendered", + ), + ) + result = self.execute_module(changed=False) + self.assertEqual( + sorted(result["rendered"]), + sorted( + [ + "set protocols static route 10.0.0.0/8", + "set protocols static interface-route 10.0.0.0/8 next-hop-interface 'eth3'", + "set protocols static interface-route 10.0.0.0/8 next-hop-interface eth3 distance '30'", + "set protocols static interface-route 10.0.0.0/8 next-hop-interface 'eth4'", + "set protocols static interface-route 10.0.0.0/8 next-hop-interface eth4 'disable'", + ], + ), + ) + + def test_vyos_static_routes_parsed_legacy_interface_next_hops(self): + set_module_args( + dict( + running_config=load_fixture("vyos_static_routes_legacy_interface_config.cfg"), + state="parsed", + ), + ) + result = self.execute_module(changed=False) + self.assertEqual( + result["parsed"], + self._legacy_interface_route( + [ + dict(interface="eth0", admin_distance=20), + dict(interface="eth1", enabled=False), + ], + ), + ) + + def test_vyos_static_routes_merged_legacy_interface_next_hops_idempotent(self): + set_module_args( + dict( + config=self._legacy_interface_route( + [ + dict(interface="eth0", admin_distance=20), + dict(interface="eth1", enabled=False), + ], + ), + state="merged", + ), + ) + self.execute_module( + changed=False, + commands=[], + filename="vyos_static_routes_legacy_interface_config.cfg", + )