6a47b9497f0d106e6c0db7610cd77b2b4a5d6ac1
[csit.git] / resources / libraries / python / PapiExecutor.py
1 # Copyright (c) 2018 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 """Python API executor library."""
15
16 import binascii
17 import json
18
19 from paramiko.ssh_exception import SSHException
20 from robot.api import logger
21
22 from resources.libraries.python.constants import Constants
23 from resources.libraries.python.PapiErrors import PapiInitError, \
24     PapiJsonFileError, PapiCommandError, PapiCommandInputError
25 # TODO: from resources.libraries.python.PapiHistory import PapiHistory
26 from resources.libraries.python.ssh import SSH, SSHTimeout
27
28 __all__ = ['PapiExecutor']
29
30
31 class PapiExecutor(object):
32     """Contains methods for executing Python API commands on DUTs."""
33
34     def __init__(self, node):
35         self._stdout = None
36         self._stderr = None
37         self._ret_code = None
38         self._node = node
39         self._json_data = None
40         self._api_reply = list()
41         self._api_data = None
42
43         self._ssh = SSH()
44         try:
45             self._ssh.connect(node)
46         except:
47             raise SSHException('Cannot open SSH connection to host {host} to '
48                                'execute PAPI command(s)'.
49                                format(host=self._node['host']))
50
51     def __enter__(self):
52         return self
53
54     def __exit__(self, exc_type, exc_val, exc_tb):
55         pass
56
57     @staticmethod
58     def _process_api_data(api_d):
59         """Process API data for smooth converting to JSON string.
60
61         Apply binascii.hexlify() method for string values.
62
63         :param api_d: List of APIs with their arguments.
64         :type api_d: list
65         :returns: List of APIs with arguments pre-processed for JSON.
66         :rtype: list
67         """
68
69         api_data_processed = list()
70         for api in api_d:
71             api_name = api['api_name']
72             api_args = api['api_args']
73             api_processed = dict(api_name=api_name)
74             api_args_processed = dict()
75             for a_k, a_v in api_args.iteritems():
76                 value = binascii.hexlify(a_v) if isinstance(a_v, str) else a_v
77                 api_args_processed[str(a_k)] = value
78             api_processed['api_args'] = api_args_processed
79             api_data_processed.append(api_processed)
80         return api_data_processed
81
82     @staticmethod
83     def _revert_api_reply(api_r):
84         """Process API reply / a part of API reply.
85
86         Apply binascii.unhexlify() method for unicode values.
87
88         :param api_r: API reply.
89         :type api_r: dict
90         :returns: Processed API reply / a part of API reply.
91         :rtype: dict
92         """
93
94         reply_dict = dict()
95         reply_value = dict()
96         for reply_key, reply_v in api_r.iteritems():
97             for a_k, a_v in reply_v.iteritems():
98                 value = binascii.unhexlify(a_v) if isinstance(a_v, unicode) \
99                     else a_v
100                 reply_value[a_k] = value
101             reply_dict[reply_key] = reply_value
102         return reply_dict
103
104     def _process_reply(self, api_reply):
105         """Process API reply.
106
107         :param api_reply: API reply.
108         :type api_reply: dict or list of dict
109         :returns: Processed API reply.
110         :rtype: list or dict
111         """
112
113         if isinstance(api_reply, list):
114             reverted_reply = list()
115             for a_r in api_reply:
116                 reverted_reply.append(self._revert_api_reply(a_r))
117         else:
118             reverted_reply = self._revert_api_reply(api_reply)
119         return reverted_reply
120
121     def _process_json_data(self):
122         """Process received JSON data."""
123
124         for data in self._json_data:
125             api_name = data['api_name']
126             api_reply = data['api_reply']
127             api_reply_processed = dict(
128                 api_name=api_name, api_reply=self._process_reply(api_reply))
129             self._api_reply.append(api_reply_processed)
130
131     def execute_papi(self, api_data, timeout=120):
132         """Execute PAPI command(s) on remote node and store the result.
133
134         :param api_data: List of APIs with their arguments.
135         :param timeout: Timeout in seconds.
136         :type api_data: list
137         :type timeout: int
138         :raises SSHTimeout: If PAPI command(s) execution is timed out.
139         :raises PapiInitError: If PAPI initialization failed.
140         :raises PapiJsonFileError: If no api.json file found.
141         :raises PapiCommandError: If PAPI command(s) execution failed.
142         :raises PapiCommandInputError: If invalid attribute name or invalid
143             value is used in API call.
144         :raises RuntimeError: If PAPI executor failed due to another reason.
145         """
146         self._api_data = api_data
147         api_data_processed = self._process_api_data(api_data)
148         json_data = json.dumps(api_data_processed)
149
150         cmd = "python {fw_dir}/{papi_provider} --json_data '{json}'".format(
151             fw_dir=Constants.REMOTE_FW_DIR,
152             papi_provider=Constants.RESOURCES_PAPI_PROVIDER,
153             json=json_data)
154
155         try:
156             ret_code, stdout, stderr = self._ssh.exec_command_sudo(
157                 cmd=cmd, timeout=timeout)
158         except SSHTimeout:
159             logger.error('PAPI command(s) execution timeout on host {host}:'
160                          '\n{apis}'.format(host=self._node['host'],
161                                            apis=self._api_data))
162             raise
163         except (PapiInitError, PapiJsonFileError, PapiCommandError,
164                 PapiCommandInputError):
165             logger.error('PAPI command(s) execution failed on host {host}'.
166                          format(host=self._node['host']))
167             raise
168         except:
169             raise RuntimeError('PAPI command(s) execution on host {host} '
170                                'failed: {apis}'.format(host=self._node['host'],
171                                                        apis=self._api_data))
172
173         self._ret_code = ret_code
174         self._stdout = stdout
175         self._stderr = stderr
176
177     def papi_should_have_failed(self):
178         """Read return code from last executed script and raise exception if the
179         PAPI command(s) didn't fail.
180
181         :raises RuntimeError: When no PAPI command executed.
182         :raises AssertionError: If PAPI command(s) execution passed.
183         """
184
185         if self._ret_code is None:
186             raise RuntimeError("First execute the PAPI command(s)!")
187         if self._ret_code == 0:
188             raise AssertionError(
189                 "PAPI command(s) execution passed, but failure was expected: "
190                 "{apis}".format(apis=self._api_data))
191
192     def papi_should_have_passed(self):
193         """Read return code from last executed script and raise exception if the
194         PAPI command(s) failed.
195
196         :raises RuntimeError: When no PAPI command executed.
197         :raises AssertionError: If PAPI command(s) execution failed.
198         """
199
200         if self._ret_code is None:
201             raise RuntimeError("First execute the PAPI command(s)!")
202         if self._ret_code != 0:
203             raise AssertionError(
204                 "PAPI command(s) execution failed, but success was expected: "
205                 "{apis}".format(apis=self._api_data))
206
207     def get_papi_stdout(self):
208         """Returns value of stdout from last executed PAPI command(s)."""
209
210         return self._stdout
211
212     def get_papi_stderr(self):
213         """Returns value of stderr from last executed PAPI command(s)."""
214
215         return self._stderr
216
217     def get_papi_reply(self):
218         """Returns api reply from last executed PAPI command(s)."""
219
220         self._json_data = json.loads(self._stdout)
221         self._process_json_data()
222
223         return self._api_reply