Debian Codegraph @

ansible_collections/cisco/iosxr/plugins/cliconf/iosxr.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: iosxr
27 short_description: Use iosxr cliconf to run command on Cisco IOS XR platform
28 description:
29 - This iosxr plugin provides low level abstraction apis for sending and receiving
30 CLI commands from Cisco IOS XR network devices.
31 version_added: 1.0.0
32 notes:
33 - IOSXR commit confirmed command varies with IOSXR version releases,
34 commit_comment and commit_label may or may not
35 be valid together as per the device version.
36 options:
37 commit_confirmed:
38 type: boolean
39 default: false
40 description:
41 - enable or disable commit confirmed mode
42 env:
43 - name: ANSIBLE_IOSXR_COMMIT_CONFIRMED
44 vars:
45 - name: ansible_iosxr_commit_confirmed
46 commit_confirmed_timeout:
47 type: int
48 description:
49 - Commits the configuration on a trial basis for the time specified in seconds or minutes.
50 env:
51 - name: ANSIBLE_IOSXR_COMMIT_CONFIRMED_TIMEOUT
52 vars:
53 - name: ansible_iosxr_commit_confirmed_timeout
54 commit_label:
55 type: str
56 description:
57 - Adds label to commit confirmed.
58 env:
59 - name: ANSIBLE_IOSXR_COMMIT_LABEL
60 vars:
61 - name: ansible_iosxr_commit_label
62 commit_comment:
63 type: str
64 description:
65 - Adds comment to commit confirmed..
66 env:
67 - name: ANSIBLE_IOSXR_COMMIT_COMMENT
68 vars:
69 - name: ansible_iosxr_commit_comment
70 config_commands:
71 description:
72 - Specifies a list of commands that can make configuration changes
73 to the target device.
74 - When `ansible_network_single_user_mode` is enabled, if a command sent
75 to the device is present in this list, the existing cache is invalidated.
76 version_added: 2.0.0
77 type: list
78 elements: str
79 default: []
80 vars:
81 - name: ansible_iosxr_config_commands
82 config_mode_exclusive:
83 type: boolean
84 default: false
85 description:
86 - enable or disable config mode exclusive
87 env:
88 - name: ANSIBLE_IOSXR_CONFIG_MODE_EXCLUSIVE
89 vars:
90 - name: ansible_iosxr_config_mode_exclusive
91 """
92
93 EXAMPLES = """
94 # Use commit confirmed within a task with timeout, label and comment
95
96 - name: Commit confirmed with a task
97 vars:
98 ansible_iosxr_commit_confirmed: True
99 ansible_iosxr_commit_confirmed_timeout: 50
100 ansible_iosxr_commit_label: TestLabel
101 ansible_iosxr_commit_comment: I am a test comment
102 cisco.iosxr.iosxr_logging_global:
103 state: merged
104 config:
105 buffered:
106 severity: errors #alerts #informational
107 correlator:
108 buffer_size: 2024
109
110 # Commands (cliconf specific)
111 # ["commit confirmed 50 label TestLabel comment I am a test comment"]
112
113 # Use commit within a task with label
114
115 - name: Commit label with a task
116 vars:
117 ansible_iosxr_commit_label: lblTest
118 cisco.iosxr.iosxr_hostname:
119 state: merged
120 config:
121 hostname: R1
122
123 # Commands (cliconf specific)
124 # ["commit label lblt1"]
125
126 # Use commit confirm with timeout and confirm the commit
127
128 # NOTE - IOSXR waits for a `commit` when the command
129 # executed is `commit confirmed <timeout>` within the timeout
130 # period for the config to commit successfully, else a rollback
131 # happens.
132
133 - name: Example commit confirmed
134 vars:
135 ansible_iosxr_commit_confirmed: True
136 ansible_iosxr_commit_confirmed_timeout: 60
137 tasks:
138 - name: "Commit confirmed with timeout"
139 cisco.iosxr.iosxr_hostname:
140 state: merged
141 config:
142 hostname: R1
143
144 - name: "Confirm the Commit"
145 cisco.iosxr.iosxr_command:
146 commands:
147 - commit
148
149 # Commands (cliconf specific)
150 # ["commit confirmed 60"]
151
152 # Use exclusive mode with a task
153
154 - name: Configure exclusive mode with a task
155 vars:
156 ansible_iosxr_config_mode_exclusive: True
157 cisco.iosxr.iosxr_interfaces:
158 state: merged
159 config:
160 - name: GigabitEthernet0/0/0/2
161 description: Configured via Ansible
162 - name: GigabitEthernet0/0/0/3
163 description: Configured via Ansible
164
165 # Commands (cliconf specific)
166 # ["configure exclusive"]
167
168 # Use Replace option with commit confirmed
169
170 # NOTE - IOSXR waits for a `commit` when the command
171 # executed is `commit replace confirmed <timeout>` within the timeout
172 # period for the config to commit successfully, else a rollback
173 # happens.
174 # This option is supported by only iosxr_config module
175
176 - name: Example replace config with commit confirmed
177 vars:
178 ansible_iosxr_commit_confirmed: True
179 ansible_iosxr_commit_confirmed_timeout: 60
180 tasks:
181 - name: "Replace config with Commit confirmed"
182 cisco.iosxr.iosxr_config:
183 src: 'replace_running_cfg_iosxr.txt'
184 replace: config
185
186 - name: "Confirm the Commit"
187 cisco.iosxr.iosxr_command:
188 commands:
189 - commit
190 """
191
192 import json
193 import re
194
195 from ansible.errors import AnsibleConnectionFailure
196 from ansible.module_utils._text import to_text
197 from ansible.module_utils.common._collections_compat import Mapping
198 from ansible.module_utils.connection import ConnectionError
199 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import (
200 NetworkConfig,
201 dumps,
202 )
203 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list
204 from ansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_base import CliconfBase
205
206 from ansible_collections.cisco.iosxr.plugins.module_utils.network.iosxr.iosxr import (
207 mask_config_blocks_from_diff,
208 sanitize_config,
209 )
210
211
212 class Cliconf(CliconfBase):
213 def __init__(self, *args, **kwargs):
214 self._device_info = {}
215 super(Cliconf, self).__init__(*args, **kwargs)
216
217 def get_command_output(self, command):
218 reply = self.get(command)
219 data = to_text(reply, errors="surrogate_or_strict").strip()
220 return data
221
222 def get_device_info(self):
223 if not self._device_info:
224 device_info = dict()
225 device_info["network_os"] = "iosxr"
226 data = self.get_command_output("show version | utility head -n 20")
227 match = re.search(r"Version (\S+)$", data, re.M)
228 if match:
229 device_info["network_os_version"] = match.group(1)
230 else:
231 match = re.search(r"Version (\S+ \S+)$", data, re.M)
232 if match:
233 device_info["network_os_version"] = match.group(1)
234
235 match = re.search(r'image file is "(.+)"', data)
236 if match:
237 device_info["network_os_image"] = match.group(1)
238
239 model_search_strs = [
240 r"^[Cc]isco (.+) \(\) processor",
241 r"^[Cc]isco ([A-Z0-9\-]+) processor",
242 r"^[Cc]isco (.+) \(revision",
243 r"^[Cc]isco (\S+ \S+).+bytes of .*memory",
244 ]
245 for item in model_search_strs:
246 match = re.search(item, data, re.M)
247 if match:
248 device_info["network_os_model"] = match.group(1)
249 break
250
251 try:
252 data = self.get_command_output("show inventory")
253 except AnsibleConnectionFailure:
254 data = ""
255
256 if "network_os_model" not in device_info:
257 match = re.search(r"DESCR: \"[Cc]isco (\S+ \S+)", data, re.M)
258 if match:
259 device_info["network_os_model"] = match.group(1)
260
261 match = re.search(r"SN: (\S+)\n\nNAME:", data, re.M)
262 if match:
263 device_info["network_os_serialnum"] = match.group(1)
264
265 hostname = self.get_command_output("show running-config hostname")
266 match = re.search(r"hostname\s(\S+)$", hostname, re.M)
267 if match:
268 device_info["network_os_hostname"] = match.group(1)
269
270 self._device_info = device_info
271
272 return self._device_info
273
274 def configure(self, admin=False, exclusive=False):
275 prompt = to_text(self._connection.get_prompt(), errors="surrogate_or_strict").strip()
276 if not prompt.endswith(")#"):
277 if admin and "admin-" not in prompt:
278 self.send_command("admin")
279 if exclusive or self.get_option("config_mode_exclusive"):
280 self.send_command("configure exclusive")
281 return
282 self.send_command("configure terminal")
283
284 def abort(self, admin=False):
285 prompt = to_text(self._connection.get_prompt(), errors="surrogate_or_strict").strip()
286 if prompt.endswith(")#"):
287 self.send_command("abort")
288 if admin and "admin-" in prompt:
289 self.send_command("exit")
290
291 def get_config(self, source="running", flags=None, format="text"):
292 if source not in ["running"]:
293 raise ValueError("fetching configuration from %s is not supported" % source)
294
295 lookup = {"running": "running-config"}
296
297 cmd = "show {0} ".format(lookup[source])
298 cmd += " ".join(to_list(flags))
299 cmd = cmd.strip()
300
301 return self.send_command(cmd)
302
303 def edit_config(
304 self,
305 candidate=None,
306 commit=True,
307 replace=None,
308 diff=False,
309 comment=None,
310 admin=False,
311 exclusive=False,
312 label=None,
313 ):
314 operations = self.get_device_operations()
315 self.check_edit_config_capability(operations, candidate, commit, replace, comment)
316
317 resp = {}
318 results = []
319 requests = []
320
321 self.configure(admin=admin, exclusive=exclusive)
322
323 if replace:
324 candidate = "load {0}".format(replace)
325
326 for line in to_list(candidate):
327 if not isinstance(line, Mapping):
328 line = {"command": line}
329 cmd = line["command"]
330 results.append(self.send_command(**line))
331 requests.append(cmd)
332
333 # Before any commit happened, we can get a real configuration
334 # diff from the device and make it available by the iosxr_config module.
335 # This information can be useful either in check mode or normal mode.
336 resp["show_commit_config_diff"] = self.get("show commit changes diff")
337
338 if commit:
339 try:
340 self.commit(comment=comment, label=label, replace=replace)
341 except AnsibleConnectionFailure as exc:
342 error_msg = to_text(exc, errors="surrogate_or_strict").strip()
343 if "Invalid input detected" in error_msg and "comment" in error_msg:
344 msg = (
345 "value of comment option '%s' is ignored as it in not supported by IOSXR"
346 % comment
347 )
348 self._connection.queue_message("warning", msg)
349 comment = None
350 self.commit(comment=comment, label=label, replace=replace)
351 else:
352 raise ConnectionError(error_msg)
353
354 else:
355 self.discard_changes()
356
357 if not self.get_option("commit_confirmed"):
358 self.abort(admin=admin)
359
360 resp["request"] = requests
361 resp["response"] = results
362 return resp
363
364 def restore(self, filename=None, path=""):
365 if not filename:
366 raise ValueError("'file_name' value is required for restore")
367 self.configure()
368 cmd = f"load {path}{filename}"
369 resp = self.send_command(cmd)
370 self.commit()
371 return resp
372
373 def get_diff(
374 self,
375 candidate=None,
376 running=None,
377 diff_match="line",
378 diff_ignore_lines=None,
379 path=None,
380 diff_replace="line",
381 ):
382 diff = {}
383 device_operations = self.get_device_operations()
384 option_values = self.get_option_values()
385
386 if candidate is None and device_operations["supports_generate_diff"]:
387 raise ValueError("candidate configuration is required to generate diff")
388
389 if diff_match not in option_values["diff_match"]:
390 raise ValueError(
391 "'match' value %s in invalid, valid values are %s"
392 % (diff_match, ", ".join(option_values["diff_match"])),
393 )
394
395 if diff_replace not in option_values["diff_replace"]:
396 raise ValueError(
397 "'replace' value %s in invalid, valid values are %s"
398 % (diff_replace, ", ".join(option_values["diff_replace"])),
399 )
400
401 # prepare candidate configuration
402 sanitized_candidate = sanitize_config(candidate)
403 candidate_obj = NetworkConfig(indent=1, comment_tokens=["!"])
404 candidate_obj.load(sanitized_candidate)
405
406 if running and diff_match != "none":
407 # running configuration
408 running = mask_config_blocks_from_diff(running, candidate, "ansible")
409 running = sanitize_config(running)
410
411 running_obj = NetworkConfig(
412 indent=1,
413 contents=running,
414 ignore_lines=diff_ignore_lines,
415 comment_tokens=["!"],
416 )
417 configdiffobjs = candidate_obj.difference(
418 running_obj,
419 path=path,
420 match=diff_match,
421 replace=diff_replace,
422 )
423
424 else:
425 configdiffobjs = candidate_obj.items
426
427 diff["config_diff"] = dumps(configdiffobjs, "commands") if configdiffobjs else ""
428 return diff
429
430 def get(
431 self,
432 command=None,
433 prompt=None,
434 answer=None,
435 sendonly=False,
436 newline=True,
437 output=None,
438 check_all=False,
439 ):
440 if output:
441 raise ValueError("'output' value %s is not supported for get" % output)
442 return self.send_command(
443 command=command,
444 prompt=prompt,
445 answer=answer,
446 sendonly=sendonly,
447 newline=newline,
448 check_all=check_all,
449 )
450
451 def commit(self, comment=None, label=None, replace=None):
452 """Implements commit functionality of config module
453 and commit confirmed functionality of cliconf module
454
455 Args:
456 comment (str, optional): commit comment. Defaults to None.
457 label (str, optional): commit label. Defaults to None.
458 replace (bool, optional): Flag to replace commit. Defaults to None.
459 """
460
461 cmd_obj = {}
462 if replace:
463 cmd_obj["command"] = "commit replace"
464 if self.get_option("commit_confirmed"):
465 cmd_obj["command"] = "commit replace confirmed"
466 if self.get_option("commit_confirmed_timeout"):
467 cmd_obj["command"] += " {0}".format(
468 self.get_option("commit_confirmed_timeout"),
469 )
470
471 cmd_obj["prompt"] = (
472 "This commit will replace or remove the entire running configuration"
473 )
474 cmd_obj["answer"] = "yes"
475
476 elif self.get_option("commit_confirmed"):
477 cmd_obj["command"] = "commit confirmed"
478 if self.get_option("commit_confirmed_timeout"):
479 cmd_obj["command"] += " {0}".format(
480 self.get_option("commit_confirmed_timeout"),
481 )
482 if self.get_option("commit_label"):
483 cmd_obj["command"] += " label {0}".format(
484 self.get_option("commit_label"),
485 )
486 if self.get_option("commit_comment"):
487 cmd_obj["command"] += " comment {0}".format(
488 self.get_option("commit_comment"),
489 )
490
491 else:
492 label = label or self.get_option("commit_label")
493 comment = comment or self.get_option("commit_comment")
494
495 if comment or label:
496 cmd_obj["command"] = "commit"
497 if label:
498 cmd_obj["command"] += " label {0}".format(label)
499 if comment:
500 cmd_obj["command"] += " comment {0}".format(comment)
501
502 else:
503 cmd_obj["command"] = "commit show-error"
504 # In some cases even a normal commit, i.e., !replace,
505 # throws a prompt and we need to handle it before
506 # proceeding further
507 cmd_obj["prompt"] = "(C|c)onfirm"
508 cmd_obj["answer"] = "y"
509 self.send_command(**cmd_obj)
510
511 def run_commands(self, commands=None, check_rc=True):
512 if commands is None:
513 raise ValueError("'commands' value is required")
514 responses = list()
515 for cmd in to_list(commands):
516 if not isinstance(cmd, Mapping):
517 cmd = {"command": cmd}
518
519 output = cmd.pop("output", None)
520 if output:
521 raise ValueError(
522 "'output' value %s is not supported for run_commands" % output,
523 )
524
525 try:
526 out = self.send_command(**cmd)
527 except AnsibleConnectionFailure as e:
528 if check_rc:
529 raise
530 out = getattr(e, "err", e)
531
532 if out is not None:
533 try:
534 out = to_text(out, errors="surrogate_or_strict").strip()
535 except UnicodeError:
536 raise ConnectionError(
537 message="Failed to decode output from %s: %s" % (cmd, to_text(out)),
538 )
539
540 try:
541 out = json.loads(out)
542 except ValueError:
543 pass
544
545 responses.append(out)
546 return responses
547
548 def discard_changes(self):
549 self.send_command("abort")
550
551 def get_device_operations(self):
552 return {
553 "supports_diff_replace": True,
554 "supports_commit": True,
555 "supports_rollback": False,
556 "supports_defaults": False,
557 "supports_onbox_diff": False,
558 "supports_commit_comment": True,
559 "supports_multiline_delimiter": False,
560 "supports_diff_match": True,
561 "supports_diff_ignore_lines": True,
562 "supports_generate_diff": True,
563 "supports_replace": True,
564 "supports_admin": True,
565 "supports_commit_label": True,
566 }
567
568 def get_option_values(self):
569 return {
570 "format": ["text"],
571 "diff_match": ["line", "strict", "exact", "none"],
572 "diff_replace": ["line", "block", "config"],
573 "output": [],
574 }
575
576 def get_capabilities(self):
577 result = super(Cliconf, self).get_capabilities()
578 result["rpc"] += ["commit", "discard_changes", "get_diff", "configure", "exit"]
579 result["device_operations"] = self.get_device_operations()
580 result.update(self.get_option_values())
581 return json.dumps(result)
582
583 def set_cli_prompt_context(self):
584 """
585 Make sure we are in the operational cli mode
586 :return: None
587 """
588 if self._connection.connected and not self.get_option("commit_confirmed"):
589 self._update_cli_prompt_context(config_context=")#", exit_command="abort")