Debian Codegraph @

ansible_collections/cisco/nxos/plugins/cliconf/nxos.py

raw
1 #
2 # (c) 2017 Red Hat Inc.
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18 #
19 from __future__ import absolute_import, division, print_function
20
21
22 __metaclass__ = type
23
24 DOCUMENTATION = """
25 author: Ansible Networking Team (@ansible-network)
26 name: nxos
27 short_description: Use NX-OS cliconf to run commands on Cisco NX-OS platform
28 description:
29 - This nxos plugin provides low level abstraction apis for sending and receiving CLI
30 commands from Cisco NX-OS network devices.
31 version_added: 1.0.0
32 options:
33 config_commands:
34 description:
35 - Specifies a list of commands that can make configuration changes
36 to the target device.
37 - When `ansible_network_single_user_mode` is enabled, if a command sent
38 to the device is present in this list, the existing cache is invalidated.
39 version_added: 2.0.0
40 type: list
41 elements: str
42 default: []
43 vars:
44 - name: ansible_nxos_config_commands
45 """
46
47 import json
48 import re
49
50 from ansible.errors import AnsibleConnectionFailure
51 from ansible.module_utils._text import to_bytes, to_text
52 from ansible.module_utils.common._collections_compat import Mapping
53 from ansible.module_utils.connection import ConnectionError
54 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import (
55 NetworkConfig,
56 dumps,
57 )
58 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list
59 from ansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_base import CliconfBase
60
61
62 class Cliconf(CliconfBase):
63 def __init__(self, *args, **kwargs):
64 self._module_context = {}
65 self._device_info = {}
66 super(Cliconf, self).__init__(*args, **kwargs)
67
68 def read_module_context(self, module_key):
69 if self._module_context.get(module_key):
70 return self._module_context[module_key]
71
72 return None
73
74 def save_module_context(self, module_key, module_context):
75 self._module_context[module_key] = module_context
76
77 return None
78
79 def get_device_info(self):
80 if not self._device_info:
81 device_info = {}
82
83 device_info["network_os"] = "nxos"
84 reply = self.get("show version")
85 platform_reply = self.get("show inventory")
86
87 match_sys_ver = re.search(r"\s+system:\s+version\s*(\S+)", reply, re.M)
88 if match_sys_ver:
89 device_info["network_os_version"] = match_sys_ver.group(1)
90 else:
91 match_kick_ver = re.search(r"\s+kickstart:\s+version\s*(\S+)", reply, re.M)
92 if match_kick_ver:
93 device_info["network_os_version"] = match_kick_ver.group(1)
94
95 if "network_os_version" not in device_info:
96 match_sys_ver = re.search(r"\s+NXOS:\s+version\s*(\S+)", reply, re.M)
97 if match_sys_ver:
98 device_info["network_os_version"] = match_sys_ver.group(1)
99
100 match_chassis_id = re.search(r"Hardware\n\s+cisco(.+)$", reply, re.M)
101 if match_chassis_id:
102 device_info["network_os_model"] = match_chassis_id.group(1).strip()
103
104 match_host_name = re.search(r"\s+Device name:\s*(\S+)", reply, re.M)
105 if match_host_name:
106 device_info["network_os_hostname"] = match_host_name.group(1)
107
108 match_isan_file_name = re.search(r"\s+system image file is:\s*(\S+)", reply, re.M)
109 if match_isan_file_name:
110 device_info["network_os_image"] = match_isan_file_name.group(1)
111 else:
112 match_kick_file_name = re.search(
113 r"\s+kickstart image file is:\s*(\S+)",
114 reply,
115 re.M,
116 )
117 if match_kick_file_name:
118 device_info["network_os_image"] = match_kick_file_name.group(1)
119
120 if "network_os_image" not in device_info:
121 match_isan_file_name = re.search(r"\s+NXOS image file is:\s*(\S+)", reply, re.M)
122 if match_isan_file_name:
123 device_info["network_os_image"] = match_isan_file_name.group(1)
124
125 match_os_platform = re.search(
126 r'NAME: "Chassis",\s*DESCR:.*\nPID:\s*(\S+)',
127 platform_reply,
128 re.M,
129 )
130 if match_os_platform:
131 device_info["network_os_platform"] = match_os_platform.group(1)
132
133 self._device_info = device_info
134
135 return self._device_info
136
137 def restore(self, filename=None, path=""):
138 if not filename:
139 raise ValueError("'file_name' value is required for restore")
140 cmd = f"configure replace {path}{filename} best-effort"
141 return self.send_command(cmd)
142
143 def get_diff(
144 self,
145 candidate=None,
146 running=None,
147 diff_match="line",
148 diff_ignore_lines=None,
149 path=None,
150 diff_replace="line",
151 ):
152 diff = {}
153 device_operations = self.get_device_operations()
154 option_values = self.get_option_values()
155
156 if candidate is None and device_operations["supports_generate_diff"]:
157 raise ValueError("candidate configuration is required to generate diff")
158
159 if diff_match not in option_values["diff_match"]:
160 raise ValueError(
161 "'match' value %s in invalid, valid values are %s"
162 % (diff_match, ", ".join(option_values["diff_match"])),
163 )
164
165 if diff_replace not in option_values["diff_replace"]:
166 raise ValueError(
167 "'replace' value %s in invalid, valid values are %s"
168 % (diff_replace, ", ".join(option_values["diff_replace"])),
169 )
170
171 # prepare candidate configuration
172 candidate_obj = NetworkConfig(indent=2)
173 candidate_obj.load(candidate)
174
175 if running and diff_match != "none" and diff_replace != "config":
176 # running configuration
177 running_obj = NetworkConfig(indent=2, contents=running, ignore_lines=diff_ignore_lines)
178 configdiffobjs = candidate_obj.difference(
179 running_obj,
180 path=path,
181 match=diff_match,
182 replace=diff_replace,
183 )
184
185 else:
186 configdiffobjs = candidate_obj.items
187
188 diff["config_diff"] = dumps(configdiffobjs, "commands") if configdiffobjs else ""
189 return diff
190
191 def get_config(self, source="running", flags=None, format="text"):
192 options_values = self.get_option_values()
193 if format not in options_values["format"]:
194 raise ValueError(
195 "'format' value %s is invalid. Valid values are %s"
196 % (format, ",".join(options_values["format"])),
197 )
198
199 lookup = {"running": "running-config", "startup": "startup-config"}
200 if source not in lookup:
201 raise ValueError("fetching configuration from %s is not supported" % source)
202
203 cmd = "show {0} ".format(lookup[source])
204 if format and format != "text":
205 cmd += "| %s " % format
206
207 if flags:
208 cmd += " ".join(to_list(flags))
209 cmd = cmd.strip()
210
211 return self.send_command(cmd)
212
213 def edit_config(
214 self,
215 candidate=None,
216 commit=True,
217 replace=None,
218 diff=False,
219 comment=None,
220 err_responses=None,
221 ):
222 if diff:
223 self._connection.queue_message(
224 "warning",
225 message="setting `diff=True` in edit_config() no effect for platform cisco.nxos",
226 )
227
228 resp = {}
229 operations = self.get_device_operations()
230 self.check_edit_config_capability(
231 operations,
232 candidate,
233 commit,
234 replace,
235 comment,
236 )
237 results = []
238 requests = []
239
240 if err_responses:
241 # update platform default stderr regexes to include modules specific ones
242 err_responses = [re.compile(to_bytes(err_re)) for err_re in err_responses]
243 current_stderr_re = self._connection._get_terminal_std_re(
244 "terminal_stderr_re",
245 )
246 current_stderr_re.extend(err_responses)
247
248 if replace:
249 # not all NX-OS versions support `config replace`
250 # we let the device throw the invalid command error
251 candidate = f"config replace {replace}"
252
253 try:
254 if commit:
255 self.send_command("configure terminal")
256
257 for line in to_list(candidate):
258 if not isinstance(line, Mapping):
259 line = {"command": line}
260
261 cmd = line["command"]
262 if cmd != "end":
263 results.append(self.send_command(**line))
264 requests.append(cmd)
265
266 self.send_command("end")
267 else:
268 raise ValueError("check mode is not supported")
269
270 resp["request"] = requests
271 resp["response"] = results
272 return resp
273
274 finally:
275 # always reset terminal regexes to platform default
276 if err_responses:
277 for x in err_responses:
278 current_stderr_re.remove(x)
279
280 def get(
281 self,
282 command,
283 prompt=None,
284 answer=None,
285 sendonly=False,
286 newline=True,
287 output=None,
288 check_all=False,
289 ):
290 if output:
291 command = self._get_command_with_output(command, output)
292 return self.send_command(
293 command=command,
294 prompt=prompt,
295 answer=answer,
296 sendonly=sendonly,
297 newline=newline,
298 check_all=check_all,
299 )
300
301 def run_commands(self, commands=None, check_rc=True):
302 if commands is None:
303 raise ValueError("'commands' value is required")
304
305 responses = list()
306 for cmd in to_list(commands):
307 if not isinstance(cmd, Mapping):
308 cmd = {"command": cmd}
309
310 output = cmd.pop("output", None)
311 if output:
312 cmd["command"] = self._get_command_with_output(cmd["command"], output)
313
314 try:
315 out = self.send_command(**cmd)
316 except AnsibleConnectionFailure as e:
317 if check_rc is True:
318 raise
319 out = getattr(e, "err", e)
320
321 if out is not None:
322 try:
323 out = to_text(out, errors="surrogate_or_strict").strip()
324 except UnicodeError:
325 raise ConnectionError(
326 message="Failed to decode output from %s: %s" % (cmd, to_text(out)),
327 )
328
329 try:
330 out = json.loads(out)
331 except ValueError:
332 pass
333
334 responses.append(out)
335 return responses
336
337 def get_device_operations(self):
338 return {
339 "supports_diff_replace": True,
340 "supports_commit": False,
341 "supports_rollback": False,
342 "supports_defaults": True,
343 "supports_onbox_diff": False,
344 "supports_commit_comment": False,
345 "supports_multiline_delimiter": False,
346 "supports_diff_match": True,
347 "supports_diff_ignore_lines": True,
348 "supports_generate_diff": True,
349 "supports_replace": True,
350 }
351
352 def get_option_values(self):
353 return {
354 "format": ["text", "json"],
355 "diff_match": ["line", "strict", "exact", "none"],
356 "diff_replace": ["line", "block", "config"],
357 "output": ["text", "json", "json-pretty"],
358 }
359
360 def get_capabilities(self):
361 result = super(Cliconf, self).get_capabilities()
362 result["rpc"] += ["get_diff", "run_commands"]
363 result["device_operations"] = self.get_device_operations()
364 result.update(self.get_option_values())
365
366 return json.dumps(result)
367
368 def pull_file(self, command, remotepassword=None):
369 possible_errors_re = [
370 re.compile(rb"timed out"),
371 re.compile(rb"(?i)No space.*#"),
372 re.compile(rb"(?i)Permission denied.*#"),
373 re.compile(rb"(?i)No such file.*#"),
374 re.compile(rb"Compaction is not supported on this platform.*#"),
375 re.compile(rb"Compact of.*failed.*#"),
376 re.compile(rb"(?i)Could not resolve hostname"),
377 re.compile(rb"(?i)Too many authentication failures"),
378 re.compile(rb"Access Denied"),
379 re.compile(rb"(?i)Copying to\/from this server name is not permitted"),
380 re.compile(rb"Could not resolve hostname"),
381 ]
382
383 # set error regex for copy command
384 current_stderr_re = self._connection._get_terminal_std_re("terminal_stderr_re")
385 current_stderr_re.extend(possible_errors_re)
386
387 # do not change the ordering of this list
388 possible_prompts_re = [
389 re.compile(rb"file existing with this name"),
390 re.compile(rb"sure you want to continue connecting"),
391 re.compile(rb"(?i)Password:.*"),
392 ]
393
394 # set stdout regex for copy command to handle optional user prompts
395 # based on different match conditions
396 current_stdout_re = self._connection._get_terminal_std_re("terminal_stdout_re")
397 current_stdout_re.extend(possible_prompts_re)
398
399 retry = 1
400 file_pulled = False
401
402 try:
403 while not file_pulled and retry <= 6:
404 retry += 1
405 output = self.send_command(command=command, strip_prompt=False)
406
407 if possible_prompts_re[0].search(to_bytes(output)):
408 output = self.send_command(command="y", strip_prompt=False)
409
410 if possible_prompts_re[1].search(to_bytes(output)):
411 output = self.send_command(command="yes", strip_prompt=False)
412
413 if possible_prompts_re[2].search(to_bytes(output)):
414 output = self.send_command(command=remotepassword, strip_prompt=False)
415 if "Copy complete" in output:
416 file_pulled = True
417 return file_pulled
418 finally:
419 # always reset terminal regexes to default
420 for x in possible_prompts_re:
421 current_stdout_re.remove(x)
422 for x in possible_errors_re:
423 current_stderr_re.remove(x)
424
425 def set_cli_prompt_context(self):
426 """
427 Make sure we are in the operational cli context
428 :return: None
429 """
430 if self._connection.connected:
431 out = self._connection.get_prompt()
432 if out is None:
433 raise AnsibleConnectionFailure(
434 message="cli prompt is not identified from the last received"
435 " response window: %s" % self._connection._last_recv_window,
436 )
437 # Match prompts ending in )# except those with (maint-mode)#
438 config_prompt = re.compile(r"^.*\((?!maint-mode).*\)#$")
439
440 while config_prompt.match(to_text(out, errors="surrogate_then_replace").strip()):
441 self._connection.queue_message("vvvv", "wrong context, sending exit to device")
442 self._connection.send_command("exit")
443 out = self._connection.get_prompt()
444
445 def _get_command_with_output(self, command, output):
446 output_re = r".+\|\s*json(?:-pretty)?$"
447 options_values = self.get_option_values()
448 if output not in options_values["output"]:
449 raise ValueError(
450 "'output' value %s is invalid. Valid values are %s"
451 % (output, ",".join(options_values["output"])),
452 )
453
454 if output in ["json", "json-pretty"] and not re.search(output_re, command):
455 device_info = self.get_device_info()
456 model = device_info.get("network_os_model", "")
457 platform = device_info.get("network_os_platform", "")
458 if platform.startswith("DS-") and "MDS" in model:
459 cmd = "%s | json native" % command
460 else:
461 cmd = "%s | %s" % (command, output)
462 elif output == "text" and re.search(output_re, command):
463 cmd = command.rsplit("|", 1)[0]
464 else:
465 cmd = command
466 return cmd