1 # Copyright 2015-2016 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_PORT
23 IxNetwork host port number
24 * TRAFFICGEN_IXNET_USER
25 IxNetwork host user name
26 * TRAFFICGEN_IXNET_TESTER_RESULT_DIR
27 The result directory on the IxNetwork computer
28 * TRAFFICGEN_IXNET_DUT_RESULT_DIR
29 The result directory on DUT. This needs to map to the same directory
32 The following settings are also required. These can likely be shared
33 with an 'Ixia' traffic generator instance:
35 * TRAFFICGEN_IXIA_HOST
36 IXIA chassis IP address
37 * TRAFFICGEN_IXIA_CARD
39 * TRAFFICGEN_IXIA_PORT1
41 * TRAFFICGEN_IXIA_PORT2
44 If any of these don't exist, the application will raise an exception
47 Additional Configuration:
48 -------------------------
50 You will also need to configure the IxNetwork machine to start the IXIA
51 IxNetworkTclServer. This can be started like so:
53 1. Connect to the IxNetwork machine using RDP
60 IxNetwork 7.21.893.14 GA ->
63 Pin a shortcut to this application to the taskbar.
64 3. Before running it right click the pinned shortcut and go to
65 "Properties". Here change the port number to your own port number.
66 This will be the same value as "TRAFFICGEN_IXNET_PORT" above.
67 4. You will find this on the shortcut tab under the heading "Target"
68 5. Finally run it. If you see the following error check that you
69 followed the above steps exactly:
71 ERROR: couldn't open socket : connection refused
76 This method of automation is quite error prone as the IxNetwork API
77 does not give any feedback as to the status of tests. As such, it can
78 be expected that the user have access to the IxNetwork machine should
79 this trafficgen need to be debugged.
88 from collections import OrderedDict
89 from tools.pkt_gen import trafficgen
90 from conf import settings
91 from core.results.results_constants import ResultsConstants
93 _ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
95 _RESULT_RE = r'(?:\{kString,result\},\{kString,)(\w+)(?:\})'
96 _RESULTPATH_RE = r'(?:\{kString,resultPath\},\{kString,)([\\\w\.\-\:]+)(?:\})'
99 def _build_set_cmds(values, prefix='dict set'):
100 """Generate a list of 'dict set' args for Tcl.
102 Parse a dictionary and recursively build the arguments for the
103 'dict set' Tcl command, given that this is of the format:
105 dict set [name...] [key] [value]
107 For example, for a non-nested dict (i.e. a non-dict element):
109 dict set mydict mykey myvalue
111 For a nested dict (i.e. a dict element):
113 dict set mydict mysubdict mykey myvalue
115 :param values: Dictionary to yield values for
116 :param prefix: Prefix to append to output string. Generally the
117 already generated part of the command.
119 :yields: Output strings to be passed to a `Tcl` instance.
124 # Not allowing derived dictionary types for now
125 # pylint: disable=unidiomatic-typecheck
126 if type(value) == dict:
127 _prefix = ' '.join([prefix, key]).strip()
128 for subkey in _build_set_cmds(value, _prefix):
132 # pylint: disable=unidiomatic-typecheck
133 # tcl doesn't recognise the strings "True" or "False", only "1"
134 # or "0". Special case to convert them
135 if type(value) == bool:
136 value = str(int(value))
141 yield ' '.join([prefix, key, value]).strip()
143 yield ' '.join([key, value]).strip()
146 class IxNet(trafficgen.ITrafficGenerator):
147 """A wrapper around IXIA IxNetwork applications.
149 Runs different traffic generator tests through an Ixia traffic
150 generator chassis by generating TCL scripts from templates.
152 Currently only the RFC2544 tests are implemented.
154 if settings.getValue('TRAFFICGEN_IXNET_TCL_SCRIPT') == '':
155 _script = os.path.join(os.path.dirname(__file__), 'ixnetrfc2544.tcl')
157 _script = os.path.join(os.path.dirname(__file__),
158 settings.getValue('TRAFFICGEN_IXNET_TCL_SCRIPT'))
159 _tclsh = tkinter.Tcl()
161 _logger = logging.getLogger(__name__)
165 def run_tcl(self, cmd):
166 """Run a TCL script using the TCL interpreter found in ``tkinter``.
168 :param cmd: Command to execute
170 :returns: Output of command, where applicable.
172 self._logger.debug('%s%s', trafficgen.CMD_PREFIX, cmd)
174 output = self._tclsh.eval(cmd)
176 return output.split()
179 """Configure system for IxNetwork.
182 'lib_path': settings.getValue('TRAFFICGEN_IXNET_LIB_PATH'),
183 # IxNetwork machine configuration
184 'machine': settings.getValue('TRAFFICGEN_IXNET_MACHINE'),
185 'port': settings.getValue('TRAFFICGEN_IXNET_PORT'),
186 'user': settings.getValue('TRAFFICGEN_IXNET_USER'),
187 # IXIA chassis configuration
188 'chassis': settings.getValue('TRAFFICGEN_IXIA_HOST'),
189 'card': settings.getValue('TRAFFICGEN_IXIA_CARD'),
190 'port1': settings.getValue('TRAFFICGEN_IXIA_PORT1'),
191 'port2': settings.getValue('TRAFFICGEN_IXIA_PORT2'),
193 settings.getValue('TRAFFICGEN_IXNET_TESTER_RESULT_DIR'),
196 self._logger.debug('IXIA configuration configuration : %s', self._cfg)
200 def disconnect(self):
201 """Disconnect from Ixia chassis.
205 def send_cont_traffic(self, traffic=None, duration=30):
206 """See ITrafficGenerator for description
208 self.start_cont_traffic(traffic, duration)
210 return self.stop_cont_traffic()
212 def start_cont_traffic(self, traffic=None, duration=30):
213 """Start transmission.
215 self._bidir = traffic['bidir']
218 self._params['config'] = {
219 'binary': False, # don't do binary search and send one stream
220 'duration': duration,
221 'framerate': traffic['frame_rate'],
222 'multipleStreams': traffic['multistream'],
223 'streamType': traffic['stream_type'],
224 'rfc2544TestType': 'throughput',
226 self._params['traffic'] = self.traffic_defaults.copy()
229 self._params['traffic'] = trafficgen.merge_spec(
230 self._params['traffic'], traffic)
231 self._cfg['bidir'] = self._bidir
233 for cmd in _build_set_cmds(self._cfg, prefix='set'):
236 for cmd in _build_set_cmds(self._params):
239 output = self.run_tcl('source {%s}' % self._script)
241 self._logger.critical(
242 'An error occured when connecting to IxNetwork machine...')
243 raise RuntimeError('Ixia failed to initialise.')
245 self.run_tcl('startRfc2544Test $config $traffic')
247 self._logger.critical(
248 'Failed to start continuous traffic test')
249 raise RuntimeError('Continuous traffic test failed to start.')
251 def stop_cont_traffic(self):
252 """See ITrafficGenerator for description
254 return self._wait_result()
256 def send_rfc2544_throughput(self, traffic=None, tests=1, duration=20,
258 """See ITrafficGenerator for description
260 self.start_rfc2544_throughput(traffic, tests, duration, lossrate)
262 return self.wait_rfc2544_throughput()
264 def start_rfc2544_throughput(self, traffic=None, tests=1, duration=20,
266 """Start transmission.
268 self._bidir = traffic['bidir']
271 self._params['config'] = {
274 'duration': duration,
275 'lossrate': lossrate,
276 'multipleStreams': traffic['multistream'],
277 'streamType': traffic['stream_type'],
278 'rfc2544TestType': 'throughput',
280 self._params['traffic'] = self.traffic_defaults.copy()
283 self._params['traffic'] = trafficgen.merge_spec(
284 self._params['traffic'], traffic)
285 self._cfg['bidir'] = self._bidir
287 for cmd in _build_set_cmds(self._cfg, prefix='set'):
290 for cmd in _build_set_cmds(self._params):
293 output = self.run_tcl('source {%s}' % self._script)
295 self._logger.critical(
296 'An error occured when connecting to IxNetwork machine...')
297 raise RuntimeError('Ixia failed to initialise.')
299 self.run_tcl('startRfc2544Test $config $traffic')
301 self._logger.critical(
302 'Failed to start RFC2544 test')
303 raise RuntimeError('RFC2544 test failed to start.')
305 def wait_rfc2544_throughput(self):
306 """See ITrafficGenerator for description
308 return self._wait_result()
310 def _wait_result(self):
313 def parse_result_string(results):
314 """Get path to results file from output
316 Check for related errors
318 :param results: Text stream from test.
320 :returns: Path to results file.
322 result_status = re.search(_RESULT_RE, results)
323 result_path = re.search(_RESULTPATH_RE, results)
325 if not result_status or not result_path:
326 self._logger.critical(
327 'Could not parse results from IxNetwork machine...')
328 raise ValueError('Failed to parse output.')
330 if result_status.group(1) != 'pass':
331 self._logger.critical(
332 'An error occured when running tests...')
333 raise RuntimeError('Ixia failed to initialise.')
335 # transform path into someting useful
337 path = result_path.group(1).replace('\\', '/')
338 path = os.path.join(path, 'AggregateResults.csv')
340 settings.getValue('TRAFFICGEN_IXNET_TESTER_RESULT_DIR'),
341 settings.getValue('TRAFFICGEN_IXNET_DUT_RESULT_DIR'))
344 def parse_ixnet_rfc_results(path):
345 """Parse CSV output of IxNet RFC2544 test run.
347 :param path: Input file path
349 results = OrderedDict()
351 with open(path, 'r') as in_file:
352 reader = csv.reader(in_file, delimiter=',')
355 #Replace null entries added by Ixia with 0s.
356 row = [entry if len(entry) > 0 else '0' for entry in row]
358 # tx_fps and tx_mps cannot be reliably calculated
359 # as the DUT may be modifying the frame size
363 if bool(results.get(ResultsConstants.THROUGHPUT_RX_FPS)) \
365 prev_percent_rx = 0.0
368 float(results.get(ResultsConstants.THROUGHPUT_RX_FPS))
369 if float(row[5]) >= prev_percent_rx:
370 results[ResultsConstants.TX_RATE_FPS] = tx_fps
371 results[ResultsConstants.THROUGHPUT_RX_FPS] = row[5]
372 results[ResultsConstants.TX_RATE_MBPS] = tx_mbps
373 results[ResultsConstants.THROUGHPUT_RX_MBPS] = row[6]
374 results[ResultsConstants.TX_RATE_PERCENT] = row[3]
375 results[ResultsConstants.THROUGHPUT_RX_PERCENT] = row[4]
376 results[ResultsConstants.FRAME_LOSS_PERCENT] = row[10]
377 results[ResultsConstants.MIN_LATENCY_NS] = row[11]
378 results[ResultsConstants.MAX_LATENCY_NS] = row[12]
379 results[ResultsConstants.AVG_LATENCY_NS] = row[13]
382 output = self.run_tcl('waitForRfc2544Test')
384 # the run_tcl function will return a list with one element. We extract
385 # that one element (a string representation of an IXIA-specific Tcl
386 # datatype), parse it to find the path of the results file then parse
388 return parse_ixnet_rfc_results(parse_result_string(output[0]))
390 def send_rfc2544_back2back(self, traffic=None, tests=1, duration=2,
392 """See ITrafficGenerator for description
394 # NOTE 2 seconds is the recommended duration for a back 2 back
395 # test in RFC2544. 50 trials is the recommended number from the
397 self.start_rfc2544_back2back(traffic, tests, duration, lossrate)
399 return self.wait_rfc2544_back2back()
401 def start_rfc2544_back2back(self, traffic=None, tests=1, duration=2,
403 """Start transmission.
405 self._bidir = traffic['bidir']
408 self._params['config'] = {
411 'duration': duration,
412 'lossrate': lossrate,
413 'multipleStreams': traffic['multistream'],
414 'streamType': traffic['stream_type'],
415 'rfc2544TestType': 'back2back',
417 self._params['traffic'] = self.traffic_defaults.copy()
420 self._params['traffic'] = trafficgen.merge_spec(
421 self._params['traffic'], traffic)
422 self._cfg['bidir'] = self._bidir
424 for cmd in _build_set_cmds(self._cfg, prefix='set'):
427 for cmd in _build_set_cmds(self._params):
430 output = self.run_tcl('source {%s}' % self._script)
432 self._logger.critical(
433 'An error occured when connecting to IxNetwork machine...')
434 raise RuntimeError('Ixia failed to initialise.')
436 self.run_tcl('startRfc2544Test $config $traffic')
438 self._logger.critical(
439 'Failed to start RFC2544 test')
440 raise RuntimeError('RFC2544 test failed to start.')
442 def wait_rfc2544_back2back(self):
445 def parse_result_string(results):
446 """Get path to results file from output
448 Check for related errors
450 :param results: Text stream from test.
452 :returns: Path to results file.
454 result_status = re.search(_RESULT_RE, results)
455 result_path = re.search(_RESULTPATH_RE, results)
457 if not result_status or not result_path:
458 self._logger.critical(
459 'Could not parse results from IxNetwork machine...')
460 raise ValueError('Failed to parse output.')
462 if result_status.group(1) != 'pass':
463 self._logger.critical(
464 'An error occured when running tests...')
465 raise RuntimeError('Ixia failed to initialise.')
467 # transform path into something useful
469 path = result_path.group(1).replace('\\', '/')
470 path = os.path.join(path, 'iteration.csv')
472 settings.getValue('TRAFFICGEN_IXNET_TESTER_RESULT_DIR'),
473 settings.getValue('TRAFFICGEN_IXNET_DUT_RESULT_DIR'))
477 def parse_ixnet_rfc_results(path):
478 """Parse CSV output of IxNet RFC2544 Back2Back test run.
480 :param path: Input file path
482 :returns: Best parsed result from CSV file.
484 results = OrderedDict()
485 results[ResultsConstants.B2B_FRAMES] = 0
486 results[ResultsConstants.B2B_FRAME_LOSS_PERCENT] = 100
488 with open(path, 'r') as in_file:
489 reader = csv.reader(in_file, delimiter=',')
492 # if back2back count higher than previously found, store it
493 # Note: row[N] here refers to the Nth column of a row
494 if float(row[14]) <= self._params['config']['lossrate']:
496 int(results[ResultsConstants.B2B_FRAMES]):
497 results[ResultsConstants.B2B_FRAMES] = int(row[12])
498 results[ResultsConstants.B2B_FRAME_LOSS_PERCENT] = float(row[14])
502 output = self.run_tcl('waitForRfc2544Test')
504 # the run_tcl function will return a list with one element. We extract
505 # that one element (a string representation of an IXIA-specific Tcl
506 # datatype), parse it to find the path of the results file then parse
509 return parse_ixnet_rfc_results(parse_result_string(output[0]))
512 if __name__ == '__main__':
517 'dstip': '10.1.1.254',
522 print(dev.send_cont_traffic())
523 print(dev.send_rfc2544_throughput())