1 # Copyright 2015 Intel Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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 """IXIA traffic generator model.
16 Provides a model for the IXIA traffic generator. In addition, provides
17 a number of generic "helper" functions that are used to do the "heavy
20 This requires the following settings in your config file:
22 * TRAFFICGEN_IXIA_LIB_PATH
24 * TRAFFICGEN_IXIA_HOST
25 IXIA chassis IP address
26 * TRAFFICGEN_IXIA_CARD
28 * TRAFFICGEN_IXIA_PORT1
30 * TRAFFICGEN_IXIA_PORT2
33 If any of these don't exist, the application will raise an exception
41 from tools.pkt_gen import trafficgen
42 from conf import settings
43 from collections import OrderedDict
44 from core.results.results_constants import ResultsConstants
46 _ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
47 _IXIA_ROOT_DIR = settings.getValue('TRAFFICGEN_IXIA_ROOT_DIR')
51 """Configure envionment for TCL.
54 os.environ['IXIA_HOME'] = _IXIA_ROOT_DIR
56 # USER MAY NEED TO CHANGE THESE IF USING OWN TCL LIBRARY
57 os.environ['TCL_HOME'] = _IXIA_ROOT_DIR
58 os.environ['TCLver'] = '8.5'
60 # USER NORMALLY DOES NOT CHANGE ANY LINES BELOW
61 os.environ['IxiaLibPath'] = os.path.expandvars('$IXIA_HOME/lib')
62 os.environ['IxiaBinPath'] = os.path.expandvars('$IXIA_HOME/bin')
64 os.environ['TCLLibPath'] = os.path.expandvars('$TCL_HOME/lib')
65 os.environ['TCLBinPath'] = os.path.expandvars('$TCL_HOME/bin')
67 os.environ['TCL_LIBRARY'] = os.path.expandvars('$TCLLibPath/tcl$TCLver')
68 os.environ['TK_LIBRARY'] = os.path.expandvars('$TCLLibPath/tk$TCLver')
70 os.environ['PATH'] = os.path.expandvars('$IxiaBinPath:.:$TCLBinPath:$PATH')
71 os.environ['TCLLIBPATH'] = os.path.expandvars('$IxiaLibPath')
72 os.environ['LD_LIBRARY_PATH'] = os.path.expandvars(
73 '$IxiaLibPath:$TCLLibPath:$LD_LIBRARY_PATH')
75 os.environ['IXIA_RESULTS_DIR'] = '/tmp/Ixia/Results'
76 os.environ['IXIA_LOGS_DIR'] = '/tmp/Ixia/Logs'
77 os.environ['IXIA_TCL_DIR'] = os.path.expandvars('$IxiaLibPath')
78 os.environ['IXIA_SAMPLES'] = os.path.expandvars('$IxiaLibPath/ixTcl1.0')
79 os.environ['IXIA_VERSION'] = '6.60.1000.11'
82 def _build_set_cmds(values, prefix='dict set'):
83 """Generate a list of 'dict set' args for Tcl.
85 Parse a dictionary and recursively build the arguments for the
86 'dict set' Tcl command, given that this is of the format:
88 dict set [name...] [key] [value]
90 For example, for a non-nested dict (i.e. a non-dict element):
92 dict set mydict mykey myvalue
94 For a nested dict (i.e. a dict element):
96 dict set mydict mysubdict mykey myvalue
98 :param values: Dictionary to yield values for
99 :param prefix: Prefix to append to output string. Generally the
100 already generated part of the command.
102 :yields: Output strings to be passed to a `Tcl` instance.
107 # Not allowing derived dictionary types for now
108 # pylint: disable=unidiomatic-typecheck
109 if type(value) == dict:
110 _prefix = ' '.join([prefix, key]).strip()
111 for subkey in _build_set_cmds(value, _prefix):
115 # tcl doesn't recognise the strings "True" or "False", only "1"
116 # or "0". Special case to convert them
117 if type(value) == bool:
118 value = str(int(value))
123 yield ' '.join([prefix, key, value]).strip()
125 yield ' '.join([key, value]).strip()
128 class Ixia(trafficgen.ITrafficGenerator):
129 """A wrapper around the IXIA traffic generator.
131 Runs different traffic generator tests through an Ixia traffic
132 generator chassis by generating TCL scripts from templates.
134 _script = os.path.join(os.path.dirname(__file__), 'pass_fail.tcl')
135 _tclsh = tkinter.Tcl()
136 _logger = logging.getLogger(__name__)
138 def run_tcl(self, cmd):
139 """Run a TCL script using the TCL interpreter found in ``tkinter``.
141 :param cmd: Command to execute
143 :returns: Output of command, where applicable.
145 self._logger.debug('%s%s', trafficgen.CMD_PREFIX, cmd)
147 output = self._tclsh.eval(cmd)
149 return output.split()
152 """Connect to Ixia chassis.
155 'lib_path': os.path.join(_IXIA_ROOT_DIR, 'lib', 'ixTcl1.0'),
156 'host': settings.getValue('TRAFFICGEN_IXIA_HOST'),
157 'card': settings.getValue('TRAFFICGEN_IXIA_CARD'),
158 'port1': settings.getValue('TRAFFICGEN_IXIA_PORT1'),
159 'port2': settings.getValue('TRAFFICGEN_IXIA_PORT2'),
162 self._logger.info('Connecting to IXIA...')
164 self._logger.debug('IXIA configuration configuration : %s', ixia_cfg)
168 for cmd in _build_set_cmds(ixia_cfg, prefix='set'):
171 output = self.run_tcl('source {%s}' % self._script)
173 self._logger.critical(
174 'An error occured when connecting to IXIA...')
175 raise RuntimeError('Ixia failed to initialise.')
177 self._logger.info('Connected to IXIA...')
181 def disconnect(self):
182 """Disconnect from Ixia chassis.
184 self._logger.info('Disconnecting from IXIA...')
186 self.run_tcl('cleanUp')
188 self._logger.info('Disconnected from IXIA...')
190 def _send_traffic(self, flow, traffic):
191 """Send regular traffic.
193 :param flow: Flow specification
194 :param traffic: Traffic specification
196 :returns: Results from IXIA
200 params['flow'] = flow
201 params['traffic'] = self.traffic_defaults.copy()
204 params['traffic'] = trafficgen.merge_spec(
205 params['traffic'], traffic)
207 for cmd in _build_set_cmds(params):
210 result = self.run_tcl('sendTraffic $flow $traffic')
214 def send_burst_traffic(self, traffic=None, numpkts=100, duration=20):
215 """See ITrafficGenerator for description
219 'duration': duration,
220 'type': 'stopStream',
221 'framerate': traffic['frame_rate'],
224 result = self._send_traffic(flow, traffic)
226 assert len(result) == 6 # fail-fast if underlying Tcl code changes
228 #TODO - implement Burst results setting via TrafficgenResults.
230 def send_cont_traffic(self, traffic=None, duration=30, multistream=False):
231 """See ITrafficGenerator for description
235 'duration': duration,
236 'type': 'contPacket',
237 'framerate': traffic['frame_rate'],
238 'multipleStreams': traffic['multistream'],
241 result = self._send_traffic(flow, traffic)
243 return Ixia._create_result(result)
245 def start_cont_traffic(self, traffic=None, duration=30):
246 """See ITrafficGenerator for description
248 return self.send_cont_traffic(traffic, 0)
250 def stop_cont_traffic(self):
251 """See ITrafficGenerator for description
253 return self.run_tcl('stopTraffic')
255 def send_rfc2544_throughput(self, traffic=None, trials=3, duration=20,
256 lossrate=0.0, multistream=False):
257 """See ITrafficGenerator for description
263 'duration': duration,
264 'lossrate': lossrate,
265 'multipleStreams': traffic['multistream'],
267 params['traffic'] = self.traffic_defaults.copy()
270 params['traffic'] = trafficgen.merge_spec(
271 params['traffic'], traffic)
273 for cmd in _build_set_cmds(params):
276 # this will return a list with one result
277 result = self.run_tcl('rfcThroughputTest $config $traffic')
279 return Ixia._create_result(result)
282 def _create_result(result):
283 """Create result based on list returned from tcl script.
285 :param result: list representing output from tcl script.
287 :returns: dictionary strings representing results from
290 assert len(result) == 8 # fail-fast if underlying Tcl code changes
292 result_dict = OrderedDict()
293 # drop the first 4 elements as we don't use/need them. In
294 # addition, IxExplorer does not support latency or % line rate
295 # metrics so we have to return dummy values for these metrics
296 result_dict[ResultsConstants.THROUGHPUT_RX_FPS] = result[4]
297 result_dict[ResultsConstants.TX_RATE_FPS] = result[5]
298 result_dict[ResultsConstants.THROUGHPUT_RX_MBPS] = result[6]
299 result_dict[ResultsConstants.TX_RATE_MBPS] = result[7]
300 result_dict[ResultsConstants.TX_RATE_PERCENT] = \
301 ResultsConstants.UNKNOWN_VALUE
302 result_dict[ResultsConstants.THROUGHPUT_RX_PERCENT] = \
303 ResultsConstants.UNKNOWN_VALUE
304 result_dict[ResultsConstants.MIN_LATENCY_NS] = \
305 ResultsConstants.UNKNOWN_VALUE
306 result_dict[ResultsConstants.MAX_LATENCY_NS] = \
307 ResultsConstants.UNKNOWN_VALUE
308 result_dict[ResultsConstants.AVG_LATENCY_NS] = \
309 ResultsConstants.UNKNOWN_VALUE
313 if __name__ == '__main__':
318 'dstip': '10.1.1.254',
323 print(dev.send_burst_traffic(traffic=TRAFFIC))
324 print(dev.send_cont_traffic(traffic=TRAFFIC))
325 print(dev.send_rfc2544_throughput(traffic=TRAFFIC))