add new topology parameter: arch
[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
14 """VAT executor library."""
15
16 import json
17
18 from paramiko.ssh_exception import SSHException
19 from robot.api import logger
20
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
24
25 __all__ = ['VatExecutor']
26
27
28 def cleanup_vat_json_output(json_output, vat_name=None):
29     """Return VAT JSON output cleaned from VAT clutter.
30
31     Clean up VAT JSON output from clutter like vat# prompts and such.
32
33     :param json_output: Cluttered JSON output.
34     :param vat_name: Name of the VAT script.
35     :type json_output: JSON
36     :type vat_name: str
37     :returns: Cleaned up output JSON string.
38     :rtype: JSON
39     """
40
41     retval = json_output
42     clutter = ['vat#', 'dump_interface_table error: Misc']
43     if vat_name:
44         remote_file_path = '{0}/{1}/{2}'.format(Constants.REMOTE_FW_DIR,
45                                                 Constants.RESOURCES_TPL_VAT,
46                                                 vat_name)
47         clutter.append("{0}(2):".format(remote_file_path))
48     for garbage in clutter:
49         retval = retval.replace(garbage, '')
50     return retval
51
52
53 def get_vpp_pid(node):
54     """Get PID of running VPP process.
55
56     :param node: DUT node.
57     :type node: dict
58     :returns: PID of VPP process / List of PIDs if more VPP processes are
59     running on the DUT node.
60     :rtype: int or list
61     """
62     import resources.libraries.python.DUTSetup as PidLib
63     pid = PidLib.DUTSetup.get_vpp_pid(node)
64     return pid
65
66
67 class VatExecutor(object):
68     """Contains methods for executing VAT commands on DUTs."""
69     def __init__(self):
70         self._stdout = None
71         self._stderr = None
72         self._ret_code = None
73
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.
76
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.
82         :type vat_name: str
83         :type node: dict
84         :type timeout: int
85         :type json_out: bool
86         :returns: Status code, stdout and stderr of executed VAT script.
87         :rtype: tuple
88         :raises RuntimeError: If VAT script execution failed.
89         """
90
91         ssh = SSH()
92         try:
93             ssh.connect(node)
94         except:
95             raise SSHException("Cannot open SSH connection to execute VAT "
96                                "command(s) from template {0}".format(vat_name))
97
98         remote_file_path = '{0}/{1}/{2}'.format(Constants.REMOTE_FW_DIR,
99                                                 Constants.RESOURCES_TPL_VAT,
100                                                 vat_name)
101         # TODO this overwrites the output if the vat script has been used twice
102         # remote_file_out = remote_file_path + ".out"
103
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)
108
109         try:
110             (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout)
111         except SSHTimeout:
112             logger.error("VAT script execution timeout: {0}".format(cmd))
113             raise
114         except:
115             raise RuntimeError("VAT script execution failed: {0}".format(cmd))
116
117         self._ret_code = ret_code
118         self._stdout = stdout
119         self._stderr = stderr
120
121         # TODO: download vpp_api_test output file
122         # self._delete_files(node, remote_file_path, remote_file_out)
123
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.
126
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.
132         :type vat_name: str
133         :type node: dict
134         :type timeout: int
135         :type json_out: bool
136         :returns: Status code, stdout and stderr of executed VAT script.
137         :rtype: tuple
138         :raises RuntimeError: If VAT script execution failed.
139         """
140
141         ssh = SSH()
142         try:
143             ssh.connect(node)
144         except:
145             raise SSHException("Cannot open SSH connection to execute VAT "
146                                "command(s) from template {0}".format(vat_name))
147
148         ssh.scp(vat_name, vat_name)
149
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,
153             input=vat_name)
154
155         with open(vat_name, 'r') as tmp_f:
156             VatHistory.add_to_vat_history(node, tmp_f.read())
157
158         try:
159             (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout)
160         except SSHTimeout:
161             logger.error("VAT script execution timeout: {0}".format(cmd))
162             raise
163         except:
164             raise RuntimeError("VAT script execution failed: {0}".format(cmd))
165
166         self._ret_code = ret_code
167         self._stdout = stdout
168         self._stderr = stderr
169
170         self._delete_files(node, vat_name)
171
172     def scp_and_execute_cli_script(self, fname, node, timeout=15,
173                                    json_out=True):
174         """Copy vat_name script to node, execute it and return result.
175
176         :param fname: Name of the VPP script file.
177         Full path and name of the script is required.
178         :param node: Node to execute the VPP script on.
179         :param timeout: Seconds to allow the script to run.
180         :param json_out: Require JSON output.
181         :type fname: str
182         :type node: dict
183         :type timeout: int
184         :type json_out: bool
185         :returns: Status code, stdout and stderr of executed CLI script.
186         :rtype: tuple
187         :raises RuntimeError: If CLI script execution failed.
188         """
189
190         ssh = SSH()
191         try:
192             ssh.connect(node)
193         except:
194             raise SSHException("Cannot open SSH connection to execute CLI "
195                                "command(s) from template {0}".format(fname))
196
197         ssh.scp(fname, fname)
198
199         cmd = "{vat} {json}".format(json="json" if json_out is True else "",
200                                     vat=Constants.VAT_BIN_NAME)
201         cmd_input = "exec exec {0}".format(fname)
202
203         VatHistory.add_to_vat_history(node, cmd_input)
204         with open(fname, 'r') as tmp_f:
205             VatHistory.add_to_vat_history(node, tmp_f.read())
206
207         try:
208             (ret_code, stdout, stderr) = ssh.exec_command_sudo(cmd, cmd_input,
209                                                                timeout)
210         except SSHTimeout:
211             logger.error("CLI script execution timeout: {0}{1}".
212                          format(cmd, "<<< " + cmd_input if cmd_input else ""))
213             raise
214         except:
215             raise RuntimeError("CLI script execution failed: {0}{1}".format(
216                 cmd, "<<< " + cmd_input if cmd_input else ""))
217
218         self._ret_code = ret_code
219         self._stdout = stdout
220         self._stderr = stderr
221
222         self._delete_files(node, fname)
223
224     def execute_script_json_out(self, vat_name, node, timeout=15):
225         """Pass all arguments to 'execute_script' method, then cleanup returned
226         json output.
227
228          :param vat_name: Name of the vat script file. Only the file name of
229         the script is required, the resources path is prepended automatically.
230         :param node: Node to execute the VAT script on.
231         :param timeout: Seconds to allow the script to run.
232         :type vat_name: str
233         :type node: dict
234         :type timeout: int
235         """
236         self.execute_script(vat_name, node, timeout, json_out=True)
237         self._stdout = cleanup_vat_json_output(self._stdout, vat_name=vat_name)
238
239     @staticmethod
240     def _delete_files(node, *files):
241         """Use SSH to delete the specified files on node.
242
243         :param node: Node in topology.
244         :param files: Files to delete.
245         :type node: dict
246         :type files: iterable
247         """
248
249         ssh = SSH()
250         ssh.connect(node)
251         files = " ".join([str(x) for x in files])
252         ssh.exec_command("rm {0}".format(files))
253
254     def script_should_have_failed(self):
255         """Read return code from last executed script and raise exception if the
256         script didn't fail."""
257         if self._ret_code is None:
258             raise Exception("First execute the script!")
259         if self._ret_code == 0:
260             raise AssertionError(
261                 "Script execution passed, but failure was expected")
262
263     def script_should_have_passed(self):
264         """Read return code from last executed script and raise exception if the
265         script failed."""
266         if self._ret_code is None:
267             raise Exception("First execute the script!")
268         if self._ret_code != 0:
269             raise AssertionError(
270                 "Script execution failed, but success was expected")
271
272     def get_script_stdout(self):
273         """Returns value of stdout from last executed script."""
274         return self._stdout
275
276     def get_script_stderr(self):
277         """Returns value of stderr from last executed script."""
278         return self._stderr
279
280     @staticmethod
281     def cmd_from_template(node, vat_template_file, **vat_args):
282         """Execute VAT script on specified node. This method supports
283         script templates with parameters.
284
285         :param node: Node in topology on witch the script is executed.
286         :param vat_template_file: Template file of VAT script.
287         :param vat_args: Arguments to the template file.
288         :return: List of JSON objects returned by VAT.
289         """
290         with VatTerminal(node) as vat:
291             return vat.vat_terminal_exec_cmd_from_template(vat_template_file,
292                                                            **vat_args)
293
294
295 class VatTerminal(object):
296     """VAT interactive terminal.
297
298     :param node: Node to open VAT terminal on.
299     :param json_param: Defines if outputs from VAT are in JSON format.
300     Default is True.
301     :type node: dict
302     :type json_param: bool
303
304     """
305
306     __VAT_PROMPT = ("vat# ", )
307     __LINUX_PROMPT = (":~$ ", "~]$ ", "~]# ")
308
309     def __init__(self, node, json_param=True):
310         json_text = ' json' if json_param else ''
311         self.json = json_param
312         self._node = node
313         self._ssh = SSH()
314         self._ssh.connect(self._node)
315         try:
316             self._tty = self._ssh.interactive_terminal_open()
317         except Exception:
318             raise RuntimeError("Cannot open interactive terminal on node {0}".
319                                format(self._node))
320
321         for _ in range(3):
322             try:
323                 self._ssh.interactive_terminal_exec_command(
324                     self._tty,
325                     'sudo -S {0}{1}'.format(Constants.VAT_BIN_NAME, json_text),
326                     self.__VAT_PROMPT)
327             except Exception:
328                 continue
329             else:
330                 break
331         else:
332             vpp_pid = get_vpp_pid(self._node)
333             if vpp_pid:
334                 if isinstance(vpp_pid, int):
335                     logger.trace("VPP running on node {0}".
336                                  format(self._node['host']))
337                 else:
338                     logger.error("More instances of VPP running on node {0}.".
339                                  format(self._node['host']))
340             else:
341                 logger.error("VPP not running on node {0}.".
342                              format(self._node['host']))
343             raise RuntimeError("Failed to open VAT console on node {0}".
344                                format(self._node['host']))
345
346         self._exec_failure = False
347         self.vat_stdout = None
348
349     def __enter__(self):
350         return self
351
352     def __exit__(self, exc_type, exc_val, exc_tb):
353         self.vat_terminal_close()
354
355     def vat_terminal_exec_cmd(self, cmd):
356         """Execute command on the opened VAT terminal.
357
358         :param cmd: Command to be executed.
359
360         :return: Command output in python representation of JSON format or
361         None if not in JSON mode.
362         """
363         VatHistory.add_to_vat_history(self._node, cmd)
364         logger.debug("Executing command in VAT terminal: {0}".format(cmd))
365         try:
366             out = self._ssh.interactive_terminal_exec_command(self._tty, cmd,
367                                                               self.__VAT_PROMPT)
368             self.vat_stdout = out
369         except Exception:
370             self._exec_failure = True
371             vpp_pid = get_vpp_pid(self._node)
372             if vpp_pid:
373                 if isinstance(vpp_pid, int):
374                     raise RuntimeError("VPP running on node {0} but VAT command"
375                                        " {1} execution failed.".
376                                        format(self._node['host'], cmd))
377                 else:
378                     raise RuntimeError("More instances of VPP running on node "
379                                        "{0}. VAT command {1} execution failed.".
380                                        format(self._node['host'], cmd))
381             else:
382                 raise RuntimeError("VPP not running on node {0}. VAT command "
383                                    "{1} execution failed.".
384                                    format(self._node['host'], cmd))
385
386         logger.debug("VAT output: {0}".format(out))
387         if self.json:
388             obj_start = out.find('{')
389             obj_end = out.rfind('}')
390             array_start = out.find('[')
391             array_end = out.rfind(']')
392
393             if obj_start == -1 and array_start == -1:
394                 raise RuntimeError("VAT command {0}: no JSON data.".format(cmd))
395
396             if obj_start < array_start or array_start == -1:
397                 start = obj_start
398                 end = obj_end + 1
399             else:
400                 start = array_start
401                 end = array_end + 1
402             out = out[start:end]
403             json_out = json.loads(out)
404             return json_out
405         else:
406             return None
407
408     def vat_terminal_close(self):
409         """Close VAT terminal."""
410         # interactive terminal is dead, we only need to close session
411         if not self._exec_failure:
412             try:
413                 self._ssh.interactive_terminal_exec_command(self._tty,
414                                                             'quit',
415                                                             self.__LINUX_PROMPT)
416             except Exception:
417                 vpp_pid = get_vpp_pid(self._node)
418                 if vpp_pid:
419                     if isinstance(vpp_pid, int):
420                         logger.trace("VPP running on node {0}.".
421                                      format(self._node['host']))
422                     else:
423                         logger.error("More instances of VPP running on node "
424                                      "{0}.".format(self._node['host']))
425                 else:
426                     logger.error("VPP not running on node {0}.".
427                                  format(self._node['host']))
428                 raise RuntimeError("Failed to close VAT console on node {0}".
429                                    format(self._node['host']))
430         try:
431             self._ssh.interactive_terminal_close(self._tty)
432         except:
433             raise RuntimeError("Cannot close interactive terminal on node {0}".
434                                format(self._node['host']))
435
436     def vat_terminal_exec_cmd_from_template(self, vat_template_file, **args):
437         """Execute VAT script from a file.
438
439         :param vat_template_file: Template file name of a VAT script.
440         :param args: Dictionary of parameters for VAT script.
441         :return: List of JSON objects returned by VAT.
442         """
443         file_path = '{}/{}'.format(Constants.RESOURCES_TPL_VAT,
444                                    vat_template_file)
445         with open(file_path, 'r') as template_file:
446             cmd_template = template_file.readlines()
447         ret = []
448         for line_tmpl in cmd_template:
449             vat_cmd = line_tmpl.format(**args)
450             ret.append(self.vat_terminal_exec_cmd(vat_cmd.replace('\n', '')))
451         return ret