integration: Support of integration testcases
[vswitchperf.git] / core / traffic_controller_rfc2544.py
1 # Copyright 2015 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 """RFC2544 Traffic Controller implementation.
15 """
16 import logging
17
18 from core.traffic_controller import ITrafficController
19 from core.results.results_constants import ResultsConstants
20 from core.results.results import IResults
21 from conf import settings
22 from conf import get_test_param
23
24
25 class TrafficControllerRFC2544(ITrafficController, IResults):
26     """Traffic controller for RFC2544 traffic
27
28     Used to setup and control a traffic generator for an RFC2544 deployment
29     traffic scenario.
30     """
31
32     def __init__(self, traffic_gen_class):
33         """Initialise the trafficgen and store.
34
35         :param traffic_gen_class: The traffic generator class to be used.
36         """
37         self._logger = logging.getLogger(__name__)
38         self._logger.debug("__init__")
39         self._traffic_gen_class = traffic_gen_class()
40         self._traffic_started = False
41         self._traffic_started_call_count = 0
42         self._trials = int(get_test_param('rfc2544_trials', 1))
43         self._duration = int(get_test_param('duration', 30))
44         self._results = []
45
46         # If set, comma separated packet_sizes value from --test_params
47         # on cli takes precedence over value in settings file.
48         self._packet_sizes = None
49         packet_sizes_cli = get_test_param('pkt_sizes')
50         if packet_sizes_cli:
51             self._packet_sizes = [int(x.strip())
52                                   for x in packet_sizes_cli.split(',')]
53         else:
54             self._packet_sizes = settings.getValue('TRAFFICGEN_PKT_SIZES')
55
56     def __enter__(self):
57         """Call initialisation function.
58         """
59         self._traffic_gen_class.connect()
60
61     def __exit__(self, type_, value, traceback):
62         """Stop traffic, clean up.
63         """
64         if self._traffic_started:
65             self.stop_traffic()
66
67     @staticmethod
68     def _append_results(result_dict, packet_size):
69         """Adds common values to traffic generator results.
70
71         :param result_dict: Dictionary containing results from trafficgen
72         :param packet_size: Packet size value.
73
74         :returns: dictionary of results with additional entries.
75         """
76
77         ret_value = result_dict
78
79         # TODO Old TOIT controller had knowledge about scenario beeing
80         # executed, should new controller also fill Configuration & ID,
81         # or this should be passed to TestCase?
82         ret_value[ResultsConstants.TYPE] = 'rfc2544'
83         ret_value[ResultsConstants.PACKET_SIZE] = str(packet_size)
84
85         return ret_value
86
87     def send_traffic(self, traffic):
88         """See ITrafficController for description
89         """
90         self._logger.debug('send_traffic with ' +
91                            str(self._traffic_gen_class))
92
93         for packet_size in self._packet_sizes:
94             # Merge framesize with the default traffic definition
95             if 'l2' in traffic:
96                 traffic['l2'] = dict(traffic['l2'],
97                                      **{'framesize': packet_size})
98             else:
99                 traffic['l2'] = {'framesize': packet_size}
100
101             if traffic['traffic_type'] == 'back2back':
102                 result = self._traffic_gen_class.send_rfc2544_back2back(
103                     traffic, trials=self._trials, duration=self._duration)
104             elif traffic['traffic_type'] == 'continuous':
105                 result = self._traffic_gen_class.send_cont_traffic(
106                     traffic, duration=self._duration)
107             else:
108                 result = self._traffic_gen_class.send_rfc2544_throughput(
109                     traffic, trials=self._trials, duration=self._duration)
110
111             result = TrafficControllerRFC2544._append_results(result,
112                                                               packet_size)
113             self._results.append(result)
114
115     def send_traffic_async(self, traffic, function):
116         """See ITrafficController for description
117         """
118         self._logger.debug('send_traffic_async with ' +
119                            str(self._traffic_gen_class))
120
121         for packet_size in self._packet_sizes:
122             traffic['l2'] = {'framesize': packet_size}
123             self._traffic_gen_class.start_rfc2544_throughput(
124                 traffic,
125                 trials=self._trials,
126                 duration=self._duration)
127             self._traffic_started = True
128             if len(function['args']) > 0:
129                 function['function'](function['args'])
130             else:
131                 function['function']()
132             result = self._traffic_gen_class.wait_rfc2544_throughput()
133             result = TrafficControllerRFC2544._append_results(result,
134                                                               packet_size)
135             self._results.append(result)
136
137     def stop_traffic(self):
138         """Kills traffic being sent from the traffic generator.
139         """
140         self._logger.debug("stop_traffic()")
141
142     def print_results(self):
143         """IResult interface implementation.
144         """
145         counter = 0
146         for item in self._results:
147             logging.info("Record: " + str(counter))
148             counter += 1
149             for(key, value) in list(item.items()):
150                 logging.info("         Key: " + str(key) +
151                              ", Value: " + str(value))
152
153     def get_results(self):
154         """IResult interface implementation.
155         """
156         return self._results
157
158     def validate_send_traffic(self, result, traffic):
159         """Verify that send traffic has succeeded
160         """
161         if len(self._results):
162             if 'b2b_frames' in self._results[-1]:
163                 return float(self._results[-1]['b2b_frames']) > 0
164             elif 'throughput_rx_fps' in self._results[-1]:
165                 return float(self._results[-1]['throughput_rx_fps']) > 0
166             else:
167                 return True
168         else:
169             return False