Add show memory to show_vpp_statistics
[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_verbose(node):
160         """Run "show hardware-interfaces verbose" 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 verbose')
166
167     @staticmethod
168     def vpp_show_memory(node):
169         """Run "show memory" debug CLI command.
170
171         Currently, every flag is hardcoded, giving the longest output.
172
173         :param node: Node to run command on.
174         :type node: dict
175         """
176         PapiSocketExecutor.run_cli_cmd(
177             node, 'show memory verbose api-segment stats-segment main-heap')
178
179     @staticmethod
180     def vpp_clear_runtime(node):
181         """Run "clear runtime" CLI command.
182
183         :param node: Node to run command on.
184         :type node: dict
185         :returns: Verified data from PAPI response.
186         :rtype: dict
187         """
188         return PapiSocketExecutor.run_cli_cmd(node, 'clear runtime', log=False)
189
190     @staticmethod
191     def clear_runtime_counters_on_all_duts(nodes):
192         """Run "clear runtime" CLI command on all DUTs.
193
194         :param nodes: VPP nodes.
195         :type nodes: dict
196         """
197         for node in nodes.values():
198             if node['type'] == NodeType.DUT:
199                 VppCounters.vpp_clear_runtime(node)
200
201     @staticmethod
202     def vpp_clear_interface_counters(node):
203         """Run "clear interfaces" CLI command.
204
205         :param node: Node to run command on.
206         :type node: dict
207         :returns: Verified data from PAPI response.
208         :rtype: dict
209         """
210         return PapiSocketExecutor.run_cli_cmd(
211             node, 'clear interfaces', log=False)
212
213     @staticmethod
214     def clear_interface_counters_on_all_duts(nodes):
215         """Clear interface counters on all DUTs.
216
217         :param nodes: VPP nodes.
218         :type nodes: dict
219         """
220         for node in nodes.values():
221             if node['type'] == NodeType.DUT:
222                 VppCounters.vpp_clear_interface_counters(node)
223
224     @staticmethod
225     def vpp_clear_hardware_counters(node):
226         """Run "clear hardware" CLI command.
227
228         :param node: Node to run command on.
229         :type node: dict
230         :returns: Verified data from PAPI response.
231         :rtype: dict
232         """
233         return PapiSocketExecutor.run_cli_cmd(node, 'clear hardware', log=False)
234
235     @staticmethod
236     def clear_hardware_counters_on_all_duts(nodes):
237         """Clear hardware counters on all DUTs.
238
239         :param nodes: VPP nodes.
240         :type nodes: dict
241         """
242         for node in nodes.values():
243             if node['type'] == NodeType.DUT:
244                 VppCounters.vpp_clear_hardware_counters(node)
245
246     @staticmethod
247     def vpp_clear_errors_counters(node):
248         """Run "clear errors" CLI command.
249
250         :param node: Node to run command on.
251         :type node: dict
252         :returns: Verified data from PAPI response.
253         :rtype: dict
254         """
255         return PapiSocketExecutor.run_cli_cmd(node, 'clear errors', log=False)
256
257     @staticmethod
258     def clear_error_counters_on_all_duts(nodes):
259         """Clear VPP errors counters on all DUTs.
260
261         :param nodes: VPP nodes.
262         :type nodes: dict
263         """
264         for node in nodes.values():
265             if node['type'] == NodeType.DUT:
266                 VppCounters.vpp_clear_errors_counters(node)
267
268     def vpp_get_ipv4_interface_counter(self, node, interface):
269         """
270
271         :param node: Node to get interface IPv4 counter on.
272         :param interface: Interface name.
273         :type node: dict
274         :type interface: str
275         :returns: Interface IPv4 counter.
276         :rtype: int
277         """
278         return self.vpp_get_ipv46_interface_counter(node, interface, False)
279
280     def vpp_get_ipv6_interface_counter(self, node, interface):
281         """
282
283         :param node: Node to get interface IPv6 counter on.
284         :param interface: Interface name.
285         :type node: dict
286         :type interface: str
287         :returns: Interface IPv6 counter.
288         :rtype: int
289         """
290         return self.vpp_get_ipv46_interface_counter(node, interface, True)
291
292     def vpp_get_ipv46_interface_counter(self, node, interface, is_ipv6=True):
293         """Return interface IPv4/IPv6 counter.
294
295         :param node: Node to get interface IPv4/IPv6 counter on.
296         :param interface: Interface name.
297         :param is_ipv6: Specify IP version.
298         :type node: dict
299         :type interface: str
300         :type is_ipv6: bool
301         :returns: Interface IPv4/IPv6 counter.
302         :rtype: int
303         """
304         version = 'ip6' if is_ipv6 else 'ip4'
305         topo = Topology()
306         sw_if_index = topo.get_interface_sw_index(node, interface)
307         if sw_if_index is None:
308             logger.trace('{i} sw_if_index not found.'.format(i=interface))
309             return 0
310
311         if_counters = self._stats_table.get('interface_counters')
312         if not if_counters:
313             logger.trace('No interface counters.')
314             return 0
315         for counter in if_counters:
316             if counter['vnet_counter_type'] == version:
317                 data = counter['data']
318                 return data[sw_if_index]
319         logger.trace('{i} {v} counter not found.'.format(
320             i=interface, v=version))
321         return 0
322
323     @staticmethod
324     def show_vpp_statistics(node):
325         """Show [error, hardware, interface] stats.
326
327         :param node: VPP node.
328         :type node: dict
329         """
330         VppCounters.vpp_show_errors(node)
331         VppCounters.vpp_show_hardware_verbose(node)
332         VppCounters.vpp_show_runtime(node)
333         VppCounters.vpp_show_memory(node)
334
335     @staticmethod
336     def show_statistics_on_all_duts(nodes, sleeptime=5):
337         """Show VPP statistics on all DUTs.
338
339         :param nodes: VPP nodes.
340         :type nodes: dict
341         :param sleeptime: Time to wait for traffic to arrive back to TG.
342         :type sleeptime: int
343         """
344         logger.trace('Waiting for statistics to be collected')
345         time.sleep(sleeptime)
346         for node in nodes.values():
347             if node['type'] == NodeType.DUT:
348                 VppCounters.show_vpp_statistics(node)