1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 """VAT executor library."""
18 from paramiko.ssh_exception import SSHException
19 from robot.api import logger
21 from resources.libraries.python.ssh import SSH, SSHTimeout
22 from resources.libraries.python.constants import Constants
23 from resources.libraries.python.VatHistory import VatHistory
25 __all__ = ['VatExecutor']
28 def cleanup_vat_json_output(json_output, vat_name=None):
29 """Return VAT JSON output cleaned from VAT clutter.
31 Clean up VAT JSON output from clutter like vat# prompts and such.
33 :param json_output: Cluttered JSON output.
34 :param vat_name: Name of the VAT script.
35 :type json_output: JSON
37 :returns: Cleaned up output JSON string.
42 clutter = ['vat#', 'dump_interface_table error: Misc']
44 remote_file_path = '{0}/{1}/{2}'.format(Constants.REMOTE_FW_DIR,
45 Constants.RESOURCES_TPL_VAT,
47 clutter.append("{0}(2):".format(remote_file_path))
48 for garbage in clutter:
49 retval = retval.replace(garbage, '')
53 def get_vpp_pid(node):
54 """Get PID of running VPP process.
56 :param node: DUT node.
58 :returns: PID of VPP process / List of PIDs if more VPP processes are
59 running on the DUT node.
62 import resources.libraries.python.DUTSetup as PidLib
63 pid = PidLib.DUTSetup.get_vpp_pid(node)
67 class VatExecutor(object):
68 """Contains methods for executing VAT commands on DUTs."""
74 def execute_script(self, vat_name, node, timeout=15, json_out=True):
75 """Copy local_path script to node, execute it and return result.
77 :param vat_name: Name of the vat script file. Only the file name of
78 the script is required, the resources path is prepended automatically.
79 :param node: Node to execute the VAT script on.
80 :param timeout: Seconds to allow the script to run.
81 :param json_out: Require JSON output.
86 :returns: Status code, stdout and stderr of executed VAT script.
88 :raises RuntimeError: If VAT script execution failed.
95 raise SSHException("Cannot open SSH connection to execute VAT "
96 "command(s) from template {0}".format(vat_name))
98 remote_file_path = '{0}/{1}/{2}'.format(Constants.REMOTE_FW_DIR,
99 Constants.RESOURCES_TPL_VAT,
101 # TODO this overwrites the output if the vat script has been used twice
102 # remote_file_out = remote_file_path + ".out"
104 cmd = "sudo -S {vat} {json} in {input} script".format(
105 vat=Constants.VAT_BIN_NAME,
106 json="json" if json_out is True else "",
107 input=remote_file_path)
110 (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout)
112 logger.error("VAT script execution timeout: {0}".format(cmd))
115 raise RuntimeError("VAT script execution failed: {0}".format(cmd))
117 self._ret_code = ret_code
118 self._stdout = stdout
119 self._stderr = stderr
121 # TODO: download vpp_api_test output file
122 # self._delete_files(node, remote_file_path, remote_file_out)
124 def scp_and_execute_script(self, vat_name, node, timeout=15, json_out=True):
125 """Copy vat_name script to node, execute it and return result.
127 :param vat_name: Name of the vat script file.
128 Full path and name of the script is required.
129 :param node: Node to execute the VAT script on.
130 :param timeout: Seconds to allow the script to run.
131 :param json_out: Require JSON output.
136 :returns: Status code, stdout and stderr of executed VAT script.
138 :raises RuntimeError: If VAT script execution failed.
145 raise SSHException("Cannot open SSH connection to execute VAT "
146 "command(s) from template {0}".format(vat_name))
148 ssh.scp(vat_name, vat_name)
150 cmd = "sudo -S {vat} {json} in {input} script".format(
151 json="json" if json_out is True else "",
152 vat=Constants.VAT_BIN_NAME,
156 (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout)
158 logger.error("VAT script execution timeout: {0}".format(cmd))
161 raise RuntimeError("VAT script execution failed: {0}".format(cmd))
163 self._ret_code = ret_code
164 self._stdout = stdout
165 self._stderr = stderr
167 self._delete_files(node, vat_name)
169 def scp_and_execute_cli_script(self, fname, node, timeout=15,
171 """Copy vat_name script to node, execute it and return result.
173 :param fname: Name of the VPP script file.
174 Full path and name of the script is required.
175 :param node: Node to execute the VPP script on.
176 :param timeout: Seconds to allow the script to run.
177 :param json_out: Require JSON output.
182 :returns: Status code, stdout and stderr of executed CLI script.
184 :raises RuntimeError: If CLI script execution failed.
191 raise SSHException("Cannot open SSH connection to execute CLI "
192 "command(s) from template {0}".format(fname))
194 ssh.scp(fname, fname)
196 cmd = "{vat} {json}".format(json="json" if json_out is True else "",
197 vat=Constants.VAT_BIN_NAME)
198 cmd_input = "exec exec {0}".format(fname)
201 (ret_code, stdout, stderr) = ssh.exec_command_sudo(cmd, cmd_input,
204 logger.error("CLI script execution timeout: {0}{1}".
205 format(cmd, "<<< " + cmd_input if cmd_input else ""))
208 raise RuntimeError("CLI script execution failed: {0}{1}".format(
209 cmd, "<<< " + cmd_input if cmd_input else ""))
211 self._ret_code = ret_code
212 self._stdout = stdout
213 self._stderr = stderr
215 self._delete_files(node, fname)
217 def execute_script_json_out(self, vat_name, node, timeout=15):
218 """Pass all arguments to 'execute_script' method, then cleanup returned
221 :param vat_name: Name of the vat script file. Only the file name of
222 the script is required, the resources path is prepended automatically.
223 :param node: Node to execute the VAT script on.
224 :param timeout: Seconds to allow the script to run.
229 self.execute_script(vat_name, node, timeout, json_out=True)
230 self._stdout = cleanup_vat_json_output(self._stdout, vat_name=vat_name)
233 def _delete_files(node, *files):
234 """Use SSH to delete the specified files on node.
236 :param node: Node in topology.
237 :param files: Files to delete.
239 :type files: iterable
244 files = " ".join([str(x) for x in files])
245 ssh.exec_command("rm {0}".format(files))
247 def script_should_have_failed(self):
248 """Read return code from last executed script and raise exception if the
249 script didn't fail."""
250 if self._ret_code is None:
251 raise Exception("First execute the script!")
252 if self._ret_code == 0:
253 raise AssertionError(
254 "Script execution passed, but failure was expected")
256 def script_should_have_passed(self):
257 """Read return code from last executed script and raise exception if the
259 if self._ret_code is None:
260 raise Exception("First execute the script!")
261 if self._ret_code != 0:
262 raise AssertionError(
263 "Script execution failed, but success was expected")
265 def get_script_stdout(self):
266 """Returns value of stdout from last executed script."""
269 def get_script_stderr(self):
270 """Returns value of stderr from last executed script."""
274 def cmd_from_template(node, vat_template_file, **vat_args):
275 """Execute VAT script on specified node. This method supports
276 script templates with parameters.
278 :param node: Node in topology on witch the script is executed.
279 :param vat_template_file: Template file of VAT script.
280 :param vat_args: Arguments to the template file.
281 :return: List of JSON objects returned by VAT.
283 with VatTerminal(node) as vat:
284 return vat.vat_terminal_exec_cmd_from_template(vat_template_file,
288 class VatTerminal(object):
289 """VAT interactive terminal.
291 :param node: Node to open VAT terminal on.
292 :param json_param: Defines if outputs from VAT are in JSON format.
295 :type json_param: bool
299 __VAT_PROMPT = ("vat# ", )
300 __LINUX_PROMPT = (":~$ ", "~]$ ")
302 def __init__(self, node, json_param=True):
303 json_text = ' json' if json_param else ''
304 self.json = json_param
307 self._ssh.connect(self._node)
309 self._tty = self._ssh.interactive_terminal_open()
311 raise RuntimeError("Cannot open interactive terminal on node {0}".
316 self._ssh.interactive_terminal_exec_command(
318 'sudo -S {0}{1}'.format(Constants.VAT_BIN_NAME, json_text),
325 vpp_pid = get_vpp_pid(self._node)
327 if isinstance(vpp_pid, int):
328 logger.trace("VPP running on node {0}".
329 format(self._node['host']))
331 logger.error("More instances of VPP running on node {0}.".
332 format(self._node['host']))
334 logger.error("VPP not running on node {0}.".
335 format(self._node['host']))
336 raise RuntimeError("Failed to open VAT console on node {0}".
337 format(self._node['host']))
339 self._exec_failure = False
340 self.vat_stdout = None
345 def __exit__(self, exc_type, exc_val, exc_tb):
346 self.vat_terminal_close()
348 def vat_terminal_exec_cmd(self, cmd):
349 """Execute command on the opened VAT terminal.
351 :param cmd: Command to be executed.
353 :return: Command output in python representation of JSON format or
354 None if not in JSON mode.
356 VatHistory.add_to_vat_history(self._node, cmd)
357 logger.debug("Executing command in VAT terminal: {0}".format(cmd))
359 out = self._ssh.interactive_terminal_exec_command(self._tty, cmd,
361 self.vat_stdout = out
363 self._exec_failure = True
364 vpp_pid = get_vpp_pid(self._node)
366 if isinstance(vpp_pid, int):
367 raise RuntimeError("VPP running on node {0} but VAT command"
368 " {1} execution failed.".
369 format(self._node['host'], cmd))
371 raise RuntimeError("More instances of VPP running on node "
372 "{0}. VAT command {1} execution failed.".
373 format(self._node['host'], cmd))
375 raise RuntimeError("VPP not running on node {0}. VAT command "
376 "{1} execution failed.".
377 format(self._node['host'], cmd))
379 logger.debug("VAT output: {0}".format(out))
381 obj_start = out.find('{')
382 obj_end = out.rfind('}')
383 array_start = out.find('[')
384 array_end = out.rfind(']')
386 if obj_start == -1 and array_start == -1:
387 raise RuntimeError("VAT command {0}: no JSON data.".format(cmd))
389 if obj_start < array_start or array_start == -1:
396 json_out = json.loads(out)
401 def vat_terminal_close(self):
402 """Close VAT terminal."""
403 # interactive terminal is dead, we only need to close session
404 if not self._exec_failure:
406 self._ssh.interactive_terminal_exec_command(self._tty,
410 vpp_pid = get_vpp_pid(self._node)
412 if isinstance(vpp_pid, int):
413 logger.trace("VPP running on node {0}.".
414 format(self._node['host']))
416 logger.error("More instances of VPP running on node "
417 "{0}.".format(self._node['host']))
419 logger.error("VPP not running on node {0}.".
420 format(self._node['host']))
421 raise RuntimeError("Failed to close VAT console on node {0}".
422 format(self._node['host']))
424 self._ssh.interactive_terminal_close(self._tty)
426 raise RuntimeError("Cannot close interactive terminal on node {0}".
427 format(self._node['host']))
429 def vat_terminal_exec_cmd_from_template(self, vat_template_file, **args):
430 """Execute VAT script from a file.
432 :param vat_template_file: Template file name of a VAT script.
433 :param args: Dictionary of parameters for VAT script.
434 :return: List of JSON objects returned by VAT.
436 file_path = '{}/{}'.format(Constants.RESOURCES_TPL_VAT,
438 with open(file_path, 'r') as template_file:
439 cmd_template = template_file.readlines()
441 for line_tmpl in cmd_template:
442 vat_cmd = line_tmpl.format(**args)
443 ret.append(self.vat_terminal_exec_cmd(vat_cmd.replace('\n', '')))