Use PapiSocketProvider for most PAPI calls
[csit.git] / resources / libraries / python / VppCounters.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 counters utilities library."""
15
16 import time
17
18 from pprint import pformat
19
20 from robot.api import logger
21 from resources.libraries.python.PapiExecutor import PapiExecutor
22 from resources.libraries.python.PapiExecutor import PapiSocketExecutor
23 from resources.libraries.python.topology import NodeType, Topology
24
25
26 class VppCounters(object):
27     """VPP counters utilities."""
28
29     def __init__(self):
30         self._stats_table = None
31
32     @staticmethod
33     def _get_non_zero_items(data):
34         """Extract and return non-zero items from the input data.
35
36         :param data: Data to filter.
37         :type data: dict
38         :returns: Dictionary with non-zero items.
39         :rtype dict
40         """
41         return {k: data[k] for k in data.keys() if sum(data[k])}
42
43     @staticmethod
44     def vpp_show_errors(node):
45         """Run "show errors" debug CLI command.
46
47         :param node: Node to run command on.
48         :type node: dict
49         """
50         PapiSocketExecutor.run_cli_cmd(node, 'show errors')
51
52     @staticmethod
53     def vpp_show_errors_verbose(node):
54         """Run "show errors verbose" debug CLI command.
55
56         :param node: Node to run command on.
57         :type node: dict
58         """
59         PapiSocketExecutor.run_cli_cmd(node, 'show errors verbose')
60
61     @staticmethod
62     def vpp_show_errors_on_all_duts(nodes, verbose=False):
63         """Show errors on all DUTs.
64
65         :param nodes: VPP nodes.
66         :param verbose: If True show verbose output.
67         :type nodes: dict
68         :type verbose: bool
69         """
70         for node in nodes.values():
71             if node['type'] == NodeType.DUT:
72                 if verbose:
73                     VppCounters.vpp_show_errors_verbose(node)
74                 else:
75                     VppCounters.vpp_show_errors(node)
76
77     @staticmethod
78     def vpp_show_runtime(node, log_zeros=False):
79         """Run "show runtime" CLI command.
80
81         :param node: Node to run command on.
82         :param log_zeros: Log also items with zero values.
83         :type node: dict
84         :type log_zeros: bool
85         """
86         args = dict(path='^/sys/node')
87         with PapiExecutor(node) as papi_exec:
88             stats = papi_exec.add("vpp-stats", **args).get_stats()[0]
89             # TODO: Introduce get_stat?
90
91         names = stats['/sys/node/names']
92
93         if not names:
94             return
95
96         runtime = []
97         runtime_non_zero = []
98
99         for name in names:
100             runtime.append({'name': name})
101
102         for idx, runtime_item in enumerate(runtime):
103
104             calls_th = []
105             for thread in stats['/sys/node/calls']:
106                 calls_th.append(thread[idx])
107             runtime_item["calls"] = calls_th
108
109             vectors_th = []
110             for thread in stats['/sys/node/vectors']:
111                 vectors_th.append(thread[idx])
112             runtime_item["vectors"] = vectors_th
113
114             suspends_th = []
115             for thread in stats['/sys/node/suspends']:
116                 suspends_th.append(thread[idx])
117             runtime_item["suspends"] = suspends_th
118
119             clocks_th = []
120             for thread in stats['/sys/node/clocks']:
121                 clocks_th.append(thread[idx])
122             runtime_item["clocks"] = clocks_th
123
124             if (sum(calls_th) or sum(vectors_th) or
125                     sum(suspends_th) or sum(clocks_th)):
126                 runtime_non_zero.append(runtime_item)
127
128         if log_zeros:
129             logger.info("Runtime:\n{runtime}".format(
130                 runtime=pformat(runtime)))
131         else:
132             logger.info("Runtime:\n{runtime}".format(
133                 runtime=pformat(runtime_non_zero)))
134
135     @staticmethod
136     def vpp_show_runtime_verbose(node):
137         """Run "show runtime verbose" CLI command.
138
139         TODO: Remove?
140               Only verbose output is possible to get using VPPStats.
141
142         :param node: Node to run command on.
143         :type node: dict
144         """
145         VppCounters.vpp_show_runtime(node)
146
147     @staticmethod
148     def show_runtime_counters_on_all_duts(nodes):
149         """Clear VPP runtime counters on all DUTs.
150
151         :param nodes: VPP nodes.
152         :type nodes: dict
153         """
154         for node in nodes.values():
155             if node['type'] == NodeType.DUT:
156                 VppCounters.vpp_show_runtime(node)
157
158     @staticmethod
159     def vpp_show_hardware_detail(node):
160         """Run "show hardware-interfaces detail" debug CLI command.
161
162         :param node: Node to run command on.
163         :type node: dict
164         """
165         PapiSocketExecutor.run_cli_cmd(node, 'show hardware detail')
166
167     @staticmethod
168     def vpp_clear_runtime(node):
169         """Run "clear runtime" CLI command.
170
171         :param node: Node to run command on.
172         :type node: dict
173         :returns: Verified data from PAPI response.
174         :rtype: dict
175         """
176         return PapiSocketExecutor.run_cli_cmd(node, 'clear runtime', log=False)
177
178     @staticmethod
179     def clear_runtime_counters_on_all_duts(nodes):
180         """Run "clear runtime" CLI command on all DUTs.
181
182         :param nodes: VPP nodes.
183         :type nodes: dict
184         """
185         for node in nodes.values():
186             if node['type'] == NodeType.DUT:
187                 VppCounters.vpp_clear_runtime(node)
188
189     @staticmethod
190     def vpp_clear_interface_counters(node):
191         """Run "clear interfaces" CLI command.
192
193         :param node: Node to run command on.
194         :type node: dict
195         :returns: Verified data from PAPI response.
196         :rtype: dict
197         """
198         return PapiSocketExecutor.run_cli_cmd(
199             node, 'clear interfaces', log=False)
200
201     @staticmethod
202     def clear_interface_counters_on_all_duts(nodes):
203         """Clear interface counters on all DUTs.
204
205         :param nodes: VPP nodes.
206         :type nodes: dict
207         """
208         for node in nodes.values():
209             if node['type'] == NodeType.DUT:
210                 VppCounters.vpp_clear_interface_counters(node)
211
212     @staticmethod
213     def vpp_clear_hardware_counters(node):
214         """Run "clear hardware" CLI command.
215
216         :param node: Node to run command on.
217         :type node: dict
218         :returns: Verified data from PAPI response.
219         :rtype: dict
220         """
221         return PapiSocketExecutor.run_cli_cmd(node, 'clear hardware', log=False)
222
223     @staticmethod
224     def clear_hardware_counters_on_all_duts(nodes):
225         """Clear hardware counters on all DUTs.
226
227         :param nodes: VPP nodes.
228         :type nodes: dict
229         """
230         for node in nodes.values():
231             if node['type'] == NodeType.DUT:
232                 VppCounters.vpp_clear_hardware_counters(node)
233
234     @staticmethod
235     def vpp_clear_errors_counters(node):
236         """Run "clear errors" CLI command.
237
238         :param node: Node to run command on.
239         :type node: dict
240         :returns: Verified data from PAPI response.
241         :rtype: dict
242         """
243         return PapiSocketExecutor.run_cli_cmd(node, 'clear errors', log=False)
244
245     @staticmethod
246     def clear_error_counters_on_all_duts(nodes):
247         """Clear VPP errors counters on all DUTs.
248
249         :param nodes: VPP nodes.
250         :type nodes: dict
251         """
252         for node in nodes.values():
253             if node['type'] == NodeType.DUT:
254                 VppCounters.vpp_clear_errors_counters(node)
255
256     def vpp_get_ipv4_interface_counter(self, node, interface):
257         """
258
259         :param node: Node to get interface IPv4 counter on.
260         :param interface: Interface name.
261         :type node: dict
262         :type interface: str
263         :returns: Interface IPv4 counter.
264         :rtype: int
265         """
266         return self.vpp_get_ipv46_interface_counter(node, interface, False)
267
268     def vpp_get_ipv6_interface_counter(self, node, interface):
269         """
270
271         :param node: Node to get interface IPv6 counter on.
272         :param interface: Interface name.
273         :type node: dict
274         :type interface: str
275         :returns: Interface IPv6 counter.
276         :rtype: int
277         """
278         return self.vpp_get_ipv46_interface_counter(node, interface, True)
279
280     def vpp_get_ipv46_interface_counter(self, node, interface, is_ipv6=True):
281         """Return interface IPv4/IPv6 counter.
282
283         :param node: Node to get interface IPv4/IPv6 counter on.
284         :param interface: Interface name.
285         :param is_ipv6: Specify IP version.
286         :type node: dict
287         :type interface: str
288         :type is_ipv6: bool
289         :returns: Interface IPv4/IPv6 counter.
290         :rtype: int
291         """
292         version = 'ip6' if is_ipv6 else 'ip4'
293         topo = Topology()
294         sw_if_index = topo.get_interface_sw_index(node, interface)
295         if sw_if_index is None:
296             logger.trace('{i} sw_if_index not found.'.format(i=interface))
297             return 0
298
299         if_counters = self._stats_table.get('interface_counters')
300         if not if_counters:
301             logger.trace('No interface counters.')
302             return 0
303         for counter in if_counters:
304             if counter['vnet_counter_type'] == version:
305                 data = counter['data']
306                 return data[sw_if_index]
307         logger.trace('{i} {v} counter not found.'.format(
308             i=interface, v=version))
309         return 0
310
311     @staticmethod
312     def show_vpp_statistics(node):
313         """Show [error, hardware, interface] stats.
314
315         :param node: VPP node.
316         :type node: dict
317         """
318         VppCounters.vpp_show_errors(node)
319         VppCounters.vpp_show_hardware_detail(node)
320         VppCounters.vpp_show_runtime(node)
321
322     @staticmethod
323     def show_statistics_on_all_duts(nodes, sleeptime=5):
324         """Show VPP statistics on all DUTs.
325
326         :param nodes: VPP nodes.
327         :type nodes: dict
328         :param sleeptime: Time to wait for traffic to arrive back to TG.
329         :type sleeptime: int
330         """
331         logger.trace('Waiting for statistics to be collected')
332         time.sleep(sleeptime)
333         for node in nodes.values():
334             if node['type'] == NodeType.DUT:
335                 VppCounters.show_vpp_statistics(node)