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