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 """IxNetwork traffic generator model.
16 Provides a model for an IxNetwork machine and appropriate applications.
18 This requires the following settings in your config file:
20 * TRAFFICGEN_IXNET_LIB_PATH
21 IxNetwork libraries path
22 * TRAFFICGEN_IXNET_HOST
23 IxNetwork host IP address
24 * TRAFFICGEN_IXNET_PORT
25 IxNetwork host port number
26 * TRAFFICGEN_IXNET_USER
27 IxNetwork host user name
28 * TRAFFICGEN_IXNET_TESTER_RESULT_DIR
29 The result directory on the IxNetwork computer
30 * TRAFFICGEN_IXNET_DUT_RESULT_DIR
31 The result directory on DUT. This needs to map to the same directory
34 The following settings are also required. These can likely be shared
35 an 'Ixia' traffic generator instance:
37 * TRAFFICGEN_IXIA_HOST
38 IXIA chassis IP address
39 * TRAFFICGEN_IXIA_CARD
41 * TRAFFICGEN_IXIA_PORT1
43 * TRAFFICGEN_IXIA_PORT2
46 If any of these don't exist, the application will raise an exception
49 Additional Configuration:
50 -------------------------
52 You will also need to configure the IxNetwork machine to start the IXIA
53 IxNetworkTclServer. This can be started like so:
55 1. Connect to the IxNetwork machine using RDP
62 IxNetwork 7.21.893.14 GA ->
65 Pin a shortcut to this application to the taskbar.
66 3. Before running it right click the pinned shortcut and go to
67 "Properties". Here change the port number to your own port number.
68 This will be the same value as "TRAFFICGEN_IXNET_PORT" above.
69 4. You will find this on the shortcut tab under the heading "Target"
70 5. Finally run it. If you see the following error check that you
71 followed the above steps exactly:
73 ERROR: couldn't open socket : connection refused
78 This method of automation is quite error prone as the IxNetwork API
79 does not give any feedback as to the status of tests. As such, it can
80 be expected that the user have access to the IxNetwork machine should
81 this trafficgen need to be debugged.
90 from collections import OrderedDict
91 from tools.pkt_gen import trafficgen
92 from conf import settings
93 from core.results.results_constants import ResultsConstants
95 _ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
97 _RESULT_RE = r'(?:\{kString,result\},\{kString,)(\w+)(?:\})'
98 _RESULTPATH_RE = r'(?:\{kString,resultPath\},\{kString,)([\\\w\.\-\:]+)(?:\})'
101 def _build_set_cmds(values, prefix='dict set'):
102 """Generate a list of 'dict set' args for Tcl.
104 Parse a dictionary and recursively build the arguments for the
105 'dict set' Tcl command, given that this is of the format:
107 dict set [name...] [key] [value]
109 For example, for a non-nested dict (i.e. a non-dict element):
111 dict set mydict mykey myvalue
113 For a nested dict (i.e. a dict element):
115 dict set mydict mysubdict mykey myvalue
117 :param values: Dictionary to yield values for
118 :param prefix: Prefix to append to output string. Generally the
119 already generated part of the command.
121 :yields: Output strings to be passed to a `Tcl` instance.
126 # Not allowing derived dictionary types for now
127 # pylint: disable=unidiomatic-typecheck
128 if type(value) == dict:
129 _prefix = ' '.join([prefix, key]).strip()
130 for subkey in _build_set_cmds(value, _prefix):
134 # pylint: disable=unidiomatic-typecheck
135 # tcl doesn't recognise the strings "True" or "False", only "1"
136 # or "0". Special case to convert them
137 if type(value) == bool:
138 value = str(int(value))
143 yield ' '.join([prefix, key, value]).strip()
145 yield ' '.join([key, value]).strip()
148 class IxNet(trafficgen.ITrafficGenerator):
149 """A wrapper around IXIA IxNetwork applications.
151 Runs different traffic generator tests through an Ixia traffic
152 generator chassis by generating TCL scripts from templates.
154 Currently only the RFC2544 tests are implemented.
156 _script = os.path.join(os.path.dirname(__file__), 'ixnetrfc2544.tcl')
157 _tclsh = tkinter.Tcl()
159 _logger = logging.getLogger(__name__)
163 def run_tcl(self, cmd):
164 """Run a TCL script using the TCL interpreter found in ``tkinter``.
166 :param cmd: Command to execute
168 :returns: Output of command, where applicable.
170 self._logger.debug('%s%s', trafficgen.CMD_PREFIX, cmd)
172 output = self._tclsh.eval(cmd)
174 return output.split()
177 """Configure system for IxNetwork.
180 'lib_path': settings.getValue('TRAFFICGEN_IXNET_LIB_PATH'),
181 # IxNetwork machine configuration
182 'machine': settings.getValue('TRAFFICGEN_IXNET_MACHINE'),
183 'port': settings.getValue('TRAFFICGEN_IXNET_PORT'),
184 'user': settings.getValue('TRAFFICGEN_IXNET_USER'),
185 # IXIA chassis configuration
186 'chassis': settings.getValue('TRAFFICGEN_IXIA_HOST'),
187 'card': settings.getValue('TRAFFICGEN_IXIA_CARD'),
188 'port1': settings.getValue('TRAFFICGEN_IXIA_PORT1'),
189 'port2': settings.getValue('TRAFFICGEN_IXIA_PORT2'),
191 settings.getValue('TRAFFICGEN_IXNET_TESTER_RESULT_DIR'),
194 self._logger.debug('IXIA configuration configuration : %s', self._cfg)
198 def disconnect(self):
199 """Disconnect from Ixia chassis.
203 def send_cont_traffic(self, traffic=None, time=30, framerate=100):
204 """See ITrafficGenerator for description
206 self.start_cont_traffic(traffic, time, framerate)
208 return self.stop_cont_traffic()
210 def start_cont_traffic(self, traffic=None, time=30, framerate=100):
211 """Start transmission.
213 self._bidir = traffic['bidir']
216 self._params['config'] = {
217 'binary': False, # don't do binary search and send one stream
219 'framerate': framerate,
220 'multipleStreams': traffic['multistream'],
221 'rfc2544TestType': 'throughput',
223 self._params['traffic'] = self.traffic_defaults.copy()
226 self._params['traffic'] = trafficgen.merge_spec(
227 self._params['traffic'], traffic)
228 self._cfg['bidir'] = self._bidir
230 for cmd in _build_set_cmds(self._cfg, prefix='set'):
233 for cmd in _build_set_cmds(self._params):
236 output = self.run_tcl('source {%s}' % self._script)
238 self._logger.critical(
239 'An error occured when connecting to IxNetwork machine...')
240 raise RuntimeError('Ixia failed to initialise.')
242 self.run_tcl('startRfc2544Test $config $traffic')
244 self._logger.critical(
245 'Failed to start continuous traffic test')
246 raise RuntimeError('Continuous traffic test failed to start.')
248 def stop_cont_traffic(self):
249 """See ITrafficGenerator for description
251 return self._wait_result()
253 def send_rfc2544_throughput(self, traffic=None, trials=3, duration=20,
255 """See ITrafficGenerator for description
257 self.start_rfc2544_throughput(traffic, trials, duration, lossrate)
259 return self.wait_rfc2544_throughput()
261 def start_rfc2544_throughput(self, traffic=None, trials=3, duration=20,
263 """Start transmission.
265 self._bidir = traffic['bidir']
268 self._params['config'] = {
271 'duration': duration,
272 'lossrate': lossrate,
273 'multipleStreams': traffic['multistream'],
274 'rfc2544TestType': 'throughput',
276 self._params['traffic'] = self.traffic_defaults.copy()
279 self._params['traffic'] = trafficgen.merge_spec(
280 self._params['traffic'], traffic)
281 self._cfg['bidir'] = self._bidir
283 for cmd in _build_set_cmds(self._cfg, prefix='set'):
286 for cmd in _build_set_cmds(self._params):
289 output = self.run_tcl('source {%s}' % self._script)
291 self._logger.critical(
292 'An error occured when connecting to IxNetwork machine...')
293 raise RuntimeError('Ixia failed to initialise.')
295 self.run_tcl('startRfc2544Test $config $traffic')
297 self._logger.critical(
298 'Failed to start RFC2544 test')
299 raise RuntimeError('RFC2544 test failed to start.')
301 def wait_rfc2544_throughput(self):
302 """See ITrafficGenerator for description
304 return self._wait_result()
306 def _wait_result(self):
309 def parse_result_string(results):
310 """Get path to results file from output
312 Check for related errors
314 :param results: Text stream from test.
316 :returns: Path to results file.
318 result_status = re.search(_RESULT_RE, results)
319 result_path = re.search(_RESULTPATH_RE, results)
321 if not result_status or not result_path:
322 self._logger.critical(
323 'Could not parse results from IxNetwork machine...')
324 raise ValueError('Failed to parse output.')
326 if result_status.group(1) != 'pass':
327 self._logger.critical(
328 'An error occured when running tests...')
329 raise RuntimeError('Ixia failed to initialise.')
331 # transform path into someting useful
333 path = result_path.group(1).replace('\\', '/')
334 path = os.path.join(path, 'AggregateResults.csv')
336 settings.getValue('TRAFFICGEN_IXNET_TESTER_RESULT_DIR'),
337 settings.getValue('TRAFFICGEN_IXNET_DUT_RESULT_DIR'))
340 def parse_ixnet_rfc_results(path):
341 """Parse CSV output of IxNet RFC2544 test run.
343 :param path: Input file path
345 results = OrderedDict()
347 with open(path, 'r') as in_file:
348 reader = csv.reader(in_file, delimiter=',')
351 #Replace null entries added by Ixia with 0s.
352 row = [entry if len(entry) > 0 else '0' for entry in row]
353 # calculate tx fps by (rx fps * (tx % / rx %))
354 tx_fps = float(row[5]) * (float(row[4]) / float(row[3]))
355 # calculate tx mbps by (rx mbps * (tx % / rx %))
356 tx_mbps = float(row[6]) * (float(row[4]) / float(row[3]))
358 if bool(results.get(ResultsConstants.THROUGHPUT_RX_FPS)) \
360 prev_percent_rx = 0.0
363 float(results.get(ResultsConstants.THROUGHPUT_RX_FPS))
364 if float(row[5]) >= prev_percent_rx:
365 results[ResultsConstants.THROUGHPUT_TX_FPS] = tx_fps
366 results[ResultsConstants.THROUGHPUT_RX_FPS] = row[5]
367 results[ResultsConstants.THROUGHPUT_TX_MBPS] = tx_mbps
368 results[ResultsConstants.THROUGHPUT_RX_MBPS] = row[6]
369 results[ResultsConstants.THROUGHPUT_TX_PERCENT] = row[3]
370 results[ResultsConstants.THROUGHPUT_RX_PERCENT] = row[4]
371 results[ResultsConstants.MIN_LATENCY_NS] = row[11]
372 results[ResultsConstants.MAX_LATENCY_NS] = row[12]
373 results[ResultsConstants.AVG_LATENCY_NS] = row[13]
376 output = self.run_tcl('waitForRfc2544Test')
378 # the run_tcl function will return a list with one element. We extract
379 # that one element (a string representation of an IXIA-specific Tcl
380 # datatype), parse it to find the path of the results file then parse
382 return parse_ixnet_rfc_results(parse_result_string(output[0]))
384 def send_rfc2544_back2back(self, traffic=None, trials=1, duration=20,
386 """See ITrafficGenerator for description
388 self.start_rfc2544_back2back(traffic, trials, duration, lossrate)
390 return self.wait_rfc2544_back2back()
392 def start_rfc2544_back2back(self, traffic=None, trials=1, duration=20,
394 """Start transmission.
396 self._bidir = traffic['bidir']
399 self._params['config'] = {
402 'duration': duration,
403 'lossrate': lossrate,
404 'multipleStreams': traffic['multistream'],
405 'rfc2544TestType': 'back2back',
407 self._params['traffic'] = self.traffic_defaults.copy()
410 self._params['traffic'] = trafficgen.merge_spec(
411 self._params['traffic'], traffic)
412 self._cfg['bidir'] = self._bidir
414 for cmd in _build_set_cmds(self._cfg, prefix='set'):
417 for cmd in _build_set_cmds(self._params):
420 output = self.run_tcl('source {%s}' % self._script)
422 self._logger.critical(
423 'An error occured when connecting to IxNetwork machine...')
424 raise RuntimeError('Ixia failed to initialise.')
426 self.run_tcl('startRfc2544Test $config $traffic')
428 self._logger.critical(
429 'Failed to start RFC2544 test')
430 raise RuntimeError('RFC2544 test failed to start.')
432 def wait_rfc2544_back2back(self):
435 def parse_result_string(results):
436 """Get path to results file from output
438 Check for related errors
440 :param results: Text stream from test.
442 :returns: Path to results file.
444 result_status = re.search(_RESULT_RE, results)
445 result_path = re.search(_RESULTPATH_RE, results)
447 if not result_status or not result_path:
448 self._logger.critical(
449 'Could not parse results from IxNetwork machine...')
450 raise ValueError('Failed to parse output.')
452 if result_status.group(1) != 'pass':
453 self._logger.critical(
454 'An error occured when running tests...')
455 raise RuntimeError('Ixia failed to initialise.')
457 # transform path into something useful
459 path = result_path.group(1).replace('\\', '/')
460 path = os.path.join(path, 'iteration.csv')
462 settings.getValue('TRAFFICGEN_IXNET_TESTER_RESULT_DIR'),
463 settings.getValue('TRAFFICGEN_IXNET_DUT_RESULT_DIR'))
467 def parse_ixnet_rfc_results(path):
468 """Parse CSV output of IxNet RFC2544 Back2Back test run.
470 :param path: Input file path
472 :returns: Best parsed result from CSV file.
474 results = OrderedDict()
475 results[ResultsConstants.B2B_FRAMES] = 0
477 with open(path, 'r') as in_file:
478 reader = csv.reader(in_file, delimiter=',')
481 # if back2back count higher than previously found, store it
482 # Note: row[N] here refers to the Nth column of a row
483 if float(row[14]) <= self._params['config']['lossrate']:
485 int(results[ResultsConstants.B2B_FRAMES]):
486 results[ResultsConstants.B2B_FRAMES] = int(row[12])
490 output = self.run_tcl('waitForRfc2544Test')
492 # the run_tcl function will return a list with one element. We extract
493 # that one element (a string representation of an IXIA-specific Tcl
494 # datatype), parse it to find the path of the results file then parse
497 return parse_ixnet_rfc_results(parse_result_string(output[0]))
500 if __name__ == '__main__':
505 'dstip': '10.1.1.254',
510 print(dev.send_cont_traffic())
511 print(dev.send_rfc2544_throughput())