Debian Codegraph @

ansible_collections/community/ciscosmb/plugins/module_utils/ciscosmb.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # (c) 2016 Red Hat Inc.
8 #
9 # Redistribution and use in source and binary forms, with or without modification,
10 # are permitted provided that the following conditions are met:
11 #
12 # * Redistributions of source code must retain the above copyright
13 # notice, this list of conditions and the following disclaimer.
14 # * Redistributions in binary form must reproduce the above copyright notice,
15 # this list of conditions and the following disclaimer in the documentation
16 # and/or other materials provided with the distribution.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
26 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #
28
29 from __future__ import absolute_import, division, print_function
30 __metaclass__ = type
31
32 import json
33 import re
34
35 from ansible.module_utils._text import to_text, to_native
36 from ansible.module_utils.basic import env_fallback
37 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list, ComplexList
38 from ansible.module_utils.connection import Connection, ConnectionError
39
40 # copy of https://github.com/napalm-automation/napalm/blob/develop/napalm/base/canonical_map.py
41 from ansible_collections.community.ciscosmb.plugins.module_utils.ciscosmb_canonical_map import base_interfaces
42
43 _DEVICE_CONFIGS = {}
44
45 ciscosmb_provider_spec = {
46 'host': dict(),
47 'port': dict(type='int'),
48 'username': dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])),
49 'password': dict(fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD']), no_log=True),
50 'ssh_keyfile': dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'),
51 'timeout': dict(type='int')
52 }
53 ciscosmb_argument_spec = {}
54
55
56 def ciscosmb_split_to_tables(data):
57 TABLE_HEADER = re.compile(r"^---+ +-+.*$")
58 EMPTY_LINE = re.compile(r"^ *$")
59
60 tables = dict()
61 tableno = -1
62 lineno = 0
63 tabledataget = False
64
65 for line in data.splitlines():
66 if re.match(EMPTY_LINE, line):
67 tabledataget = False
68 continue
69
70 if re.match(TABLE_HEADER, line):
71 tableno += 1
72 tabledataget = True
73 lineno = 0
74 tables[tableno] = dict()
75 tables[tableno]["header"] = line
76 tables[tableno]["data"] = dict()
77 continue
78
79 if tabledataget:
80 tables[tableno]["data"][lineno] = line
81 lineno += 1
82 continue
83
84 return tables
85
86
87 def ciscosmb_parse_table(table, allow_overflow=True, allow_empty_fields=None):
88
89 if allow_empty_fields is None:
90 allow_empty_fields = list()
91
92 fields_end = __get_table_columns_end(table["header"])
93 data = __get_table_data(
94 table["data"], fields_end, allow_overflow, allow_empty_fields
95 )
96
97 return data
98
99
100 def __get_table_columns_end(headerline):
101 """ fields length are diferent device to device, detect them on horizontal lin """
102 fields_end = [m.start() for m in re.finditer(" *", headerline.strip())]
103 # fields_position.insert(0,0)
104 # fields_end.append(len(headerline))
105 fields_end.append(10000) # allow "long" last field
106
107 return fields_end
108
109
110 def __line_to_fields(line, fields_end):
111 """ dynamic fields lenghts """
112 line_elems = {}
113 index = 0
114 f_start = 0
115 for f_end in fields_end:
116 line_elems[index] = line[f_start:f_end].strip()
117 index += 1
118 f_start = f_end
119
120 return line_elems
121
122
123 def __get_table_data(
124 tabledata, fields_end, allow_overflow=True, allow_empty_fields=None
125 ):
126
127 if allow_empty_fields is None:
128 allow_empty_fields = list()
129 data = dict()
130
131 dataindex = 0
132 for lineno in tabledata:
133 owerflownfields = list()
134 owerflow = False
135
136 line = tabledata[lineno]
137 line_elems = __line_to_fields(line, fields_end)
138
139 if allow_overflow:
140 # search for overflown fields
141 for elemno in line_elems:
142 if elemno not in allow_empty_fields and line_elems[elemno] == "":
143 owerflow = True
144 else:
145 owerflownfields.append(elemno)
146
147 if owerflow:
148 # concat owerflown elements to previous data
149 for fieldno in owerflownfields:
150 data[dataindex - 1][fieldno] += line_elems[fieldno]
151
152 else:
153 data[dataindex] = line_elems
154 dataindex += 1
155 else:
156 data[dataindex] = line_elems
157 dataindex += 1
158
159 return data
160
161
162 def ciscosmb_merge_dicts(a, b, path=None):
163 "merges b into a"
164 if path is None:
165 path = []
166
167 # is b empty?
168 if not bool(b):
169 return a
170
171 for key in b:
172 if key in a:
173 if isinstance(a[key], dict) and isinstance(b[key], dict):
174 ciscosmb_merge_dicts(a[key], b[key], path + [str(key)])
175 elif a[key] == b[key]:
176 pass # same leaf value
177 else:
178 raise Exception("Conflict at %s" % ".".join(path + [str(key)]))
179 else:
180 a[key] = b[key]
181 return a
182
183
184 def interface_canonical_name(interface):
185 iftype = interface.rstrip(r"/\0123456789. ")
186 ifno = interface[len(iftype):].lstrip()
187
188 if iftype in base_interfaces:
189 iftype = base_interfaces[iftype]
190
191 interface = iftype + str(ifno)
192
193 return interface
194
195
196 def get_provider_argspec():
197 return ciscosmb_provider_spec
198
199
200 def get_connection(module):
201 if hasattr(module, '_ciscosmb_connection'):
202 return module._ciscosmb_connection
203
204 capabilities = get_capabilities(module)
205 network_api = capabilities.get('network_api')
206 if network_api == 'cliconf':
207 module._ciscosmb_connection = Connection(module._socket_path)
208 else:
209 module.fail_json(msg='Invalid connection type %s' % network_api)
210
211 return module._ciscosmb_connection
212
213
214 def get_capabilities(module):
215 if hasattr(module, '_ciscosmb_capabilities'):
216 return module._ciscosmb_capabilities
217
218 try:
219 capabilities = Connection(module._socket_path).get_capabilities()
220 module._ciscosmb_capabilities = json.loads(capabilities)
221 return module._ciscosmb_capabilities
222 except ConnectionError as exc:
223 module.fail_json(msg=to_native(exc, errors='surrogate_then_replace'))
224
225
226 def get_defaults_flag(module):
227 connection = get_connection(module)
228
229 try:
230 out = connection.get('/system default-configuration print')
231 except ConnectionError as exc:
232 module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
233
234 out = to_text(out, errors='surrogate_then_replace')
235
236 commands = set()
237 for line in out.splitlines():
238 if line.strip():
239 commands.add(line.strip().split()[0])
240
241 if 'all' in commands:
242 return ['all']
243 else:
244 return ['full']
245
246
247 def get_config(module, flags=None):
248 flag_str = ' '.join(to_list(flags))
249
250 try:
251 return _DEVICE_CONFIGS[flag_str]
252 except KeyError:
253 connection = get_connection(module)
254
255 try:
256 out = connection.get_config(flags=flags)
257 except ConnectionError as exc:
258 module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
259
260 cfg = to_text(out, errors='surrogate_then_replace').strip()
261 _DEVICE_CONFIGS[flag_str] = cfg
262 return cfg
263
264
265 def to_commands(module, commands):
266 spec = {
267 'command': dict(key=True),
268 'prompt': dict(),
269 'answer': dict()
270 }
271 transform = ComplexList(spec, module)
272 return transform(commands)
273
274
275 def run_commands(module, commands, check_rc=True):
276 responses = list()
277 connection = get_connection(module)
278
279 for cmd in to_list(commands):
280 if isinstance(cmd, dict):
281 command = cmd['command']
282 prompt = cmd['prompt']
283 answer = cmd['answer']
284 else:
285 command = cmd
286 prompt = None
287 answer = None
288
289 try:
290 out = connection.get(command, prompt, answer)
291 except ConnectionError as exc:
292 module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
293
294 try:
295 out = to_text(out, errors='surrogate_or_strict')
296 except UnicodeError:
297 module.fail_json(
298 msg=u'Failed to decode output from %s: %s' % (cmd, to_text(out)))
299
300 responses.append(out)
301
302 return responses