Line length: Fix recent merges
[csit.git] / resources / libraries / python / VPPUtil.py
1 # Copyright (c) 2021 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, exec_cmd
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         Disconnect possibly connected PAPI executor.
62
63         :param node: Topology node.
64         :param node_key: Topology node key.
65         :type node: dict
66         :type node_key: str
67         """
68         # Containers have a separate lifecycle, but better be safe.
69         PapiSocketExecutor.disconnect_all_sockets_by_node(node)
70         DUTSetup.restart_service(node, Constants.VPP_UNIT)
71         if node_key:
72             Topology.add_new_socket(
73                 node, SocketType.PAPI, node_key, Constants.SOCKSVR_PATH)
74             Topology.add_new_socket(
75                 node, SocketType.STATS, node_key, Constants.SOCKSTAT_PATH)
76
77     @staticmethod
78     def restart_vpp_service_on_all_duts(nodes):
79         """Restart VPP service on all DUT nodes.
80
81         :param nodes: Topology nodes.
82         :type nodes: dict
83         """
84         for node_key, node in nodes.items():
85             if node[u"type"] == NodeType.DUT:
86                 VPPUtil.restart_vpp_service(node, node_key)
87
88     @staticmethod
89     def stop_vpp_service(node, node_key=None):
90         """Stop VPP service on the specified topology node.
91
92         Disconnect possibly connected PAPI executor.
93
94         :param node: Topology node.
95         :param node_key: Topology node key.
96         :type node: dict
97         :type node_key: str
98         """
99         # Containers have a separate lifecycle, but better be safe.
100         PapiSocketExecutor.disconnect_all_sockets_by_node(node)
101         DUTSetup.stop_service(node, Constants.VPP_UNIT)
102         if node_key:
103             Topology.del_node_socket_id(node, SocketType.PAPI, node_key)
104             Topology.del_node_socket_id(node, SocketType.STATS, node_key)
105
106     @staticmethod
107     def stop_vpp_service_on_all_duts(nodes):
108         """Stop VPP service on all DUT nodes.
109
110         :param nodes: Topology nodes.
111         :type nodes: dict
112         """
113         for node_key, node in nodes.items():
114             if node[u"type"] == NodeType.DUT:
115                 VPPUtil.stop_vpp_service(node, node_key)
116
117     @staticmethod
118     def verify_vpp_installed(node):
119         """Verify that VPP is installed on the specified topology node.
120
121         :param node: Topology node.
122         :type node: dict
123         """
124         DUTSetup.verify_program_installed(node, u"vpp")
125
126     @staticmethod
127     def adjust_privileges(node):
128         """Adjust privileges to control VPP without sudo.
129
130         :param node: Topology node.
131         :type node: dict
132         """
133         cmd = u"chmod -R o+rwx /run/vpp"
134         exec_cmd_no_error(
135             node, cmd, sudo=True, message=u"Failed to adjust privileges!",
136             retries=120)
137
138     @staticmethod
139     def verify_vpp_started(node):
140         """Verify that VPP is started on the specified topology node.
141
142         :param node: Topology node.
143         :type node: dict
144         """
145         cmd = u"echo \"show pci\" | sudo socat - UNIX-CONNECT:/run/vpp/cli.sock"
146         exec_cmd_no_error(
147             node, cmd, sudo=False, message=u"VPP failed to start!", retries=120
148         )
149
150         cmd = u"vppctl show pci 2>&1 | fgrep -v \"Connection refused\" | " \
151               u"fgrep -v \"No such file or directory\""
152         exec_cmd_no_error(
153             node, cmd, sudo=True, message=u"VPP failed to start!", retries=120
154         )
155
156         # Properly enable cards in case they were disabled. This will be
157         # followed in https://jira.fd.io/browse/VPP-1934.
158         cmd = u"for i in $(sudo vppctl sho int | grep Eth | cut -d' ' -f1); do"\
159               u" sudo vppctl set int sta $i up; done"
160         exec_cmd(node, cmd, sudo=False)
161
162     @staticmethod
163     def verify_vpp(node):
164         """Verify that VPP is installed and started on the specified topology
165         node. Adjust privileges so user can connect without sudo.
166
167         :param node: Topology node.
168         :type node: dict
169         :raises RuntimeError: If VPP service fails to start.
170         """
171         DUTSetup.verify_program_installed(node, 'vpp')
172         try:
173             # Verify responsiveness of vppctl.
174             VPPUtil.verify_vpp_started(node)
175             # Adjust privileges.
176             VPPUtil.adjust_privileges(node)
177             # Verify responsiveness of PAPI.
178             VPPUtil.show_log(node)
179             VPPUtil.vpp_show_version(node)
180         finally:
181             DUTSetup.get_service_logs(node, Constants.VPP_UNIT)
182
183     @staticmethod
184     def verify_vpp_on_all_duts(nodes):
185         """Verify that VPP is installed and started on all DUT nodes.
186
187         :param nodes: Nodes in the topology.
188         :type nodes: dict
189         """
190         for node in nodes.values():
191             if node[u"type"] == NodeType.DUT:
192                 VPPUtil.verify_vpp(node)
193
194     @staticmethod
195     def vpp_show_version(
196             node, remote_vpp_socket=Constants.SOCKSVR_PATH, log=True):
197         """Run "show_version" PAPI command.
198
199         Socket is configurable, so VPP inside container can be accessed.
200
201         :param node: Node to run command on.
202         :param remote_vpp_socket: Path to remote socket to target VPP.
203         :param log: If true, show the result in Robot log.
204         :type node: dict
205         :type remote_vpp_socket: str
206         :type log: bool
207         :returns: VPP version.
208         :rtype: str
209         :raises RuntimeError: If PAPI connection fails.
210         :raises AssertionError: If PAPI retcode is nonzero.
211         """
212         cmd = u"show_version"
213         with PapiSocketExecutor(node, remote_vpp_socket) as papi_exec:
214             reply = papi_exec.add(cmd).get_reply()
215         if log:
216             logger.info(f"VPP version: {reply[u'version']}\n")
217         return f"{reply[u'version']}"
218
219     @staticmethod
220     def show_vpp_version_on_all_duts(nodes):
221         """Show VPP version verbose on all DUTs.
222
223         :param nodes: Nodes in the topology.
224         :type nodes: dict
225         """
226         for node in nodes.values():
227             if node[u"type"] == NodeType.DUT:
228                 VPPUtil.vpp_show_version(node)
229
230     @staticmethod
231     def vpp_show_interfaces(node):
232         """Run "show interface" CLI command.
233
234         :param node: Node to run command on.
235         :type node: dict
236         """
237
238         cmd = u"sw_interface_dump"
239         args = dict(
240             name_filter_valid=False,
241             name_filter=u""
242         )
243         err_msg = f"Failed to get interface dump on host {node[u'host']}"
244         with PapiSocketExecutor(node) as papi_exec:
245             details = papi_exec.add(cmd, **args).get_details(err_msg)
246
247         for if_dump in details:
248             if_dump[u"l2_address"] = str(if_dump[u"l2_address"])
249             if_dump[u"b_dmac"] = str(if_dump[u"b_dmac"])
250             if_dump[u"b_smac"] = str(if_dump[u"b_smac"])
251             if_dump[u"flags"] = if_dump[u"flags"].value
252             if_dump[u"type"] = if_dump[u"type"].value
253             if_dump[u"link_duplex"] = if_dump[u"link_duplex"].value
254             if_dump[u"sub_if_flags"] = if_dump[u"sub_if_flags"].value \
255                 if hasattr(if_dump[u"sub_if_flags"], u"value") \
256                 else int(if_dump[u"sub_if_flags"])
257         # TODO: return only base data
258         logger.trace(f"Interface data of host {node[u'host']}:\n{details}")
259
260     @staticmethod
261     def vpp_enable_traces_on_dut(node, fail_on_error=False):
262         """Enable vpp packet traces on the DUT node.
263
264         :param node: DUT node to set up.
265         :param fail_on_error: If True, keyword fails if an error occurs,
266             otherwise passes.
267         :type node: dict
268         :type fail_on_error: bool
269         """
270         cmds = [
271             u"trace add dpdk-input 50",
272             u"trace add vhost-user-input 50",
273             u"trace add memif-input 50",
274             u"trace add avf-input 50"
275         ]
276
277         for cmd in cmds:
278             try:
279                 PapiSocketExecutor.run_cli_cmd_on_all_sockets(node, cmd)
280             except AssertionError:
281                 if fail_on_error:
282                     raise
283
284     @staticmethod
285     def vpp_enable_traces_on_all_duts(nodes, fail_on_error=False):
286         """Enable vpp packet traces on all DUTs in the given topology.
287
288         :param nodes: Nodes in the topology.
289         :param fail_on_error: If True, keyword fails if an error occurs,
290             otherwise passes.
291         :type nodes: dict
292         :type fail_on_error: bool
293         """
294         for node in nodes.values():
295             if node[u"type"] == NodeType.DUT:
296                 VPPUtil.vpp_enable_traces_on_dut(node, fail_on_error)
297
298     @staticmethod
299     def vpp_enable_elog_traces(node):
300         """Enable API/CLI/Barrier traces on the specified topology node.
301
302         :param node: Topology node.
303         :type node: dict
304         """
305         try:
306             PapiSocketExecutor.run_cli_cmd_on_all_sockets(
307                 node, u"event-logger trace api cli barrier")
308         except AssertionError:
309             # Perhaps an older VPP build is tested.
310             PapiSocketExecutor.run_cli_cmd_on_all_sockets(
311                 node, u"elog trace api cli barrier")
312
313     @staticmethod
314     def vpp_enable_elog_traces_on_all_duts(nodes):
315         """Enable API/CLI/Barrier traces on all DUTs in the given topology.
316
317         :param nodes: Nodes in the topology.
318         :type nodes: dict
319         """
320         for node in nodes.values():
321             if node[u"type"] == NodeType.DUT:
322                 VPPUtil.vpp_enable_elog_traces(node)
323
324     @staticmethod
325     def show_event_logger(node):
326         """Show event logger on the specified topology node.
327
328         :param node: Topology node.
329         :type node: dict
330         """
331         PapiSocketExecutor.run_cli_cmd_on_all_sockets(
332             node, u"show event-logger")
333
334     @staticmethod
335     def show_event_logger_on_all_duts(nodes):
336         """Show event logger on all DUTs in the given topology.
337
338         :param nodes: Nodes in the topology.
339         :type nodes: dict
340         """
341         for node in nodes.values():
342             if node[u"type"] == NodeType.DUT:
343                 VPPUtil.show_event_logger(node)
344
345     @staticmethod
346     def show_log(node):
347         """Show logging on the specified topology node.
348
349         :param node: Topology node.
350         :type node: dict
351         """
352         PapiSocketExecutor.run_cli_cmd(node, u"show logging")
353
354     @staticmethod
355     def show_log_on_all_duts(nodes):
356         """Show logging on all DUTs in the given topology.
357
358         :param nodes: Nodes in the topology.
359         :type nodes: dict
360         """
361         for node in nodes.values():
362             if node[u"type"] == NodeType.DUT:
363                 VPPUtil.show_log(node)
364
365     @staticmethod
366     def vpp_show_threads(node):
367         """Show VPP threads on node.
368
369         :param node: Node to run command on.
370         :type node: dict
371         :returns: VPP thread data.
372         :rtype: list
373         """
374         cmd = u"show_threads"
375         with PapiSocketExecutor(node) as papi_exec:
376             reply = papi_exec.add(cmd).get_reply()
377
378         threads_data = reply[u"thread_data"]
379         logger.trace(f"show threads:\n{threads_data}")
380
381         return threads_data
382
383     @staticmethod
384     def vpp_add_graph_node_next(node, graph_node_name, graph_next_name):
385         """Set the next node for a given node.
386
387         :param node: Node to run command on.
388         :param graph_node_name: Graph node to add the next node on.
389         :param graph_next_name: Graph node to add as the next node.
390         :type node: dict
391         :type graph_node_name: str
392         :type graph_next_name: str
393         :returns: The index of the next graph node.
394         :rtype: int
395         """
396         cmd = u"add_node_next"
397         args = dict(
398             node_name=graph_node_name,
399             next_name=graph_next_name
400         )
401         with PapiSocketExecutor(node) as papi_exec:
402             reply = papi_exec.add(cmd, **args).get_reply()
403
404         return reply[u"next_index"]