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 from robot.api import logger
15 from constants import Constants
18 __all__ = ['VatExecutor']
21 def cleanup_vat_json_output(json_output):
22 """Return VAT json output cleaned from VAT clutter.
24 Clean up VAT json output from clutter like vat# prompts and such
25 :param json_output: cluttered json output.
26 :return: cleaned up output json string
30 clutter = ['vat#', 'dump_interface_table error: Misc']
31 for garbage in clutter:
32 retval = retval.replace(garbage, '')
36 class VatExecutor(object):
42 def execute_script(self, vat_name, node, timeout=10, json_out=True):
43 """Copy local_path script to node, execute it and return result.
45 :param vat_name: name of the vat script file. Only the file name of
46 the script is required, the resources path is prepended
48 :param node: node to execute the VAT script on.
49 :param timeout: seconds to allow the script to run.
50 :param json_out: require json output.
51 :return: (rc, stdout, stderr) tuple.
57 remote_file_path = '{0}/{1}/{2}'.format(Constants.REMOTE_FW_DIR,
58 Constants.RESOURCES_TPL_VAT,
60 # TODO this overwrites the output if the vat script has been used twice
61 remote_file_out = remote_file_path + ".out"
63 cmd = "sudo -S {vat} {json} < {input}".format(
64 vat=Constants.VAT_BIN_NAME,
65 json="json" if json_out is True else "",
66 input=remote_file_path)
67 (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout)
68 self._ret_code = ret_code
72 logger.trace("Command '{0}' returned {1}'".format(cmd, self._ret_code))
73 logger.trace("stdout: '{0}'".format(self._stdout))
74 logger.trace("stderr: '{0}'".format(self._stderr))
76 # TODO: download vpp_api_test output file
77 # self._delete_files(node, remote_file_path, remote_file_out)
79 def execute_script_json_out(self, vat_name, node, timeout=10):
80 self.execute_script(vat_name, node, timeout, json_out=True)
81 self._stdout = cleanup_vat_json_output(self._stdout)
84 def _delete_files(node, *files):
87 files = " ".join([str(x) for x in files])
88 ssh.exec_command("rm {0}".format(files))
90 def script_should_have_failed(self):
91 if self._ret_code is None:
92 raise Exception("First execute the script!")
93 if self._ret_code == 0:
95 "Script execution passed, but failure was expected")
97 def script_should_have_passed(self):
98 if self._ret_code is None:
99 raise Exception("First execute the script!")
100 if self._ret_code != 0:
101 raise AssertionError(
102 "Script execution failed, but success was expected")
104 def get_script_stdout(self):
107 def get_script_stderr(self):
111 def cmd_from_template(node, vat_template_file, **vat_args):
112 """Execute VAT script on specified node. This method supports
113 script templates with parameters
114 :param node: node in topology on witch the script is executed
115 :param vat_template_file: template file of VAT script
116 :param vat_args: arguments to the template file
117 :return: list of json objects returned by VAT
119 with VatTerminal(node) as vat:
120 return vat.vat_terminal_exec_cmd_from_template(vat_template_file,
124 def copy_config_to_remote(node, local_path, remote_path):
125 # TODO: will be removed once v4 is merged to master.
126 """Copies vat configuration file to node
128 :param node: Remote node on which to copy the VAT configuration file
129 :param local_path: path of the VAT script on local device that launches
131 :param remote_path: path on remote node where to copy the VAT
132 configuration script file
136 logger.trace("Removing old file {}".format(remote_path))
137 ssh.exec_command_sudo("rm -f {}".format(remote_path))
138 ssh.scp(local_path, remote_path)
141 class VatTerminal(object):
142 """VAT interactive terminal
144 :param node: Node to open VAT terminal on.
145 :param json_param: Defines if outputs from VAT are in JSON format.
148 :type json_param: bool
152 __VAT_PROMPT = "vat# "
153 __LINUX_PROMPT = ":~$ "
155 def __init__(self, node, json_param=True):
156 json_text = ' json' if json_param else ''
157 self.json = json_param
159 self._ssh.connect(node)
160 self._tty = self._ssh.interactive_terminal_open()
161 self._ssh.interactive_terminal_exec_command(
163 'sudo -S {}{}'.format(Constants.VAT_BIN_NAME, json_text),
169 def __exit__(self, exc_type, exc_val, exc_tb):
170 self.vat_terminal_close()
172 def vat_terminal_exec_cmd(self, cmd):
173 """Execute command on the opened VAT terminal.
175 :param cmd: Command to be executed.
177 :return: Command output in python representation of JSON format or
178 None if not in JSON mode.
180 logger.debug("Executing command in VAT terminal: {}".format(cmd))
181 out = self._ssh.interactive_terminal_exec_command(self._tty,
184 logger.debug("VAT output: {}".format(out))
186 json_out = json.loads(out)
191 def vat_terminal_close(self):
192 """Close VAT terminal."""
193 self._ssh.interactive_terminal_exec_command(self._tty,
196 self._ssh.interactive_terminal_close(self._tty)
198 def vat_terminal_exec_cmd_from_template(self, vat_template_file, **args):
199 """Execute VAT script from a file.
200 :param vat_template_file: template file name of a VAT script
201 :param args: dictionary of parameters for VAT script
202 :return: list of json objects returned by VAT
204 file_path = '{}/{}'.format(Constants.RESOURCES_TPL_VAT,
206 with open(file_path, 'r') as template_file:
207 cmd_template = template_file.readlines()
209 for line_tmpl in cmd_template:
210 vat_cmd = line_tmpl.format(**args)
211 ret.append(self.vat_terminal_exec_cmd(vat_cmd.replace('\n', '')))