Merge "Add support for configuring frame rate per traffic flow for IXIA"
[yardstick.git] / yardstick / network_services / traffic_profile / ixia_rfc2544.py
1 # Copyright (c) 2016-2017 Intel Corporation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import logging
16
17 from yardstick.common import utils
18 from yardstick.network_services.traffic_profile import base as tp_base
19 from yardstick.network_services.traffic_profile import trex_traffic_profile
20
21
22 LOG = logging.getLogger(__name__)
23
24
25 class IXIARFC2544Profile(trex_traffic_profile.TrexProfile):
26
27     UPLINK = 'uplink'
28     DOWNLINK = 'downlink'
29     DROP_PERCENT_ROUND = 6
30     RATE_ROUND = 5
31     STATUS_SUCCESS = "Success"
32     STATUS_FAIL = "Failure"
33
34     def __init__(self, yaml_data):
35         super(IXIARFC2544Profile, self).__init__(yaml_data)
36         self.rate = self.config.frame_rate
37         self.rate_unit = self.config.rate_unit
38
39     def _get_ip_and_mask(self, ip_range):
40         _ip_range = ip_range.split('-')
41         if len(_ip_range) == 1:
42             return _ip_range[0], None
43
44         mask = utils.get_mask_from_ip_range(_ip_range[0], _ip_range[1])
45         return _ip_range[0], mask
46
47     def _get_fixed_and_mask(self, port_range):
48         _port_range = str(port_range).split('-')
49         if len(_port_range) == 1:
50             return int(_port_range[0]), 0
51
52         return int(_port_range[0]), int(_port_range[1])
53
54     def _get_ixia_traffic_profile(self, profile_data, mac=None):
55         mac = {} if mac is None else mac
56         result = {}
57         for traffickey, values in profile_data.items():
58             if not traffickey.startswith((self.UPLINK, self.DOWNLINK)):
59                 continue
60
61             # values should be single-item dict, so just grab the first item
62             try:
63                 key, value = next(iter(values.items()))
64             except StopIteration:
65                 result[traffickey] = {}
66                 continue
67
68             port_id = value.get('id', 1)
69             port_index = port_id - 1
70
71             result[traffickey] = {
72                 'bidir': False,
73                 'id': port_id,
74                 'rate': self.rate,
75                 'rate_unit': self.rate_unit,
76                 'outer_l2': {},
77                 'outer_l3': {},
78                 'outer_l4': {},
79             }
80
81             frame_rate = value.get('frame_rate')
82             if frame_rate:
83                 flow_rate, flow_rate_unit = self.config.parse_rate(frame_rate)
84                 result[traffickey]['rate'] = flow_rate
85                 result[traffickey]['rate_unit'] = flow_rate_unit
86
87             outer_l2 = value.get('outer_l2')
88             if outer_l2:
89                 result[traffickey]['outer_l2'].update({
90                     'framesize': outer_l2.get('framesize'),
91                     'framesPerSecond': True,
92                     'QinQ': outer_l2.get('QinQ'),
93                     'srcmac': mac.get('src_mac_{}'.format(port_index)),
94                     'dstmac': mac.get('dst_mac_{}'.format(port_index)),
95                 })
96
97             if value.get('outer_l3v4'):
98                 outer_l3 = value['outer_l3v4']
99                 src_key, dst_key = 'srcip4', 'dstip4'
100             else:
101                 outer_l3 = value.get('outer_l3v6')
102                 src_key, dst_key = 'srcip6', 'dstip6'
103             if outer_l3:
104                 srcip = srcmask = dstip = dstmask = None
105                 if outer_l3.get(src_key):
106                     srcip, srcmask = self._get_ip_and_mask(outer_l3[src_key])
107                 if outer_l3.get(dst_key):
108                     dstip, dstmask = self._get_ip_and_mask(outer_l3[dst_key])
109
110                 result[traffickey]['outer_l3'].update({
111                     'count': outer_l3.get('count', 1),
112                     'dscp': outer_l3.get('dscp'),
113                     'ttl': outer_l3.get('ttl'),
114                     'srcseed': outer_l3.get('srcseed', 1),
115                     'dstseed': outer_l3.get('dstseed', 1),
116                     'srcip': srcip,
117                     'dstip': dstip,
118                     'srcmask': srcmask,
119                     'dstmask': dstmask,
120                     'type': key,
121                     'proto': outer_l3.get('proto'),
122                     'priority': outer_l3.get('priority')
123                 })
124
125             outer_l4 = value.get('outer_l4')
126             if outer_l4:
127                 src_port = src_port_mask = dst_port = dst_port_mask = None
128                 if outer_l4.get('srcport'):
129                     src_port, src_port_mask = (
130                         self._get_fixed_and_mask(outer_l4['srcport']))
131
132                 if outer_l4.get('dstport'):
133                     dst_port, dst_port_mask = (
134                         self._get_fixed_and_mask(outer_l4['dstport']))
135
136                 result[traffickey]['outer_l4'].update({
137                     'srcport': src_port,
138                     'dstport': dst_port,
139                     'srcportmask': src_port_mask,
140                     'dstportmask': dst_port_mask,
141                     'count': outer_l4.get('count', 1),
142                     'seed': outer_l4.get('seed', 1),
143                 })
144
145         return result
146
147     def _ixia_traffic_generate(self, traffic, ixia_obj):
148         ixia_obj.update_frame(traffic, self.config.duration)
149         ixia_obj.update_ip_packet(traffic)
150         ixia_obj.update_l4(traffic)
151         ixia_obj.start_traffic()
152
153     def update_traffic_profile(self, traffic_generator):
154         def port_generator():
155             for vld_id, intfs in sorted(traffic_generator.networks.items()):
156                 if not vld_id.startswith((self.UPLINK, self.DOWNLINK)):
157                     continue
158                 profile_data = self.params.get(vld_id)
159                 if not profile_data:
160                     continue
161                 self.profile_data = profile_data
162                 self.full_profile.update({vld_id: self.profile_data})
163                 for intf in intfs:
164                     yield traffic_generator.vnfd_helper.port_num(intf)
165
166         self.ports = [port for port in port_generator()]
167
168     def execute_traffic(self, traffic_generator, ixia_obj=None, mac=None):
169         mac = {} if mac is None else mac
170         first_run = self.first_run
171         if self.first_run:
172             self.first_run = False
173             self.full_profile = {}
174             self.pg_id = 0
175             self.update_traffic_profile(traffic_generator)
176             self.max_rate = self.rate
177             self.min_rate = 0.0
178         else:
179             self.rate = round(float(self.max_rate + self.min_rate) / 2.0,
180                               self.RATE_ROUND)
181
182         traffic = self._get_ixia_traffic_profile(self.full_profile, mac)
183         self._ixia_traffic_generate(traffic, ixia_obj)
184         return first_run
185
186     def get_drop_percentage(self, samples, tol_min, tolerance, precision,
187                             first_run=False):
188         completed = False
189         drop_percent = 100
190         num_ifaces = len(samples)
191         duration = self.config.duration
192         in_packets_sum = sum(
193             [samples[iface]['in_packets'] for iface in samples])
194         out_packets_sum = sum(
195             [samples[iface]['out_packets'] for iface in samples])
196         rx_throughput = round(float(in_packets_sum) / duration, 3)
197         tx_throughput = round(float(out_packets_sum) / duration, 3)
198         packet_drop = abs(out_packets_sum - in_packets_sum)
199
200         try:
201             drop_percent = round(
202                 (packet_drop / float(out_packets_sum)) * 100,
203                 self.DROP_PERCENT_ROUND)
204         except ZeroDivisionError:
205             LOG.info('No traffic is flowing')
206
207         if first_run:
208             completed = True if drop_percent <= tolerance else False
209         if (first_run and
210                 self.rate_unit == tp_base.TrafficProfileConfig.RATE_FPS):
211             self.rate = float(out_packets_sum) / duration / num_ifaces
212
213         if drop_percent > tolerance:
214             self.max_rate = self.rate
215         elif drop_percent < tol_min:
216             self.min_rate = self.rate
217         else:
218             completed = True
219
220         LOG.debug("tolerance=%s, tolerance_precision=%s drop_percent=%s "
221                   "completed=%s", tolerance, precision, drop_percent,
222                   completed)
223
224         latency_ns_avg = float(
225             sum([samples[iface]['Store-Forward_Avg_latency_ns']
226             for iface in samples])) / num_ifaces
227         latency_ns_min = float(
228             sum([samples[iface]['Store-Forward_Min_latency_ns']
229             for iface in samples])) / num_ifaces
230         latency_ns_max = float(
231             sum([samples[iface]['Store-Forward_Max_latency_ns']
232             for iface in samples])) / num_ifaces
233
234         samples['Status'] = self.STATUS_FAIL
235         if round(drop_percent, precision) <= tolerance:
236             samples['Status'] = self.STATUS_SUCCESS
237
238         samples['TxThroughput'] = tx_throughput
239         samples['RxThroughput'] = rx_throughput
240         samples['DropPercentage'] = drop_percent
241         samples['latency_ns_avg'] = latency_ns_avg
242         samples['latency_ns_min'] = latency_ns_min
243         samples['latency_ns_max'] = latency_ns_max
244
245         return completed, samples