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