VXLAN test with dot1q tagging.
[csit.git] / resources / libraries / python / VatExecutor.py
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:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
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.
13 from ssh import SSH
14 from robot.api import logger
15 from constants import Constants
16 import json
17
18 __all__ = ['VatExecutor']
19
20
21 def cleanup_vat_json_output(json_output):
22     """Return VAT json output cleaned from VAT clutter.
23
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
27     """
28
29     retval = json_output
30     clutter = ['vat#', 'dump_interface_table error: Misc']
31     for garbage in clutter:
32         retval = retval.replace(garbage, '')
33     return retval
34
35
36 class VatExecutor(object):
37     def __init__(self):
38         self._stdout = None
39         self._stderr = None
40         self._ret_code = None
41
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.
44
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
47             automatically.
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.
52         """
53
54         ssh = SSH()
55         ssh.connect(node)
56
57         remote_file_path = '{0}/{1}/{2}'.format(Constants.REMOTE_FW_DIR,
58                                                 Constants.RESOURCES_TPL_VAT,
59                                                 vat_name)
60         # TODO this overwrites the output if the vat script has been used twice
61         remote_file_out = remote_file_path + ".out"
62
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
69         self._stdout = stdout
70         self._stderr = stderr
71
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))
75
76         # TODO: download vpp_api_test output file
77         # self._delete_files(node, remote_file_path, remote_file_out)
78
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)
82
83     @staticmethod
84     def _delete_files(node, *files):
85         ssh = SSH()
86         ssh.connect(node)
87         files = " ".join([str(x) for x in files])
88         ssh.exec_command("rm {0}".format(files))
89
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:
94             raise AssertionError(
95                 "Script execution passed, but failure was expected")
96
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")
103
104     def get_script_stdout(self):
105         return self._stdout
106
107     def get_script_stderr(self):
108         return self._stderr
109
110     @staticmethod
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
118         """
119         with VatTerminal(node) as vat:
120             return vat.vat_terminal_exec_cmd_from_template(vat_template_file,
121                                                            **vat_args)
122
123     @staticmethod
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
127
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
130         test cases.
131         :param remote_path: path on remote node where to copy the VAT
132         configuration script file
133         """
134         ssh = SSH()
135         ssh.connect(node)
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)
139
140
141 class VatTerminal(object):
142     """VAT interactive terminal
143
144        :param node: Node to open VAT terminal on.
145        :param json_param: Defines if outputs from VAT are in JSON format.
146        Default is True.
147        :type node: dict
148        :type json_param: bool
149
150     """
151
152     __VAT_PROMPT = "vat# "
153     __LINUX_PROMPT = ":~$ "
154
155     def __init__(self, node, json_param=True):
156         json_text = ' json' if json_param else ''
157         self.json = json_param
158         self._ssh = SSH()
159         self._ssh.connect(node)
160         self._tty = self._ssh.interactive_terminal_open()
161         self._ssh.interactive_terminal_exec_command(
162             self._tty,
163             'sudo -S {}{}'.format(Constants.VAT_BIN_NAME, json_text),
164             self.__VAT_PROMPT)
165
166     def __enter__(self):
167         return self
168
169     def __exit__(self, exc_type, exc_val, exc_tb):
170         self.vat_terminal_close()
171
172     def vat_terminal_exec_cmd(self, cmd):
173         """Execute command on the opened VAT terminal.
174
175            :param cmd: Command to be executed.
176
177            :return: Command output in python representation of JSON format or
178            None if not in JSON mode.
179         """
180         logger.debug("Executing command in VAT terminal: {}".format(cmd))
181         out = self._ssh.interactive_terminal_exec_command(self._tty,
182                                                           cmd,
183                                                           self.__VAT_PROMPT)
184         logger.debug("VAT output: {}".format(out))
185         if self.json:
186             json_out = json.loads(out)
187             return json_out
188         else:
189             return None
190
191     def vat_terminal_close(self):
192         """Close VAT terminal."""
193         self._ssh.interactive_terminal_exec_command(self._tty,
194                                                     'quit',
195                                                     self.__LINUX_PROMPT)
196         self._ssh.interactive_terminal_close(self._tty)
197
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
203         """
204         file_path = '{}/{}'.format(Constants.RESOURCES_TPL_VAT,
205                                    vat_template_file)
206         with open(file_path, 'r') as template_file:
207             cmd_template = template_file.readlines()
208         ret = []
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', '')))
212         return ret