4a7f8557eaa9c0d57760bee6910946b7dff7efa1
[nfvbench.git] / nfvbench / traffic_gen / traffic_utils.py
1 # Copyright 2016 Cisco Systems, Inc.  All rights reserved.
2 #
3 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
4 #    not use this file except in compliance with the License. You may obtain
5 #    a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #    Unless required by applicable law or agreed to in writing, software
10 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 #    License for the specific language governing permissions and limitations
13 #    under the License.
14
15
16 import bitmath
17 from nfvbench.utils import multiplier_map
18
19 imix_avg_l2_size = None
20
21
22 def convert_rates(l2frame_size, rate, intf_speed):
23     avg_packet_size = get_average_packet_size(l2frame_size)
24     if 'rate_pps' in rate:
25         initial_rate_type = 'rate_pps'
26         pps = rate['rate_pps']
27         bps = pps_to_bps(pps, avg_packet_size)
28         load = bps_to_load(bps, intf_speed)
29     elif 'rate_bps' in rate:
30         initial_rate_type = 'rate_bps'
31         bps = rate['rate_bps']
32         load = bps_to_load(bps, intf_speed)
33         pps = bps_to_pps(bps, avg_packet_size)
34     elif 'rate_percent' in rate:
35         initial_rate_type = 'rate_percent'
36         load = rate['rate_percent']
37         bps = load_to_bps(load, intf_speed)
38         pps = bps_to_pps(bps, avg_packet_size)
39     else:
40         raise Exception('Traffic config needs to have a rate type key')
41
42     return {
43         'initial_rate_type': initial_rate_type,
44         'rate_pps': int(pps),
45         'rate_percent': load,
46         'rate_bps': int(bps)
47     }
48
49
50 def get_average_packet_size(l2frame_size):
51     if l2frame_size.upper() == 'IMIX':
52         return imix_avg_l2_size
53     return float(l2frame_size)
54
55
56 def load_to_bps(load_percentage, intf_speed):
57     return float(load_percentage) / 100.0 * intf_speed
58
59
60 def bps_to_load(bps, intf_speed):
61     return float(bps) / intf_speed * 100.0
62
63
64 def bps_to_pps(bps, avg_packet_size):
65     return float(bps) / (avg_packet_size + 20.0) / 8
66
67
68 def pps_to_bps(pps, avg_packet_size):
69     return float(pps) * (avg_packet_size + 20.0) * 8
70
71
72 def weighted_avg(weight, count):
73     if sum(weight):
74
75         return sum([x[0] * x[1] for x in zip(weight, count)]) / sum(weight)
76     return float('nan')
77
78 def _get_bitmath_rate(rate_bps):
79     rate = rate_bps.replace('ps', '').strip()
80     bitmath_rate = bitmath.parse_string(rate)
81     if bitmath_rate.bits <= 0:
82         raise Exception('%s is out of valid range' % rate_bps)
83     return bitmath_rate
84
85 def parse_rate_str(rate_str):
86     if rate_str.endswith('pps'):
87         rate_pps = rate_str[:-3]
88         if not rate_pps:
89             raise Exception('%s is missing a numeric value' % rate_str)
90         try:
91             multiplier = multiplier_map[rate_pps[-1].upper()]
92             rate_pps = rate_pps[:-1]
93         except KeyError:
94             multiplier = 1
95         rate_pps = int(rate_pps.strip()) * multiplier
96         if rate_pps <= 0:
97             raise Exception('%s is out of valid range' % rate_str)
98         return {'rate_pps': str(rate_pps)}
99     elif rate_str.endswith('ps'):
100         rate = rate_str.replace('ps', '').strip()
101         bit_rate = bitmath.parse_string(rate).bits
102         if bit_rate <= 0:
103             raise Exception('%s is out of valid range' % rate_str)
104         return {'rate_bps': str(int(bit_rate))}
105     elif rate_str.endswith('%'):
106         rate_percent = float(rate_str.replace('%', '').strip())
107         if rate_percent <= 0 or rate_percent > 100.0:
108             raise Exception('%s is out of valid range (must be 1-100%%)' % rate_str)
109         return {'rate_percent': str(rate_percent)}
110     else:
111         raise Exception('Unknown rate string format %s' % rate_str)
112
113 def get_load_from_rate(rate_str, avg_frame_size=64, line_rate='10Gbps'):
114     '''From any rate string (with unit) return the corresponding load (in % unit)
115
116     :param str rate_str: the rate to convert - must end with a unit (e.g. 1Mpps, 30%, 1Gbps)
117     :param int avg_frame_size: average frame size in bytes (needed only if pps is given)
118     :param str line_rate: line rate ending with bps unit (e.g. 1Mbps, 10Gbps) is the rate that
119                       corresponds to 100% rate
120     :return float: the corresponding rate in % of line rate
121     '''
122     rate_dict = parse_rate_str(rate_str)
123     if 'rate_percent' in rate_dict:
124         return float(rate_dict['rate_percent'])
125     lr_bps = _get_bitmath_rate(line_rate).bits
126     if 'rate_bps' in rate_dict:
127         bps = int(rate_dict['rate_bps'])
128     else:
129         # must be rate_pps
130         pps = rate_dict['rate_pps']
131         bps = pps_to_bps(pps, avg_frame_size)
132     return bps_to_load(bps, lr_bps)
133
134 def divide_rate(rate, divisor):
135     if 'rate_pps' in rate:
136         key = 'rate_pps'
137         value = int(rate[key])
138     elif 'rate_bps' in rate:
139         key = 'rate_bps'
140         value = int(rate[key])
141     else:
142         key = 'rate_percent'
143         value = float(rate[key])
144     value /= divisor
145     rate = dict(rate)
146     rate[key] = str(value) if value else str(1)
147     return rate
148
149
150 def to_rate_str(rate):
151     if 'rate_pps' in rate:
152         pps = rate['rate_pps']
153         return '{}pps'.format(pps)
154     elif 'rate_bps' in rate:
155         bps = rate['rate_bps']
156         return '{}bps'.format(bps)
157     elif 'rate_percent' in rate:
158         load = rate['rate_percent']
159         return '{}%'.format(load)
160     assert False
161     # avert pylint warning
162     return None
163
164
165 def nan_replace(d):
166     """Replaces every occurence of 'N/A' with float nan."""
167     for k, v in d.iteritems():
168         if isinstance(v, dict):
169             nan_replace(v)
170         elif v == 'N/A':
171             d[k] = float('nan')
172
173
174 def mac_to_int(mac):
175     """Converts MAC address to integer representation."""
176     return int(mac.translate(None, ":.- "), 16)
177
178
179 def int_to_mac(i):
180     """Converts integer representation of MAC address to hex string."""
181     mac = format(i, 'x').zfill(12)
182     blocks = [mac[x:x + 2] for x in xrange(0, len(mac), 2)]
183     return ':'.join(blocks)