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:
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 """Python API executor library."""
19 from paramiko.ssh_exception import SSHException
20 from robot.api import logger
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
28 __all__ = ['PapiExecutor']
31 class PapiExecutor(object):
32 """Contains methods for executing Python API commands on DUTs."""
34 def __init__(self, node):
39 self._json_data = None
40 self._api_reply = list()
45 self._ssh.connect(node)
47 raise SSHException('Cannot open SSH connection to host {host} to '
48 'execute PAPI command(s)'.
49 format(host=self._node['host']))
54 def __exit__(self, exc_type, exc_val, exc_tb):
58 def _process_api_data(api_d):
59 """Process API data for smooth converting to JSON string.
61 Apply binascii.hexlify() method for string values.
63 :param api_d: List of APIs with their arguments.
65 :returns: List of APIs with arguments pre-processed for JSON.
69 api_data_processed = list()
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
83 def _revert_api_reply(api_r):
84 """Process API reply / a part of API reply.
86 Apply binascii.unhexlify() method for unicode values.
88 :param api_r: API reply.
90 :returns: Processed API reply / a part of API reply.
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) \
100 reply_value[a_k] = value
101 reply_dict[reply_key] = reply_value
104 def _process_reply(self, api_reply):
105 """Process API reply.
107 :param api_reply: API reply.
108 :type api_reply: dict or list of dict
109 :returns: Processed API reply.
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))
118 reverted_reply = self._revert_api_reply(api_reply)
119 return reverted_reply
121 def _process_json_data(self):
122 """Process received JSON data."""
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)
131 def execute_papi(self, api_data, timeout=120):
132 """Execute PAPI command(s) on remote node and store the result.
134 :param api_data: List of APIs with their arguments.
135 :param timeout: Timeout in seconds.
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.
146 self._api_data = api_data
147 api_data_processed = self._process_api_data(api_data)
148 json_data = json.dumps(api_data_processed)
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,
156 ret_code, stdout, stderr = self._ssh.exec_command_sudo(
157 cmd=cmd, timeout=timeout)
159 logger.error('PAPI command(s) execution timeout on host {host}:'
160 '\n{apis}'.format(host=self._node['host'],
161 apis=self._api_data))
163 except (PapiInitError, PapiJsonFileError, PapiCommandError,
164 PapiCommandInputError):
165 logger.error('PAPI command(s) execution failed on host {host}'.
166 format(host=self._node['host']))
169 raise RuntimeError('PAPI command(s) execution on host {host} '
170 'failed: {apis}'.format(host=self._node['host'],
171 apis=self._api_data))
173 self._ret_code = ret_code
174 self._stdout = stdout
175 self._stderr = stderr
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.
181 :raises RuntimeError: When no PAPI command executed.
182 :raises AssertionError: If PAPI command(s) execution passed.
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))
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.
196 :raises RuntimeError: When no PAPI command executed.
197 :raises AssertionError: If PAPI command(s) execution failed.
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))
207 def get_papi_stdout(self):
208 """Returns value of stdout from last executed PAPI command(s)."""
212 def get_papi_stderr(self):
213 """Returns value of stderr from last executed PAPI command(s)."""
217 def get_papi_reply(self):
218 """Returns api reply from last executed PAPI command(s)."""
220 self._json_data = json.loads(self._stdout)
221 self._process_json_data()
223 return self._api_reply