f856267d0c619ddea3ced76bfee23de245493e24
[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 frame size including the 4-byte FCS field
20 IMIX_L2_SIZES = [64, 594, 1518]
21 IMIX_RATIOS = [7, 4, 1]
22 # weighted average l2 frame size includng the 4-byte FCS
23 IMIX_AVG_L2_FRAME_SIZE = sum(
24     [1.0 * imix[0] * imix[1] for imix in zip(IMIX_L2_SIZES, IMIX_RATIOS)]) / sum(IMIX_RATIOS)
25
26
27 def convert_rates(l2frame_size, rate, intf_speed):
28     """Convert a given rate unit into the other rate units.
29
30     l2frame_size: size of the L2 frame in bytes (includes 32-bit FCS) or 'IMIX'
31     rate: a dict that has at least one of the following key:
32           'rate_pps', 'rate_bps', 'rate_percent'
33           with the corresponding input value
34     intf_speed: the line rate speed in bits per second
35     """
36     avg_packet_size = get_average_packet_size(l2frame_size)
37     if 'rate_pps' in rate:
38         # input = packets/sec
39         initial_rate_type = 'rate_pps'
40         pps = rate['rate_pps']
41         bps = pps_to_bps(pps, avg_packet_size)
42         load = bps_to_load(bps, intf_speed)
43     elif 'rate_bps' in rate:
44         # input = bits per second
45         initial_rate_type = 'rate_bps'
46         bps = rate['rate_bps']
47         load = bps_to_load(bps, intf_speed)
48         pps = bps_to_pps(bps, avg_packet_size)
49     elif 'rate_percent' in rate:
50         # input = percentage of the line rate (between 0.0 and 100.0)
51         initial_rate_type = 'rate_percent'
52         load = rate['rate_percent']
53         bps = load_to_bps(load, intf_speed)
54         pps = bps_to_pps(bps, avg_packet_size)
55     else:
56         raise Exception('Traffic config needs to have a rate type key')
57
58     return {
59         'initial_rate_type': initial_rate_type,
60         'rate_pps': int(pps),
61         'rate_percent': load,
62         'rate_bps': int(bps)
63     }
64
65
66 def get_average_packet_size(l2frame_size):
67     """Retrieve the average L2 frame size
68
69     l2frame_size: an L2 frame size in bytes (including FCS) or 'IMIX'
70     return: average l2 frame size inlcuding the 32-bit FCS
71     """
72     if l2frame_size.upper() == 'IMIX':
73         return IMIX_AVG_L2_FRAME_SIZE
74     return float(l2frame_size)
75
76
77 def load_to_bps(load_percentage, intf_speed):
78     return float(load_percentage) / 100.0 * intf_speed
79
80
81 def bps_to_load(bps, intf_speed):
82     return float(bps) / intf_speed * 100.0
83
84
85 def bps_to_pps(bps, avg_packet_size):
86     return float(bps) / (avg_packet_size + 20.0) / 8
87
88
89 def pps_to_bps(pps, avg_packet_size):
90     return float(pps) * (avg_packet_size + 20.0) * 8
91
92
93 def weighted_avg(weight, count):
94     if sum(weight):
95
96         return sum([x[0] * x[1] for x in zip(weight, count)]) / sum(weight)
97     return float('nan')
98
99 def _get_bitmath_rate(rate_bps):
100     rate = rate_bps.replace('ps', '').strip()
101     bitmath_rate = bitmath.parse_string(rate)
102     if bitmath_rate.bits <= 0:
103         raise Exception('%s is out of valid range' % rate_bps)
104     return bitmath_rate
105
106 def parse_rate_str(rate_str):
107     if rate_str.endswith('pps'):
108         rate_pps = rate_str[:-3]
109         if not rate_pps:
110             raise Exception('%s is missing a numeric value' % rate_str)
111         try:
112             multiplier = multiplier_map[rate_pps[-1].upper()]
113             rate_pps = rate_pps[:-1]
114         except KeyError:
115             multiplier = 1
116         rate_pps = int(rate_pps.strip()) * multiplier
117         if rate_pps <= 0:
118             raise Exception('%s is out of valid range' % rate_str)
119         return {'rate_pps': str(rate_pps)}
120     elif rate_str.endswith('ps'):
121         rate = rate_str.replace('ps', '').strip()
122         bit_rate = bitmath.parse_string(rate).bits
123         if bit_rate <= 0:
124             raise Exception('%s is out of valid range' % rate_str)
125         return {'rate_bps': str(int(bit_rate))}
126     elif rate_str.endswith('%'):
127         rate_percent = float(rate_str.replace('%', '').strip())
128         if rate_percent <= 0 or rate_percent > 100.0:
129             raise Exception('%s is out of valid range (must be 1-100%%)' % rate_str)
130         return {'rate_percent': str(rate_percent)}
131     else:
132         raise Exception('Unknown rate string format %s' % rate_str)
133
134 def get_load_from_rate(rate_str, avg_frame_size=64, line_rate='10Gbps'):
135     '''From any rate string (with unit) return the corresponding load (in % unit)
136
137     :param str rate_str: the rate to convert - must end with a unit (e.g. 1Mpps, 30%, 1Gbps)
138     :param int avg_frame_size: average frame size in bytes (needed only if pps is given)
139     :param str line_rate: line rate ending with bps unit (e.g. 1Mbps, 10Gbps) is the rate that
140                       corresponds to 100% rate
141     :return float: the corresponding rate in % of line rate
142     '''
143     rate_dict = parse_rate_str(rate_str)
144     if 'rate_percent' in rate_dict:
145         return float(rate_dict['rate_percent'])
146     lr_bps = _get_bitmath_rate(line_rate).bits
147     if 'rate_bps' in rate_dict:
148         bps = int(rate_dict['rate_bps'])
149     else:
150         # must be rate_pps
151         pps = rate_dict['rate_pps']
152         bps = pps_to_bps(pps, avg_frame_size)
153     return bps_to_load(bps, lr_bps)
154
155 def divide_rate(rate, divisor):
156     if 'rate_pps' in rate:
157         key = 'rate_pps'
158         value = int(rate[key])
159     elif 'rate_bps' in rate:
160         key = 'rate_bps'
161         value = int(rate[key])
162     else:
163         key = 'rate_percent'
164         value = float(rate[key])
165     value /= divisor
166     rate = dict(rate)
167     rate[key] = str(value) if value else str(1)
168     return rate
169
170
171 def to_rate_str(rate):
172     if 'rate_pps' in rate:
173         pps = rate['rate_pps']
174         return '{}pps'.format(pps)
175     elif 'rate_bps' in rate:
176         bps = rate['rate_bps']
177         return '{}bps'.format(bps)
178     elif 'rate_percent' in rate:
179         load = rate['rate_percent']
180         return '{}%'.format(load)
181     assert False
182     # avert pylint warning
183     return None
184
185
186 def nan_replace(d):
187     """Replaces every occurence of 'N/A' with float nan."""
188     for k, v in d.iteritems():
189         if isinstance(v, dict):
190             nan_replace(v)
191         elif v == 'N/A':
192             d[k] = float('nan')
193
194
195 def mac_to_int(mac):
196     """Converts MAC address to integer representation."""
197     return int(mac.translate(None, ":.- "), 16)
198
199
200 def int_to_mac(i):
201     """Converts integer representation of MAC address to hex string."""
202     mac = format(i, 'x').zfill(12)
203     blocks = [mac[x:x + 2] for x in xrange(0, len(mac), 2)]
204     return ':'.join(blocks)