5d72bc9f5380f4f514bf653ac783c57c17403ab5
[nfvbench.git] / nfvbench / packet_analyzer.py
1 #!/usr/bin/env python
2 # Copyright 2016 Cisco Systems, Inc.  All rights reserved.
3 #
4 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
5 #    not use this file except in compliance with the License. You may obtain
6 #    a copy of the License at
7 #
8 #         http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #    Unless required by applicable law or agreed to in writing, software
11 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 #    License for the specific language governing permissions and limitations
14 #    under the License.
15 #
16
17 from collections import OrderedDict
18 from log import LOG
19
20
21 class PacketAnalyzer(object):
22     """Analyze packet drop counter in a chain"""
23
24     def __init__(self):
25         self.last_packet_count = 0
26         self.chain = []
27
28     def record(self, interface, traffic_type):
29         """Records the counter of the next interface with the corresponding traffic type"""
30         if interface.is_no_op():
31             return
32         packet_count = interface.get_packet_count(traffic_type)
33         packet_drop_count = self.last_packet_count - packet_count
34         path_data = OrderedDict()
35         path_data['interface'] = interface.name
36         path_data['device'] = interface.device
37         path_data['packet_count'] = packet_count
38
39         if self.chain:
40             path_data['packet_drop_count'] = packet_drop_count
41
42         self.chain.append(path_data)
43         self.last_packet_count = packet_count
44
45     def get_analysis(self):
46         """Gets the analysis of packet drops"""
47         transmitted_packets = self.chain[0]['packet_count']
48
49         for (index, path_data) in enumerate(self.chain):
50             LOG.info('[Packet Analyze] Interface: %s', path_data['interface'])
51             LOG.info('[Packet Analyze]            > Count: %d', path_data['packet_count'])
52
53             if index:
54                 if transmitted_packets:
55                     self.chain[index]['packet_drop_percentage'] = \
56                         100.0 * path_data['packet_drop_count'] / transmitted_packets
57                 else:
58                     self.chain[index]['packet_drop_percentage'] = float('nan')
59                 LOG.info('[Packet Analyze]            > Packet Drops: %d',
60                          path_data['packet_drop_count'])
61                 LOG.info('[Packet Analyze]            > Percentage: %s',
62                          path_data['packet_drop_percentage'])
63
64         return self.chain