Align suite/test teardown/setup
[csit.git] / resources / libraries / python / VPPUtil.py
1 # Copyright (c) 2019 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 """VPP util library."""
15
16 import binascii
17
18 from robot.api import logger
19
20 from resources.libraries.python.Constants import Constants
21 from resources.libraries.python.DUTSetup import DUTSetup
22 from resources.libraries.python.PapiExecutor import PapiExecutor
23 from resources.libraries.python.ssh import exec_cmd_no_error
24 from resources.libraries.python.topology import NodeType
25
26
27 class VPPUtil(object):
28     """General class for any VPP related methods/functions."""
29
30     @staticmethod
31     def show_vpp_settings(node, *additional_cmds):
32         """Print default VPP settings. In case others are needed, can be
33         accepted as next parameters (each setting one parameter), preferably
34         in form of a string.
35
36         :param node: VPP node.
37         :param additional_cmds: Additional commands that the vpp should print
38             settings for.
39         :type node: dict
40         :type additional_cmds: tuple
41         """
42         def_setting_tb_displayed = {
43             'IPv6 FIB': 'ip6 fib',
44             'IPv4 FIB': 'ip fib',
45             'Interface IP': 'int addr',
46             'Interfaces': 'int',
47             'ARP': 'ip arp',
48             'Errors': 'err'
49         }
50
51         if additional_cmds:
52             for cmd in additional_cmds:
53                 def_setting_tb_displayed['Custom Setting: {}'.format(cmd)] = cmd
54
55         for _, cmd in def_setting_tb_displayed.items():
56             command = 'vppctl sh {cmd}'.format(cmd=cmd)
57             exec_cmd_no_error(node, command, timeout=30, sudo=True)
58
59     @staticmethod
60     def restart_vpp_service(node):
61         """Restart VPP service on the specified topology node.
62
63         :param node: Topology node.
64         :type node: dict
65         """
66         DUTSetup.restart_service(node, Constants.VPP_UNIT)
67
68     @staticmethod
69     def restart_vpp_service_on_all_duts(nodes):
70         """Restart VPP service on all DUT nodes.
71
72         :param nodes: Topology nodes.
73         :type nodes: dict
74         """
75         for node in nodes.values():
76             if node['type'] == NodeType.DUT:
77                 VPPUtil.restart_vpp_service(node)
78
79     @staticmethod
80     def stop_vpp_service(node):
81         """Stop VPP service on the specified topology node.
82
83         :param node: Topology node.
84         :type node: dict
85         """
86         DUTSetup.stop_service(node, Constants.VPP_UNIT)
87
88     @staticmethod
89     def stop_vpp_service_on_all_duts(nodes):
90         """Stop VPP service on all DUT nodes.
91
92         :param nodes: Topology nodes.
93         :type nodes: dict
94         """
95         for node in nodes.values():
96             if node['type'] == NodeType.DUT:
97                 VPPUtil.stop_vpp_service(node)
98
99     @staticmethod
100     def verify_vpp_installed(node):
101         """Verify that VPP is installed on the specified topology node.
102
103         :param node: Topology node.
104         :type node: dict
105         """
106         cmd = 'command -v vpp'
107         exec_cmd_no_error(
108             node, cmd, message='VPP is not installed!')
109
110     @staticmethod
111     def verify_vpp_started(node):
112         """Verify that VPP is started on the specified topology node.
113
114         :param node: Topology node.
115         :type node: dict
116         """
117         cmd = ('vppctl show pci 2>&1 | '
118                'fgrep -v "Connection refused" | '
119                'fgrep -v "No such file or directory"')
120         exec_cmd_no_error(
121             node, cmd, sudo=True, message='VPP failed to start!', retries=120)
122
123     @staticmethod
124     def verify_vpp(node):
125         """Verify that VPP is installed and started on the specified topology
126         node.
127
128         :param node: Topology node.
129         :type node: dict
130         :raises RuntimeError: If VPP service fails to start.
131         """
132         VPPUtil.verify_vpp_installed(node)
133         try:
134             # Verify responsivness of vppctl.
135             VPPUtil.verify_vpp_started(node)
136             # Verify responsivness of PAPI.
137             VPPUtil.show_log(node)
138         finally:
139             DUTSetup.get_service_logs(node, Constants.VPP_UNIT)
140
141     @staticmethod
142     def verify_vpp_on_all_duts(nodes):
143         """Verify that VPP is installed and started on all DUT nodes.
144
145         :param nodes: Nodes in the topology.
146         :type nodes: dict
147         """
148         for node in nodes.values():
149             if node['type'] == NodeType.DUT:
150                 VPPUtil.verify_vpp(node)
151
152     @staticmethod
153     def vpp_show_version(node, verbose=True):
154         """Run "show_version" PAPI command.
155
156         :param node: Node to run command on.
157         :param verbose: Show version, compile date and compile location if True
158             otherwise show only version.
159         :type node: dict
160         :type verbose: bool
161         :returns: VPP version.
162         :rtype: str
163         """
164         with PapiExecutor(node) as papi_exec:
165             data = papi_exec.add('show_version').get_replies().verify_reply()
166         version = ('VPP version:      {ver}\n'.
167                    format(ver=data['version'].rstrip('\0x00')))
168         if verbose:
169             version += ('Compile date:     {date}\n'
170                         'Compile location: {cl}\n '.
171                         format(date=data['build_date'].rstrip('\0x00'),
172                                cl=data['build_directory'].rstrip('\0x00')))
173         logger.info(version)
174         return data['version'].rstrip('\0x00')
175
176     @staticmethod
177     def show_vpp_version_on_all_duts(nodes):
178         """Show VPP version verbose on all DUTs.
179
180         :param nodes: Nodes in the topology.
181         :type nodes: dict
182         """
183         for node in nodes.values():
184             if node['type'] == NodeType.DUT:
185                 VPPUtil.vpp_show_version(node)
186
187     @staticmethod
188     def vpp_show_interfaces(node):
189         """Run "show interface" CLI command.
190
191         :param node: Node to run command on.
192         :type node: dict
193         """
194
195         cmd = 'sw_interface_dump'
196         cmd_reply = 'sw_interface_details'
197         args = dict(name_filter_valid=0, name_filter='')
198         err_msg = 'Failed to get interface dump on host {host}'.format(
199             host=node['host'])
200         with PapiExecutor(node) as papi_exec:
201             papi_resp = papi_exec.add(cmd, **args).get_replies(err_msg)
202
203         papi_if_dump = papi_resp.reply[0]['api_reply']
204
205         if_data = list()
206         for item in papi_if_dump:
207             data = item[cmd_reply]
208             data['interface_name'] = data['interface_name'].rstrip('\x00')
209             data['tag'] = data['tag'].rstrip('\x00')
210             data['l2_address'] = str(':'.join(binascii.hexlify(
211                 data['l2_address'])[i:i + 2] for i in range(0, 12, 2)).
212                                      decode('ascii'))
213             if_data.append(data)
214         # TODO: return only base data
215         logger.trace('Interface data of host {host}:\n{if_data}'.format(
216             host=node['host'], if_data=if_data))
217
218     @staticmethod
219     def vpp_enable_traces_on_dut(node, fail_on_error=False):
220         """Enable vpp packet traces on the DUT node.
221
222         :param node: DUT node to set up.
223         :param fail_on_error: If True, keyword fails if an error occurs,
224             otherwise passes.
225         :type node: dict
226         :type fail_on_error: bool
227         """
228         cmds = [
229             "trace add dpdk-input 50",
230             "trace add vhost-user-input 50",
231             "trace add memif-input 50"
232         ]
233
234         for cmd in cmds:
235             try:
236                 PapiExecutor.run_cli_cmd(node, cmd)
237             except AssertionError:
238                 if fail_on_error:
239                     raise
240
241     @staticmethod
242     def vpp_enable_traces_on_all_duts(nodes, fail_on_error=False):
243         """Enable vpp packet traces on all DUTs in the given topology.
244
245         :param nodes: Nodes in the topology.
246         :param fail_on_error: If True, keyword fails if an error occurs,
247             otherwise passes.
248         :type nodes: dict
249         :type fail_on_error: bool
250         """
251         for node in nodes.values():
252             if node['type'] == NodeType.DUT:
253                 VPPUtil.vpp_enable_traces_on_dut(node, fail_on_error)
254
255     @staticmethod
256     def vpp_enable_elog_traces_on_dut(node):
257         """Enable API/CLI/Barrier traces on the DUT node.
258
259         :param node: DUT node to set up.
260         :type node: dict
261         """
262         PapiExecutor.run_cli_cmd(node, "elog trace api cli barrier")
263
264     @staticmethod
265     def vpp_enable_elog_traces_on_all_duts(nodes):
266         """Enable API/CLI/Barrier traces on all DUTs in the given topology.
267
268         :param nodes: Nodes in the topology.
269         :type nodes: dict
270         """
271         for node in nodes.values():
272             if node['type'] == NodeType.DUT:
273                 VPPUtil.vpp_enable_elog_traces_on_dut(node)
274
275     @staticmethod
276     def show_event_logger_on_dut(node):
277         """Show event logger on the DUT node.
278
279         :param node: DUT node to show traces on.
280         :type node: dict
281         """
282         PapiExecutor.run_cli_cmd(node, "show event-logger")
283
284     @staticmethod
285     def show_event_logger_on_all_duts(nodes):
286         """Show event logger on all DUTs in the given topology.
287
288         :param nodes: Nodes in the topology.
289         :type nodes: dict
290         """
291         for node in nodes.values():
292             if node['type'] == NodeType.DUT:
293                 VPPUtil.show_event_logger_on_dut(node)
294
295     @staticmethod
296     def show_log(node):
297         """Show log on the specified topology node.
298
299         :param node: Topology node.
300         :type node: dict
301         :returns: VPP log data.
302         :rtype: list
303         """
304         return PapiExecutor.run_cli_cmd(node, "show log")["reply"]
305
306     @staticmethod
307     def vpp_show_threads(node):
308         """Show VPP threads on node.
309
310         :param node: Node to run command on.
311         :type node: dict
312         :returns: VPP thread data.
313         :rtype: list
314         """
315         with PapiExecutor(node) as papi_exec:
316             data = papi_exec.add('show_threads').get_replies().\
317                 verify_reply()["thread_data"]
318
319         threads_data = list()
320         for thread in data:
321             thread_data = list()
322             for item in thread:
323                 if isinstance(item, unicode):
324                     item = item.rstrip('\x00')
325                 thread_data.append(item)
326             threads_data.append(thread_data)
327
328         logger.info("show threads:\n{threads}".format(threads=threads_data))
329
330         return threads_data