Debian Codegraph @

ansible_collections/community/routeros/plugins/module_utils/routeros.py

raw
1 # Copyright (c) 2016 Red Hat Inc.
2 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
3 # SPDX-License-Identifier: BSD-2-Clause
4
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8 import json
9 from ansible.module_utils.common.text.converters import to_native
10 from ansible.module_utils.basic import env_fallback
11 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list, ComplexList
12 from ansible_collections.community.routeros.plugins.module_utils.version import LooseVersion
13 from ansible.module_utils.connection import Connection, ConnectionError
14
15 _DEVICE_CONFIGS = {}
16
17 routeros_provider_spec = {
18 'host': dict(),
19 'port': dict(type='int'),
20 'username': dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])),
21 'password': dict(fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD']), no_log=True),
22 'ssh_keyfile': dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'),
23 'timeout': dict(type='int')
24 }
25 routeros_argument_spec = {}
26
27
28 def get_provider_argspec():
29 return routeros_provider_spec
30
31
32 def get_connection(module):
33 if hasattr(module, '_routeros_connection'):
34 return module._routeros_connection
35
36 capabilities = get_capabilities(module)
37 network_api = capabilities.get('network_api')
38 if network_api == 'cliconf':
39 module._routeros_connection = Connection(module._socket_path)
40 else:
41 module.fail_json(msg='Invalid connection type %s' % network_api)
42
43 return module._routeros_connection
44
45
46 def get_capabilities(module):
47 if hasattr(module, '_routeros_capabilities'):
48 return module._routeros_capabilities
49
50 try:
51 capabilities = Connection(module._socket_path).get_capabilities()
52 module._routeros_capabilities = json.loads(capabilities)
53 return module._routeros_capabilities
54 except ConnectionError as exc:
55 module.fail_json(msg=to_native(exc, errors='surrogate_then_replace'))
56
57
58 def get_defaults_flag(module):
59 connection = get_connection(module)
60
61 try:
62 out = connection.get('/system default-configuration print')
63 except ConnectionError as exc:
64 module.fail_json(msg=to_native(exc, errors='surrogate_then_replace'))
65
66 out = to_native(out, errors='surrogate_then_replace')
67
68 commands = set()
69 for line in out.splitlines():
70 if line.strip():
71 commands.add(line.strip().split()[0])
72
73 if 'all' in commands:
74 return ['all']
75 else:
76 return ['full']
77
78
79 def get_config(module, flags=None):
80 flag_str = ' '.join(to_list(flags))
81
82 try:
83 return _DEVICE_CONFIGS[flag_str]
84 except KeyError:
85 connection = get_connection(module)
86
87 try:
88 out = connection.get_config(flags=flags)
89 except ConnectionError as exc:
90 module.fail_json(msg=to_native(exc, errors='surrogate_then_replace'))
91
92 cfg = to_native(out, errors='surrogate_then_replace').strip()
93 _DEVICE_CONFIGS[flag_str] = cfg
94 return cfg
95
96
97 def to_commands(module, commands):
98 spec = {
99 'command': dict(key=True),
100 'prompt': dict(),
101 'answer': dict()
102 }
103 transform = ComplexList(spec, module)
104 return transform(commands)
105
106
107 def should_add_leading_space(module):
108 """Determines whether adding a leading space to the command is needed
109 to workaround prompt bug in 6.49 <= ROS < 7.2"""
110 capabilities = get_capabilities(module)
111 network_os_version = capabilities.get('device_info', {}).get('network_os_version')
112 if network_os_version is None:
113 return False
114 return LooseVersion('6.49') <= LooseVersion(network_os_version) < LooseVersion('7.2')
115
116
117 def run_commands(module, commands, check_rc=True):
118 responses = list()
119 connection = get_connection(module)
120
121 for cmd in to_list(commands):
122 if isinstance(cmd, dict):
123 command = cmd['command']
124 prompt = cmd['prompt']
125 answer = cmd['answer']
126 else:
127 command = cmd
128 prompt = None
129 answer = None
130
131 if should_add_leading_space(module):
132 command = " " + command
133
134 try:
135 out = connection.get(command, prompt, answer)
136 except ConnectionError as exc:
137 module.fail_json(msg=to_native(exc, errors='surrogate_then_replace'))
138
139 try:
140 out = to_native(out, errors='surrogate_or_strict')
141 except UnicodeError:
142 module.fail_json(
143 msg=u'Failed to decode output from %s: %s' % (cmd, to_native(out)))
144
145 responses.append(out)
146
147 return responses
148
149
150 def load_config(module, commands):
151 connection = get_connection(module)
152
153 out = connection.edit_config(commands)