Debian Codegraph @

ansible_collections/cisco/nxos/plugins/httpapi/nxos.py

raw
1 # (c) 2018 Red Hat Inc.
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import absolute_import, division, print_function
5
6
7 __metaclass__ = type
8
9 DOCUMENTATION = """
10 author: Ansible Networking Team (@ansible-network)
11 name: nxos
12 short_description: Use NX-API to run commands on Cisco NX-OS platform
13 description:
14 - This plugin provides low level abstraction APIs for sending and receiving
15 commands using NX-API with devices running Cisco NX-OS.
16 version_added: 1.0.0
17 """
18
19 import collections
20 import json
21 import re
22
23 from ansible.module_utils._text import to_text
24 from ansible.module_utils.connection import ConnectionError
25 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list
26 from ansible_collections.ansible.netcommon.plugins.plugin_utils.httpapi_base import HttpApiBase
27
28
29 OPTIONS = {
30 "format": ["text", "json"],
31 "diff_match": ["line", "strict", "exact", "none"],
32 "diff_replace": ["line", "block", "config"],
33 "output": ["text", "json"],
34 }
35
36
37 class HttpApi(HttpApiBase):
38 def __init__(self, *args, **kwargs):
39 super(HttpApi, self).__init__(*args, **kwargs)
40 self._device_info = None
41 self._module_context = {}
42
43 def read_module_context(self, module_key):
44 if self._module_context.get(module_key):
45 return self._module_context[module_key]
46
47 return None
48
49 def save_module_context(self, module_key, module_context):
50 self._module_context[module_key] = module_context
51
52 return None
53
54 def send_request(self, data, **message_kwargs):
55 output = None
56 queue = list()
57 responses = list()
58
59 for item in to_list(data):
60 cmd_output = message_kwargs.get("output") or "text"
61 if isinstance(item, dict):
62 command = item["command"]
63 if "output" in item:
64 cmd_output = item["output"]
65 else:
66 command = item
67
68 # Emulate '| json' from CLI
69 if command.endswith("| json"):
70 command = command.rsplit("|", 1)[0]
71 cmd_output = "json"
72
73 if output and output != cmd_output:
74 responses.extend(self._run_queue(queue, output))
75 queue = list()
76
77 output = cmd_output
78 queue.append(command)
79
80 if queue:
81 responses.extend(self._run_queue(queue, output))
82
83 if len(responses) == 1:
84 return responses[0]
85 return responses
86
87 def _run_queue(self, queue, output):
88 if self._become:
89 self.connection.queue_message(
90 "warning",
91 "become has no effect over httpapi. Use network_cli if privilege escalation is required",
92 )
93
94 request = request_builder(queue, output)
95 headers = {"Content-Type": "application/json"}
96
97 response, response_data = self.connection.send(
98 "/ins",
99 request,
100 headers=headers,
101 method="POST",
102 )
103
104 try:
105 response_data = json.loads(to_text(response_data.getvalue()))
106 except ValueError:
107 raise ConnectionError(
108 "Response was not valid JSON, got {0}".format(to_text(response_data.getvalue())),
109 )
110
111 results = handle_response(response_data)
112 return results
113
114 def get_device_info(self):
115 if self._device_info:
116 return self._device_info
117
118 device_info = {}
119
120 device_info["network_os"] = "nxos"
121 reply, platform_reply = self.send_request(["show version", "show inventory"])
122
123 find_os_version = [
124 r"\s+system:\s+version\s*(\S+)",
125 r"\s+kickstart:\s+version\s*(\S+)",
126 r"\s+NXOS:\s+version\s*(\S+)",
127 ]
128 for regex in find_os_version:
129 match_ver = re.search(regex, reply, re.M)
130 if match_ver:
131 device_info["network_os_version"] = match_ver.group(1)
132 break
133
134 match_chassis_id = re.search(r"Hardware\n\s+cisco\s*(\S+\s+\S+)", reply, re.M)
135 if match_chassis_id:
136 device_info["network_os_model"] = match_chassis_id.group(1)
137
138 match_host_name = re.search(r"\s+Device name:\s*(\S+)", reply, re.M)
139 if match_host_name:
140 device_info["network_os_hostname"] = match_host_name.group(1)
141
142 find_os_image = [
143 r"\s+system image file is:\s*(\S+)",
144 r"\s+kickstart image file is:\s*(\S+)",
145 r"\s+NXOS image file is:\s*(\S+)",
146 ]
147 for regex in find_os_image:
148 match_file_name = re.search(regex, reply, re.M)
149 if match_file_name:
150 device_info["network_os_image"] = match_file_name.group(1)
151 break
152
153 match_os_platform = re.search(
154 r'NAME: (?:"Chassis"| Chassis ),\s*DESCR:.*\nPID:\s*(\S+)',
155 platform_reply,
156 re.M,
157 )
158 if match_os_platform:
159 device_info["network_os_platform"] = match_os_platform.group(1)
160
161 self._device_info = device_info
162 return self._device_info
163
164 def get_device_operations(self):
165 platform = self.get_device_info().get("network_os_platform", "")
166 return {
167 "supports_diff_replace": True,
168 "supports_commit": False,
169 "supports_rollback": False,
170 "supports_defaults": True,
171 "supports_onbox_diff": False,
172 "supports_commit_comment": False,
173 "supports_multiline_delimiter": False,
174 "supports_diff_match": True,
175 "supports_diff_ignore_lines": True,
176 "supports_generate_diff": True,
177 "supports_replace": True if "9K" in platform else False,
178 }
179
180 def get_capabilities(self):
181 result = {}
182 result["rpc"] = []
183 result["device_info"] = self.get_device_info()
184 result["device_operations"] = self.get_device_operations()
185 result.update(OPTIONS)
186 result["network_api"] = "nxapi"
187
188 return json.dumps(result)
189
190 # Shims for resource module support
191 def get(self, command, output=None):
192 # This method is ONLY here to support resource modules. Therefore most
193 # arguments are unsupported and not present.
194
195 return self.send_request(data=command, output=output)
196
197 def edit_config(self, candidate):
198 # This method is ONLY here to support resource modules. Therefore most
199 # arguments are unsupported and not present.
200
201 responses = self.send_request(candidate, output="config")
202 return [resp for resp in to_list(responses) if resp != "{}"]
203
204
205 def handle_response(response):
206 results = []
207
208 if response["ins_api"].get("outputs"):
209 for output in to_list(response["ins_api"]["outputs"]["output"]):
210 if output["code"] != "200":
211 # Best effort messages: some API output keys may not exist on some platforms
212 input_data = output.get("input", "")
213 msg = output.get("msg", "")
214 clierror = output.get("clierror", "")
215 raise ConnectionError(
216 "%s: %s: %s" % (input_data, msg, clierror),
217 code=output["code"],
218 )
219 elif "body" in output:
220 result = output["body"]
221 if isinstance(result, dict):
222 result = json.dumps(result)
223
224 results.append(result.strip())
225
226 return results
227
228
229 def request_builder(commands, output, version="1.0", chunk="0", sid=None):
230 """Encodes a NXAPI JSON request message"""
231 output_to_command_type = {
232 "text": "cli_show_ascii",
233 "json": "cli_show",
234 "bash": "bash",
235 "config": "cli_conf",
236 }
237
238 maybe_output = commands[0].split("|")[-1].strip()
239 if maybe_output in output_to_command_type:
240 command_type = output_to_command_type[maybe_output]
241 commands = [command.split("|")[0].strip() for command in commands]
242 else:
243 try:
244 command_type = output_to_command_type[output]
245 except KeyError:
246 msg = "invalid format, received %s, expected one of %s" % (
247 output,
248 ",".join(output_to_command_type.keys()),
249 )
250 raise ConnectionError(msg)
251
252 if isinstance(commands, (list, set, tuple)):
253 commands = " ;".join(commands)
254
255 # Order should not matter but some versions of NX-OS software fail
256 # to process the payload properly if 'input' gets serialized before
257 # 'type' and the payload of 'input' contains the word 'type'.
258 msg = collections.OrderedDict()
259 msg["version"] = version
260 msg["type"] = command_type
261 msg["chunk"] = chunk
262 msg["sid"] = sid
263 msg["input"] = commands
264 msg["output_format"] = "json"
265
266 return json.dumps(dict(ins_api=msg))