Hoststack perf infrastructure refactoring
[csit.git] / resources / libraries / python / VPPUtil.py
1 # Copyright (c) 2020 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 Topology, SocketType, NodeType
23
24
25 class VPPUtil:
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             u"IPv6 FIB": u"ip6 fib",
42             u"IPv4 FIB": u"ip fib",
43             u"Interface IP": u"int addr",
44             u"Interfaces": u"int",
45             u"ARP": u"ip arp",
46             u"Errors": u"err"
47         }
48
49         if additional_cmds:
50             for cmd in additional_cmds:
51                 def_setting_tb_displayed[f"Custom Setting: {cmd}"] = cmd
52
53         for _, cmd in def_setting_tb_displayed.items():
54             command = f"vppctl sh {cmd}"
55             exec_cmd_no_error(node, command, timeout=30, sudo=True)
56
57     @staticmethod
58     def restart_vpp_service(node, node_key=None):
59         """Restart VPP service on the specified topology node.
60
61         :param node: Topology node.
62         :param node_key: Topology node key.
63         :type node: dict
64         :type node_key: str
65         """
66         DUTSetup.restart_service(node, Constants.VPP_UNIT)
67         if node_key:
68             Topology.add_new_socket(
69                 node, SocketType.PAPI, node_key, Constants.SOCKSVR_PATH)
70             Topology.add_new_socket(
71                 node, SocketType.STATS, node_key, Constants.SOCKSTAT_PATH)
72
73     @staticmethod
74     def restart_vpp_service_on_all_duts(nodes):
75         """Restart VPP service on all DUT nodes.
76
77         :param nodes: Topology nodes.
78         :type nodes: dict
79         """
80         for node_key, node in nodes.items():
81             if node[u"type"] == NodeType.DUT:
82                 VPPUtil.restart_vpp_service(node, node_key)
83
84     @staticmethod
85     def stop_vpp_service(node, node_key=None):
86         """Stop VPP service on the specified topology node.
87
88         :param node: Topology node.
89         :param node_key: Topology node key.
90         :type node: dict
91         :type node_key: str
92         """
93         DUTSetup.stop_service(node, Constants.VPP_UNIT)
94         if node_key:
95             Topology.del_node_socket_id(node, SocketType.PAPI, node_key)
96             Topology.del_node_socket_id(node, SocketType.STATS, node_key)
97
98     @staticmethod
99     def stop_vpp_service_on_all_duts(nodes):
100         """Stop VPP service on all DUT nodes.
101
102         :param nodes: Topology nodes.
103         :type nodes: dict
104         """
105         for node_key, node in nodes.items():
106             if node[u"type"] == NodeType.DUT:
107                 VPPUtil.stop_vpp_service(node, node_key)
108
109     @staticmethod
110     def verify_vpp_installed(node):
111         """Verify that VPP is installed on the specified topology node.
112
113         :param node: Topology node.
114         :type node: dict
115         """
116         DUTSetup.verify_program_installed(node, u"vpp")
117
118     @staticmethod
119     def adjust_privileges(node):
120         """Adjust privileges to control VPP without sudo.
121
122         :param node: Topology node.
123         :type node: dict
124         """
125         cmd = u"chmod -R o+rwx /run/vpp"
126         exec_cmd_no_error(
127             node, cmd, sudo=True, message=u"Failed to adjust privileges!",
128             retries=120)
129
130     @staticmethod
131     def verify_vpp_started(node):
132         """Verify that VPP is started on the specified topology node.
133
134         :param node: Topology node.
135         :type node: dict
136         """
137         cmd = u"echo \"show ver\" | sudo socat - UNIX-CONNECT:/run/vpp/cli.sock"
138         exec_cmd_no_error(
139             node, cmd, sudo=False, message=u"VPP failed to start!", retries=120
140         )
141
142         cmd = u"vppctl show ver 2>&1 | fgrep -v \"Connection refused\" | " \
143               u"fgrep -v \"No such file or directory\""
144         exec_cmd_no_error(
145             node, cmd, sudo=True, message=u"VPP failed to start!", retries=120
146         )
147
148     @staticmethod
149     def verify_vpp(node):
150         """Verify that VPP is installed and started on the specified topology
151         node. Adjust privileges so user can connect without sudo.
152
153         :param node: Topology node.
154         :type node: dict
155         :raises RuntimeError: If VPP service fails to start.
156         """
157         DUTSetup.verify_program_installed(node, 'vpp')
158         try:
159             # Verify responsiveness of vppctl.
160             VPPUtil.verify_vpp_started(node)
161             # Adjust privileges.
162             VPPUtil.adjust_privileges(node)
163             # Verify responsiveness of PAPI.
164             VPPUtil.show_log(node)
165             VPPUtil.vpp_show_version(node)
166         finally:
167             DUTSetup.get_service_logs(node, Constants.VPP_UNIT)
168
169     @staticmethod
170     def verify_vpp_on_all_duts(nodes):
171         """Verify that VPP is installed and started on all DUT nodes.
172
173         :param nodes: Nodes in the topology.
174         :type nodes: dict
175         """
176         for node in nodes.values():
177             if node[u"type"] == NodeType.DUT:
178                 VPPUtil.verify_vpp(node)
179
180     @staticmethod
181     def vpp_show_version(node):
182         """Run "show_version" PAPI command.
183
184         :param node: Node to run command on.
185         :type node: dict
186         :returns: VPP version.
187         :rtype: str
188         """
189         cmd = u"show_version"
190         with PapiSocketExecutor(node) as papi_exec:
191             reply = papi_exec.add(cmd).get_reply()
192         logger.info(f"VPP version: {reply[u'version']}\n")
193         return f"{reply[u'version']}"
194
195     @staticmethod
196     def show_vpp_version_on_all_duts(nodes):
197         """Show VPP version verbose on all DUTs.
198
199         :param nodes: Nodes in the topology.
200         :type nodes: dict
201         """
202         for node in nodes.values():
203             if node[u"type"] == NodeType.DUT:
204                 VPPUtil.vpp_show_version(node)
205
206     @staticmethod
207     def vpp_show_interfaces(node):
208         """Run "show interface" CLI command.
209
210         :param node: Node to run command on.
211         :type node: dict
212         """
213
214         cmd = u"sw_interface_dump"
215         args = dict(
216             name_filter_valid=False,
217             name_filter=u""
218         )
219         err_msg = f"Failed to get interface dump on host {node[u'host']}"
220         with PapiSocketExecutor(node) as papi_exec:
221             details = papi_exec.add(cmd, **args).get_details(err_msg)
222
223         for if_dump in details:
224             if_dump[u"l2_address"] = str(if_dump[u"l2_address"])
225             if_dump[u"b_dmac"] = str(if_dump[u"b_dmac"])
226             if_dump[u"b_smac"] = str(if_dump[u"b_smac"])
227             if_dump[u"flags"] = if_dump[u"flags"].value
228             if_dump[u"type"] = if_dump[u"type"].value
229             if_dump[u"link_duplex"] = if_dump[u"link_duplex"].value
230             if_dump[u"sub_if_flags"] = if_dump[u"sub_if_flags"].value \
231                 if hasattr(if_dump[u"sub_if_flags"], u"value") \
232                 else int(if_dump[u"sub_if_flags"])
233         # TODO: return only base data
234         logger.trace(f"Interface data of host {node[u'host']}:\n{details}")
235
236     @staticmethod
237     def vpp_enable_traces_on_dut(node, fail_on_error=False):
238         """Enable vpp packet traces on the DUT node.
239
240         :param node: DUT node to set up.
241         :param fail_on_error: If True, keyword fails if an error occurs,
242             otherwise passes.
243         :type node: dict
244         :type fail_on_error: bool
245         """
246         cmds = [
247             u"trace add dpdk-input 50",
248             u"trace add vhost-user-input 50",
249             u"trace add memif-input 50",
250             u"trace add avf-input 50"
251         ]
252
253         for cmd in cmds:
254             try:
255                 PapiSocketExecutor.run_cli_cmd_on_all_sockets(node, cmd)
256             except AssertionError:
257                 if fail_on_error:
258                     raise
259
260     @staticmethod
261     def vpp_enable_traces_on_all_duts(nodes, fail_on_error=False):
262         """Enable vpp packet traces on all DUTs in the given topology.
263
264         :param nodes: Nodes in the topology.
265         :param fail_on_error: If True, keyword fails if an error occurs,
266             otherwise passes.
267         :type nodes: dict
268         :type fail_on_error: bool
269         """
270         for node in nodes.values():
271             if node[u"type"] == NodeType.DUT:
272                 VPPUtil.vpp_enable_traces_on_dut(node, fail_on_error)
273
274     @staticmethod
275     def vpp_enable_elog_traces(node):
276         """Enable API/CLI/Barrier traces on the specified topology node.
277
278         :param node: Topology node.
279         :type node: dict
280         """
281         PapiSocketExecutor.run_cli_cmd_on_all_sockets(
282             node, u"elog trace api cli barrier")
283
284     @staticmethod
285     def vpp_enable_elog_traces_on_all_duts(nodes):
286         """Enable API/CLI/Barrier traces 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[u"type"] == NodeType.DUT:
293                 VPPUtil.vpp_enable_elog_traces(node)
294
295     @staticmethod
296     def show_event_logger(node):
297         """Show event logger on the specified topology node.
298
299         :param node: Topology node.
300         :type node: dict
301         """
302         PapiSocketExecutor.run_cli_cmd_on_all_sockets(
303             node, u"show event-logger")
304
305     @staticmethod
306     def show_event_logger_on_all_duts(nodes):
307         """Show event logger on all DUTs in the given topology.
308
309         :param nodes: Nodes in the topology.
310         :type nodes: dict
311         """
312         for node in nodes.values():
313             if node[u"type"] == NodeType.DUT:
314                 VPPUtil.show_event_logger(node)
315
316     @staticmethod
317     def show_log(node):
318         """Show logging on the specified topology node.
319
320         :param node: Topology node.
321         :type node: dict
322         """
323         PapiSocketExecutor.run_cli_cmd(node, u"show logging")
324
325     @staticmethod
326     def show_log_on_all_duts(nodes):
327         """Show logging on all DUTs in the given topology.
328
329         :param nodes: Nodes in the topology.
330         :type nodes: dict
331         """
332         for node in nodes.values():
333             if node[u"type"] == NodeType.DUT:
334                 VPPUtil.show_log(node)
335
336     @staticmethod
337     def vpp_show_threads(node):
338         """Show VPP threads on node.
339
340         :param node: Node to run command on.
341         :type node: dict
342         :returns: VPP thread data.
343         :rtype: list
344         """
345         cmd = u"show_threads"
346         with PapiSocketExecutor(node) as papi_exec:
347             reply = papi_exec.add(cmd).get_reply()
348
349         threads_data = list()
350         for thread in reply[u"thread_data"]:
351             thread_data = list()
352             for item in thread:
353                 if isinstance(item, str):
354                     item = item.rstrip('\x00')
355                 thread_data.append(item)
356             threads_data.append(thread_data)
357
358         logger.trace(f"show threads:\n{threads_data}")
359
360         return threads_data