diff --git a/plugins/module_utils/network/vyos/facts/legacy/base.py b/plugins/module_utils/network/vyos/facts/legacy/base.py index 552c55c1..238cc3b0 100644 --- a/plugins/module_utils/network/vyos/facts/legacy/base.py +++ b/plugins/module_utils/network/vyos/facts/legacy/base.py @@ -1,200 +1,208 @@ # -*- 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 interfaces 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 import platform import re +from ansible.module_utils.common.text.converters import to_text from ansible.module_utils.connection import ConnectionError from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( get_capabilities, get_connection, run_commands, ) class LegacyFactsBase(object): COMMANDS = frozenset() def __init__(self, module): self.module = module self.facts = dict() self.warnings = list() self.responses = None def populate(self): self.responses = run_commands(self.module, list(self.COMMANDS)) class Default(LegacyFactsBase): COMMANDS = [ "show version", ] def populate(self): super(Default, self).populate() data = self.responses[0] self.facts["serialnum"] = self.parse_serialnum(data) self.facts.update(self.platform_facts()) secure_boot = self.secure_boot_facts() if secure_boot: self.facts["secure_boot"] = secure_boot def secure_boot_facts(self): """Secure Boot state, on images that have show secure-boot. Older images reject the command; the fact is then left out. """ data = self.run_optional("show secure-boot") if data is None: return None match = re.search(r"^SecureBoot\s+(enabled|disabled)\s*$", data, re.M) if not match: return None facts = { "enabled": match.group(1) == "enabled", "uefi": "legacy BIOS mode" not in data, } if facts["enabled"]: detail = self.run_optional("show secure-boot detail") or "" facts["certificates"] = [ {"issuer": issuer, "subject": subject} for issuer, subject in re.findall( r"^Issuer:\s+(.+?)\s*\nSubject:\s+(.+?)\s*$", detail, re.M, ) ] return facts def run_optional(self, command): - """Output of a command the image may not have, or None when the device rejects it.""" + """Output of a command the image may not have, or None when the device rejects it. + + Only "Invalid command" means the image lacks the command; other connection errors + (timeouts, disconnects) fail the module as in run_commands. + """ try: return get_connection(self.module).run_commands(commands=[command])[0] - except ConnectionError: - return None + except ConnectionError as exc: + msg = to_text(exc, errors="surrogate_then_replace") + if "Invalid command" in msg: + return None + self.module.fail_json(msg=msg) def parse_serialnum(self, data): match = re.search(r"(?:HW|Hardware) S/N:\s+(\S+)", data) if match: return match.group(1) def platform_facts(self): platform_facts = {} resp = get_capabilities(self.module) device_info = resp["device_info"] platform_facts["system"] = device_info["network_os"] for item in ("model", "image", "version", "platform", "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 Config(LegacyFactsBase): COMMANDS = [ "show configuration commands", "show system commit", ] def populate(self): super(Config, self).populate() self.facts["config"] = self.responses commits = self.responses[1] entries = list() entry = None for line in commits.split("\n"): match = re.match(r"(\d+)\s+(.+)by(.+)via(.+)", line) if match: if entry: entries.append(entry) entry = dict( revision=match.group(1), datetime=match.group(2), by=str(match.group(3)).strip(), via=str(match.group(4)).strip(), comment=None, ) else: entry["comment"] = line.strip() self.facts["commits"] = entries class Neighbors(LegacyFactsBase): COMMANDS = [ "show lldp neighbors", "show lldp neighbors detail", ] def populate(self): super(Neighbors, self).populate() all_neighbors = self.responses[0] if "LLDP not configured" not in all_neighbors: neighbors = self.parse(self.responses[1]) self.facts["neighbors"] = self.parse_neighbors(neighbors) def parse(self, data): parsed = list() values = None for line in data.split("\n"): if not line: continue if line[0] == " ": values += "\n%s" % line elif line.startswith("Interface"): if values: parsed.append(values) values = line if values: parsed.append(values) return parsed def parse_neighbors(self, data): facts = dict() for item in data: interface = self.parse_interface(item) host = self.parse_host(item) port = self.parse_port(item) if interface not in facts: facts[interface] = list() facts[interface].append(dict(host=host, port=port)) return facts def parse_interface(self, data): match = re.search(r"^Interface:\s+(\S+),", data) return match.group(1) def parse_host(self, data): match = re.search(r"SysName:\s+(.+)$", data, re.M) if match: return match.group(1) def parse_port(self, data): match = re.search(r"PortDescr:\s+(.+)$", data, re.M) if match: return match.group(1) diff --git a/tests/unit/modules/network/vyos/test_vyos_facts.py b/tests/unit/modules/network/vyos/test_vyos_facts.py index 30e09c0d..8deb01ee 100644 --- a/tests/unit/modules/network/vyos/test_vyos_facts.py +++ b/tests/unit/modules/network/vyos/test_vyos_facts.py @@ -1,173 +1,180 @@ # (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 import json from unittest.mock import patch from ansible.module_utils.connection import ConnectionError from ansible_collections.vyos.vyos.plugins.modules import vyos_facts from ansible_collections.vyos.vyos.tests.unit.modules.utils import set_module_args from .vyos_module import TestVyosModule, load_fixture class TestVyosFactsModule(TestVyosModule): module = vyos_facts def setUp(self): super(TestVyosFactsModule, self).setUp() self.mock_run_commands = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.legacy.base.run_commands", ) self.run_commands = self.mock_run_commands.start() self.mock_get_connection = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.legacy.base.get_connection", ) self.get_connection = self.mock_get_connection.start() self.mock_get_resource_connection = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) self.get_resource_connection = self.mock_get_resource_connection.start() # command outputs a test sets directly, instead of a fixture file self.outputs = {} self.mock_get_capabilities = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.legacy.base.get_capabilities", ) self.get_capabilities = self.mock_get_capabilities.start() self.get_capabilities.return_value = { "device_info": { "network_os": "vyos", "network_os_hostname": "vyos01", "network_os_model": "VMware", "network_os_version": "VyOS 1.1.7", "network_os_major_version": "1.1", }, "network_api": "cliconf", } def tearDown(self): super(TestVyosFactsModule, self).tearDown() self.mock_run_commands.stop() self.mock_get_connection.stop() self.mock_get_capabilities.stop() self.mock_get_resource_connection.stop() def load_fixtures(self, commands=None, filename=None): def load_from_file(*args, **kwargs): module, commands = args output = list() for item in commands: try: obj = json.loads(item) command = obj["command"] except ValueError: command = item if command in self.outputs: if isinstance(self.outputs[command], Exception): raise self.outputs[command] output.append(self.outputs[command]) continue filename = str(command).replace(" ", "_") output.append(load_fixture(filename)) return output self.run_commands.side_effect = load_from_file self.get_connection.return_value.run_commands.side_effect = ( lambda commands, **kwargs: load_from_file(None, commands) ) def test_vyos_facts_default(self): set_module_args(dict(gather_subset="default")) result = self.execute_module() facts = result.get("ansible_facts") self.assertEqual(len(facts), 11) self.assertEqual(facts["ansible_net_hostname"].strip(), "vyos01") self.assertEqual(facts["ansible_net_version"], "VyOS 1.1.7") def test_vyos_facts_not_all(self): set_module_args(dict(gather_subset="!all")) result = self.execute_module() facts = result.get("ansible_facts") self.assertEqual(len(facts), 11) self.assertEqual(facts["ansible_net_hostname"].strip(), "vyos01") self.assertEqual(facts["ansible_net_version"], "VyOS 1.1.7") def test_vyos_facts_exclude_most(self): set_module_args(dict(gather_subset=["!neighbors", "!config"])) result = self.execute_module() facts = result.get("ansible_facts") self.assertEqual(len(facts), 11) self.assertEqual(facts["ansible_net_hostname"].strip(), "vyos01") self.assertEqual(facts["ansible_net_version"], "VyOS 1.1.7") def test_vyos_facts_invalid_subset(self): set_module_args(dict(gather_subset="cereal")) self.execute_module(failed=True) def test_vyos_facts_secure_boot_legacy_bios(self): # real output of a rolling image booted with legacy BIOS (fixture show_secure-boot) set_module_args(dict(gather_subset="default")) facts = self.execute_module()["ansible_facts"] self.assertEqual(facts["ansible_net_secure_boot"], {"enabled": False, "uefi": False}) def test_vyos_facts_secure_boot_uefi_disabled(self): # real output of a rolling image booted with UEFI, Secure Boot off self.outputs = {"show secure-boot": "SecureBoot disabled"} set_module_args(dict(gather_subset="default")) facts = self.execute_module()["ansible_facts"] self.assertEqual(facts["ansible_net_secure_boot"], {"enabled": False, "uefi": True}) def test_vyos_facts_secure_boot_enabled(self): # format of the op-mode script (secure_boot.py); placeholder certificate names self.outputs = { "show secure-boot": "SecureBoot enabled", "show secure-boot detail": "Issuer: CN=VyOS Secure Boot CA\n" "Subject: CN=VyOS Secure Boot Signer", } set_module_args(dict(gather_subset="default")) facts = self.execute_module()["ansible_facts"] self.assertEqual( facts["ansible_net_secure_boot"], { "enabled": True, "uefi": True, "certificates": [ { "issuer": "CN=VyOS Secure Boot CA", "subject": "CN=VyOS Secure Boot Signer", }, ], }, ) def test_vyos_facts_secure_boot_not_supported(self): # images without the command (1.5.1 and older): no fact, and no failure self.outputs = {"show secure-boot": ConnectionError("Invalid command: show [secure-boot]")} set_module_args(dict(gather_subset="default")) facts = self.execute_module()["ansible_facts"] self.assertNotIn("ansible_net_secure_boot", facts) self.assertEqual(len(facts), 10) + + def test_vyos_facts_secure_boot_connection_error(self): + # a connection problem is not "command not supported": the module fails + self.outputs = {"show secure-boot": ConnectionError("timeout value 30 seconds reached")} + set_module_args(dict(gather_subset="default")) + result = self.execute_module(failed=True) + self.assertIn("timeout value 30 seconds reached", result["msg"])