1 # Copyright (c) 2019 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 """Performance testing traffic generator library."""
18 from robot.api import logger
19 from robot.libraries.BuiltIn import BuiltIn
21 from .DropRateSearch import DropRateSearch
22 from .Constants import Constants
23 from .ssh import SSH, exec_cmd_no_error
24 from .topology import NodeType
25 from .topology import NodeSubTypeTG
26 from .topology import Topology
27 from .MLRsearch.AbstractMeasurer import AbstractMeasurer
28 from .MLRsearch.MultipleLossRatioSearch import MultipleLossRatioSearch
29 from .MLRsearch.ReceiveRateMeasurement import ReceiveRateMeasurement
30 from .PLRsearch.PLRsearch import PLRsearch
32 __all__ = ['TGDropRateSearchImpl', 'TrafficGenerator', 'OptimizedSearch']
35 def check_subtype(node):
36 """Return supported subtype of given node, or raise an exception.
38 Currently only one subtype is supported,
39 but we want our code to be ready for other ones.
41 :param node: Topology node to check. Can be None.
42 :type node: dict or NoneType
43 :returns: Subtype detected.
45 :raises RuntimeError: If node is not supported, message explains how.
47 if node.get('type') is None:
48 raise RuntimeError('Node type is not defined')
49 elif node['type'] != NodeType.TG:
50 raise RuntimeError('Node type is {typ!r}, not a TG'.format(
52 elif node.get('subtype') is None:
53 raise RuntimeError('TG subtype is not defined')
54 elif node['subtype'] == NodeSubTypeTG.TREX:
55 return NodeSubTypeTG.TREX
56 raise RuntimeError('TG subtype {sub!r} is not supported'.format(
60 class TGDropRateSearchImpl(DropRateSearch):
61 """Drop Rate Search implementation."""
64 super(TGDropRateSearchImpl, self).__init__()
66 def measure_loss(self, rate, frame_size, loss_acceptance,
67 loss_acceptance_type, traffic_profile, skip_warmup=False):
68 """Runs the traffic and evaluate the measured results.
70 :param rate: Offered traffic load.
71 :param frame_size: Size of frame.
72 :param loss_acceptance: Permitted drop ratio or frames count.
73 :param loss_acceptance_type: Type of permitted loss.
74 :param traffic_profile: Module name as a traffic profile identifier.
75 See resources/traffic_profiles/trex for implemented modules.
76 :param skip_warmup: Start TRex without warmup traffic if true.
79 :type loss_acceptance: float
80 :type loss_acceptance_type: LossAcceptanceType
81 :type traffic_profile: str
82 :type skip_warmup: bool
83 :returns: Drop threshold exceeded? (True/False)
85 :raises NotImplementedError: If TG is not supported.
86 :raises RuntimeError: If TG is not specified.
88 # we need instance of TrafficGenerator instantiated by Robot Framework
89 # to be able to use trex_stl-*()
90 tg_instance = BuiltIn().get_library_instance(
91 'resources.libraries.python.TrafficGenerator')
92 subtype = check_subtype(tg_instance.node)
93 if subtype == NodeSubTypeTG.TREX:
94 unit_rate = str(rate) + self.get_rate_type_str()
96 tg_instance.trex_stl_start_remote_exec(
97 self.get_duration(), unit_rate, frame_size, traffic_profile,
100 tg_instance.trex_stl_start_remote_exec(
101 self.get_duration(), unit_rate, frame_size, traffic_profile)
102 loss = tg_instance.get_loss()
103 sent = tg_instance.get_sent()
104 if self.loss_acceptance_type_is_percentage():
105 loss = (float(loss) / float(sent)) * 100
106 logger.trace("comparing: {los} < {acc} {typ}".format(
107 los=loss, acc=loss_acceptance, typ=loss_acceptance_type))
108 return float(loss) <= float(loss_acceptance)
111 def get_latency(self):
112 """Returns min/avg/max latency.
114 :returns: Latency stats.
117 tg_instance = BuiltIn().get_library_instance(
118 'resources.libraries.python.TrafficGenerator')
119 return tg_instance.get_latency_int()
122 class TrafficGenerator(AbstractMeasurer):
123 """Traffic Generator.
125 FIXME: Describe API."""
127 # TODO: Decrease friction between various search and rate provider APIs.
128 # TODO: Remove "trex" from lines which could work with other TGs.
130 # Use one instance of TrafficGenerator for all tests in test suite
131 ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
134 # TODO: Number of fields will be reduced with CSIT-1378.
136 # T-REX interface order mapping
137 self._ifaces_reordered = False
138 # Result holding fields, to be removed.
143 self._received = None
144 # Measurement input fields, needed for async stop result.
145 self._start_time = None
147 # Other input parameters, not knowable from measure() signature.
148 self.frame_size = None
149 self.traffic_profile = None
150 self.warmup_time = None
151 # TODO: Rename "xstats" to something opaque, so TRex is not privileged?
152 self._xstats = (None, None)
158 :returns: Traffic generator node.
164 """Return number of lost packets.
166 :returns: Number of lost packets.
172 """Return number of sent packets.
174 :returns: Number of sent packets.
179 def get_received(self):
180 """Return number of received packets.
182 :returns: Number of received packets.
185 return self._received
187 def get_latency_int(self):
188 """Return rounded min/avg/max latency.
190 :returns: Latency stats.
195 def initialize_traffic_generator(
196 self, tg_node, tg_if1, tg_if2, tg_if1_adj_node, tg_if1_adj_if,
197 tg_if2_adj_node, tg_if2_adj_if, osi_layer, tg_if1_dst_mac=None,
198 tg_if2_dst_mac=None):
199 """TG initialization.
201 TODO: Document why do we need (and how do we use) _ifaces_reordered.
203 :param tg_node: Traffic generator node.
204 :param tg_if1: TG - name of first interface.
205 :param tg_if2: TG - name of second interface.
206 :param tg_if1_adj_node: TG if1 adjecent node.
207 :param tg_if1_adj_if: TG if1 adjecent interface.
208 :param tg_if2_adj_node: TG if2 adjecent node.
209 :param tg_if2_adj_if: TG if2 adjecent interface.
210 :param osi_layer: 'L2', 'L3' or 'L7' - OSI Layer testing type.
211 :param tg_if1_dst_mac: Interface 1 destination MAC address.
212 :param tg_if2_dst_mac: Interface 2 destination MAC address.
216 :type tg_if1_adj_node: dict
217 :type tg_if1_adj_if: str
218 :type tg_if2_adj_node: dict
219 :type tg_if2_adj_if: str
221 :type tg_if1_dst_mac: str
222 :type tg_if2_dst_mac: str
224 :raises RuntimeError: In case of issue during initialization.
226 subtype = check_subtype(tg_node)
227 if subtype == NodeSubTypeTG.TREX:
231 ssh.connect(self._node)
233 (ret, _, _) = ssh.exec_command(
234 "sudo -E sh -c '{0}/resources/tools/trex/"
235 "trex_installer.sh {1}'".format(Constants.REMOTE_FW_DIR,
236 Constants.TREX_INSTALL_VERSION),
239 raise RuntimeError('TRex installation failed.')
241 if1_pci = Topology().get_interface_pci_addr(self._node, tg_if1)
242 if2_pci = Topology().get_interface_pci_addr(self._node, tg_if2)
243 if1_addr = Topology().get_interface_mac(self._node, tg_if1)
244 if2_addr = Topology().get_interface_mac(self._node, tg_if2)
246 if osi_layer == 'L2':
247 if1_adj_addr = if2_addr
248 if2_adj_addr = if1_addr
249 elif osi_layer == 'L3':
250 if1_adj_addr = Topology().get_interface_mac(tg_if1_adj_node,
252 if2_adj_addr = Topology().get_interface_mac(tg_if2_adj_node,
254 elif osi_layer == 'L7':
255 if1_addr = Topology().get_interface_ip4(self._node, tg_if1)
256 if2_addr = Topology().get_interface_ip4(self._node, tg_if2)
257 if1_adj_addr = Topology().get_interface_ip4(tg_if1_adj_node,
259 if2_adj_addr = Topology().get_interface_ip4(tg_if2_adj_node,
262 raise ValueError("Unknown Test Type")
264 # in case of switched environment we can override MAC addresses
265 if tg_if1_dst_mac is not None and tg_if2_dst_mac is not None:
266 if1_adj_addr = tg_if1_dst_mac
267 if2_adj_addr = tg_if2_dst_mac
269 if min(if1_pci, if2_pci) != if1_pci:
270 if1_pci, if2_pci = if2_pci, if1_pci
271 if1_addr, if2_addr = if2_addr, if1_addr
272 if1_adj_addr, if2_adj_addr = if2_adj_addr, if1_adj_addr
273 self._ifaces_reordered = True
275 if osi_layer == 'L2' or osi_layer == 'L3':
276 (ret, _, _) = ssh.exec_command(
277 "sudo sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
279 " interfaces: [\"{0}\",\"{1}\"]\n"
281 " - dest_mac: [{2}]\n"
283 " - dest_mac: [{4}]\n"
286 .format(if1_pci, if2_pci,
287 "0x"+if1_adj_addr.replace(":", ",0x"),
288 "0x"+if1_addr.replace(":", ",0x"),
289 "0x"+if2_adj_addr.replace(":", ",0x"),
290 "0x"+if2_addr.replace(":", ",0x")))
291 elif osi_layer == 'L7':
292 (ret, _, _) = ssh.exec_command(
293 "sudo sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
295 " interfaces: [\"{0}\",\"{1}\"]\n"
298 " default_gw: [{3}]\n"
300 " default_gw: [{5}]\n"
302 .format(if1_pci, if2_pci,
303 if1_addr, if1_adj_addr,
304 if2_addr, if2_adj_addr))
306 raise ValueError("Unknown Test Type")
308 raise RuntimeError('TRex config generation error')
310 self._startup_trex(osi_layer)
312 def _startup_trex(self, osi_layer):
313 """Startup sequence for the TRex traffic generator.
315 :param osi_layer: 'L2', 'L3' or 'L7' - OSI Layer testing type.
317 :raises RuntimeError: If node subtype is not a TREX or startup failed.
319 # No need to check subtype, we know it is TREX.
320 for _ in range(0, 3):
321 # Kill TRex only if it is already running.
322 cmd = "sh -c 'pgrep t-rex && pkill t-rex && sleep 3 || true'"
324 self._node, cmd, sudo=True, message='Kill TRex failed!')
328 for port in self._node['interfaces'].values():
329 ports += ' {pci}'.format(pci=port.get('pci_address'))
331 cmd = ("sh -c 'cd {dir}/scripts/ && "
332 "./dpdk_nic_bind.py -u {ports} || true'"
333 .format(dir=Constants.TREX_INSTALL_DIR, ports=ports))
335 self._node, cmd, sudo=True,
336 message='Unbind PCI ports from driver failed!')
338 cmd = ("sh -c 'cd {dir}/scripts/ && ./trex-cfg'"
339 .format(dir=Constants.TREX_INSTALL_DIR))
341 self._node, cmd, sudo=True, message='Config TRex failed!')
344 cmd = ("sh -c 'cd {dir}/scripts/ && "
345 "nohup ./t-rex-64 {mode} --prefix $(hostname)"
346 " -i -c 7 > /tmp/trex.log 2>&1 &' > /dev/null"
347 .format(dir=Constants.TREX_INSTALL_DIR,
348 mode='--astf' if osi_layer == 'L7' else ''))
350 exec_cmd_no_error(self._node, cmd, sudo=True)
352 cmd = "sh -c 'cat /tmp/trex.log'"
353 exec_cmd_no_error(self._node, cmd, sudo=True,
354 message='Get TRex logs failed!')
355 raise RuntimeError('Start TRex failed!')
357 # Test if TRex starts successfuly.
358 cmd = ("sh -c '{dir}/resources/tools/trex/trex_server_info.py'"
359 .format(dir=Constants.REMOTE_FW_DIR))
362 self._node, cmd, sudo=True, message='Test TRex failed!',
367 # After max retries TRex is still not responding to API critical error
369 raise RuntimeError('Start TRex failed after multiple retries!')
372 def is_trex_running(node):
373 """Check if TRex is running using pidof.
375 :param node: Traffic generator node.
377 :returns: True if TRex is running otherwise False.
379 :raises RuntimeError: If node type is not a TG.
381 # No need to check subtype, we know it is TREX.
385 ret, _, _ = ssh.exec_command_sudo("pidof t-rex")
386 return bool(int(ret) == 0)
389 def teardown_traffic_generator(node):
392 :param node: Traffic generator node.
395 :raises RuntimeError: If node type is not a TG,
396 or if TRex teardown fails.
398 subtype = check_subtype(node)
399 if subtype == NodeSubTypeTG.TREX:
402 (ret, _, _) = ssh.exec_command(
403 "sh -c 'sudo pkill t-rex && sleep 3'")
405 raise RuntimeError('pkill t-rex failed')
407 def _parse_traffic_results(self, stdout):
408 """Parse stdout of scripts into fields of self.
410 Block of code to reuse, by sync start, or stop after async.
411 TODO: Is the output TG subtype dependent?
413 :param stdout: Text containing the standard output.
416 # last line from console output
417 line = stdout.splitlines()[-1]
419 logger.info('TrafficGen result: {0}'.format(self._result))
420 self._received = self._result.split(', ')[1].split('=')[1]
421 self._sent = self._result.split(', ')[2].split('=')[1]
422 self._loss = self._result.split(', ')[3].split('=')[1]
424 self._latency.append(self._result.split(', ')[4].split('=')[1])
425 self._latency.append(self._result.split(', ')[5].split('=')[1])
427 def trex_stl_stop_remote_exec(self, node):
428 """Execute script on remote node over ssh to stop running traffic.
430 Internal state is updated with measurement results.
432 :param node: TRex generator node.
434 :raises RuntimeError: If stop traffic script fails.
436 # No need to check subtype, we know it is TREX.
441 for index, value in enumerate(self._xstats):
442 if value is not None:
443 # Nested quoting is fun.
444 value = value.replace("'", "\"")
445 x_args += " --xstat{i}='\"'\"'{v}'\"'\"'".format(
447 (ret, stdout, _) = ssh.exec_command(
448 "sh -c '{d}/resources/tools/trex/trex_stateless_stop.py{a}'"\
449 .format(d=Constants.REMOTE_FW_DIR, a=x_args))
452 raise RuntimeError('TRex stateless runtime error')
454 self._parse_traffic_results(stdout)
456 def trex_stl_start_remote_exec(
457 self, duration, rate, frame_size, traffic_profile, async_call=False,
458 latency=True, warmup_time=5.0, unidirection=False, tx_port=0,
460 """Execute script on remote node over ssh to start traffic.
462 In sync mode, measurement results are stored internally.
463 In async mode, initial data including xstats are stored internally.
465 :param duration: Time expresed in seconds for how long to send traffic.
466 :param rate: Traffic rate expressed with units (pps, %)
467 :param frame_size: L2 frame size to send (without padding and IPG).
468 :param traffic_profile: Module name as a traffic profile identifier.
469 See resources/traffic_profiles/trex for implemented modules.
470 :param async_call: If enabled then don't wait for all incomming trafic.
471 :param latency: With latency measurement.
472 :param warmup_time: Warmup time period.
473 :param unidirection: Traffic is unidirectional. Default: False
474 :param tx_port: Traffic generator transmit port for first flow.
476 :param rx_port: Traffic generator receive port for first flow.
478 :type duration: float
480 :type frame_size: str
481 :type traffic_profile: str
482 :type async_call: bool
484 :type warmup_time: float
485 :type unidirection: bool
488 :raises RuntimeError: In case of TG driver issue.
490 # No need to check subtype, we know it is TREX.
492 ssh.connect(self._node)
493 reorder = self._ifaces_reordered # Just to make the next line fit.
494 p_0, p_1 = (rx_port, tx_port) if reorder else (tx_port, rx_port)
495 # Values from Robot can introduce type unicode,
496 # we need to encode them, so that repr() does not lead with 'u'.
497 if isinstance(rate, unicode):
498 rate = rate.encode("utf-8")
499 if isinstance(duration, unicode):
500 duration = duration.encode("utf-8")
501 if isinstance(warmup_time, unicode):
502 warmup_time = warmup_time.encode("utf-8")
504 "sh -c '{tool}/resources/tools/trex/trex_stateless_profile.py"
505 " --profile {prof}/resources/traffic_profiles/trex/{traffic}.py"
506 " --duration {duration!r} --frame_size {frame_size} --rate {rate!r}"
507 " --warmup_time {warmup!r} --port_0 {p_0} --port_1 {p_1}").format(
508 tool=Constants.REMOTE_FW_DIR, prof=Constants.REMOTE_FW_DIR,
509 traffic=traffic_profile, duration=duration,
510 frame_size=frame_size, rate=rate, warmup=warmup_time, p_0=p_0,
513 command += " --async_start"
515 command += " --latency"
517 command += " --unidirection"
520 (ret, stdout, _) = ssh.exec_command(
521 command, timeout=float(duration) + 60)
524 raise RuntimeError('TRex stateless runtime error')
527 self._start_time = time.time()
528 self._rate = float(rate[:-3]) if "pps" in rate else float(rate)
529 self._received = None
533 xstats = [None, None]
535 for line in stdout.splitlines():
536 if "Xstats snapshot {i}: ".format(i=index) in line:
537 xstats[index] = line[19:]
541 self._xstats = tuple(xstats)
543 self._parse_traffic_results(stdout)
544 self._start_time = None
547 def stop_traffic_on_tg(self):
548 """Stop all traffic on TG.
550 :returns: Structure containing the result of the measurement.
551 :rtype: ReceiveRateMeasurement
552 :raises RuntimeError: If TG is not set.
554 subtype = check_subtype(self._node)
555 if subtype == NodeSubTypeTG.TREX:
556 self.trex_stl_stop_remote_exec(self._node)
557 return self.get_measurement_result()
559 def send_traffic_on_tg(
560 self, duration, rate, frame_size, traffic_profile, warmup_time=5,
561 async_call=False, latency=True, unidirection=False, tx_port=0,
563 """Send traffic from all configured interfaces on TG.
565 In async mode, xstats is stored internally,
566 to enable getting correct result when stopping the traffic.
567 In both modes, stdout is returned,
568 but _parse_traffic_results only works in sync output.
570 Note that bidirectional traffic also contains flows
571 transmitted from rx_port and received in tx_port.
572 But some tests use asymmetric traffic, so those arguments are relevant.
574 Also note that traffic generator uses DPDK driver which might
575 reorder port numbers based on wiring and PCI numbering.
576 This method handles that, so argument values are invariant,
577 but you can see swapped valued in debug logs.
579 TODO: Is it better to have less descriptive argument names
580 just to make them less probable to be viewed as misleading or confusing?
581 See https://gerrit.fd.io/r/#/c/17625/11/resources/libraries/python\
582 /TrafficGenerator.py@406
584 :param duration: Duration of test traffic generation in seconds.
585 :param rate: Offered load per interface (e.g. 1%, 3gbps, 4mpps, ...).
586 :param frame_size: Frame size (L2) in Bytes.
587 :param traffic_profile: Module name as a traffic profile identifier.
588 See resources/traffic_profiles/trex for implemented modules.
589 :param warmup_time: Warmup phase in seconds.
590 :param async_call: Async mode.
591 :param latency: With latency measurement.
592 :param unidirection: Traffic is unidirectional. Default: False
593 :param tx_port: Traffic generator transmit port for first flow.
595 :param rx_port: Traffic generator receive port for first flow.
599 :type frame_size: str
600 :type traffic_profile: str
601 :type warmup_time: float
602 :type async_call: bool
604 :type unidirection: bool
609 :raises RuntimeError: If TG is not set, or if node is not TG,
610 or if subtype is not specified.
611 :raises NotImplementedError: If TG is not supported.
613 subtype = check_subtype(self._node)
614 if subtype == NodeSubTypeTG.TREX:
615 self.trex_stl_start_remote_exec(
616 duration, rate, frame_size, traffic_profile, async_call,
617 latency, warmup_time, unidirection, tx_port, rx_port)
621 def no_traffic_loss_occurred(self):
622 """Fail if loss occurred in traffic run.
625 :raises Exception: If loss occured.
627 if self._loss is None:
628 raise RuntimeError('The traffic generation has not been issued')
629 if self._loss != '0':
630 raise RuntimeError('Traffic loss occurred: {0}'.format(self._loss))
632 def fail_if_no_traffic_forwarded(self):
633 """Fail if no traffic forwarded.
636 :raises Exception: If no traffic forwarded.
638 if self._received is None:
639 raise RuntimeError('The traffic generation has not been issued')
640 if self._received == '0':
641 raise RuntimeError('No traffic forwarded')
643 def partial_traffic_loss_accepted(self, loss_acceptance,
644 loss_acceptance_type):
645 """Fail if loss is higher then accepted in traffic run.
647 :param loss_acceptance: Permitted drop ratio or frames count.
648 :param loss_acceptance_type: Type of permitted loss.
649 :type loss_acceptance: float
650 :type loss_acceptance_type: LossAcceptanceType
652 :raises Exception: If loss is above acceptance criteria.
654 if self._loss is None:
655 raise Exception('The traffic generation has not been issued')
657 if loss_acceptance_type == 'percentage':
658 loss = (float(self._loss) / float(self._sent)) * 100
659 elif loss_acceptance_type == 'frames':
660 loss = float(self._loss)
662 raise Exception('Loss acceptance type not supported')
664 if loss > float(loss_acceptance):
665 raise Exception("Traffic loss {} above loss acceptance: {}".format(
666 loss, loss_acceptance))
668 def set_rate_provider_defaults(self, frame_size, traffic_profile,
670 """Store values accessed by measure().
672 :param frame_size: Frame size identifier or value [B].
673 :param traffic_profile: Module name as a traffic profile identifier.
674 See resources/traffic_profiles/trex for implemented modules.
675 :param warmup_time: Traffic duration before measurement starts [s].
676 :type frame_size: str or int
677 :type traffic_profile: str
678 :type warmup_time: float
680 self.frame_size = frame_size
681 self.traffic_profile = str(traffic_profile)
682 self.warmup_time = float(warmup_time)
684 def get_measurement_result(self, duration=None, transmit_rate=None):
685 """Return the result of last measurement as ReceiveRateMeasurement.
687 Separate function, as measurements can end either by time
688 or by explicit call, this is the common block at the end.
690 TODO: Fail on running or already reported measurement.
692 :param duration: Measurement duration [s] if known beforehand.
693 For explicitly stopped measurement it is estimated.
694 :param transmit_rate: Target aggregate transmit rate [pps].
695 If not given, computed assuming it was bidirectional.
696 :type duration: float or NoneType
697 :type transmit_rate: float or NoneType
698 :returns: Structure containing the result of the measurement.
699 :rtype: ReceiveRateMeasurement
702 duration = time.time() - self._start_time
703 self._start_time = None
704 if transmit_rate is None:
705 # Assuming bi-directional traffic here.
706 transmit_rate = self._rate * 2.0
707 transmit_count = int(self.get_sent())
708 loss_count = int(self.get_loss())
709 measurement = ReceiveRateMeasurement(
710 duration, transmit_rate, transmit_count, loss_count)
711 measurement.latency = self.get_latency_int()
714 def measure(self, duration, transmit_rate):
715 """Run bi-directional measurement, parse and return results.
717 :param duration: Trial duration [s].
718 :param transmit_rate: Target bidirectional transmit rate [pps].
719 :type duration: float
720 :type transmit_rate: float
721 :returns: Structure containing the result of the measurement.
722 :rtype: ReceiveRateMeasurement
723 :raises RuntimeError: If TG is not set, or if node is not TG,
724 or if subtype is not specified.
725 :raises NotImplementedError: If TG is not supported.
727 duration = float(duration)
728 transmit_rate = float(transmit_rate)
729 # TG needs target Tr per stream, but reports aggregate Tx and Dx.
730 unit_rate = str(transmit_rate / 2.0) + "pps"
731 self.send_traffic_on_tg(
732 duration, unit_rate, self.frame_size, self.traffic_profile,
733 warmup_time=self.warmup_time, latency=True)
734 return self.get_measurement_result(duration, transmit_rate)
737 class OptimizedSearch(object):
738 """Class to be imported as Robot Library, containing a single keyword."""
741 def perform_optimized_ndrpdr_search(
742 frame_size, traffic_profile, minimum_transmit_rate,
743 maximum_transmit_rate, packet_loss_ratio=0.005,
744 final_relative_width=0.005, final_trial_duration=30.0,
745 initial_trial_duration=1.0, number_of_intermediate_phases=2,
746 timeout=720.0, doublings=1):
747 """Setup initialized TG, perform optimized search, return intervals.
749 :param frame_size: Frame size identifier or value [B].
750 :param traffic_profile: Module name as a traffic profile identifier.
751 See resources/traffic_profiles/trex for implemented modules.
752 :param minimum_transmit_rate: Minimal bidirectional
753 target transmit rate [pps].
754 :param maximum_transmit_rate: Maximal bidirectional
755 target transmit rate [pps].
756 :param packet_loss_ratio: Fraction of packets lost, for PDR [1].
757 :param final_relative_width: Final lower bound transmit rate
758 cannot be more distant that this multiple of upper bound [1].
759 :param final_trial_duration: Trial duration for the final phase [s].
760 :param initial_trial_duration: Trial duration for the initial phase
761 and also for the first intermediate phase [s].
762 :param number_of_intermediate_phases: Number of intermediate phases
763 to perform before the final phase [1].
764 :param timeout: The search will fail itself when not finished
765 before this overall time [s].
766 :param doublings: How many doublings to do in external search step.
767 Default 1 is suitable for fairly stable tests,
768 less stable tests might get better overal duration with 2 or more.
769 :type frame_size: str or int
770 :type traffic_profile: str
771 :type minimum_transmit_rate: float
772 :type maximum_transmit_rate: float
773 :type packet_loss_ratio: float
774 :type final_relative_width: float
775 :type final_trial_duration: float
776 :type initial_trial_duration: float
777 :type number_of_intermediate_phases: int
780 :returns: Structure containing narrowed down NDR and PDR intervals
781 and their measurements.
783 :raises RuntimeError: If total duration is larger than timeout.
785 # we need instance of TrafficGenerator instantiated by Robot Framework
786 # to be able to use trex_stl-*()
787 tg_instance = BuiltIn().get_library_instance(
788 'resources.libraries.python.TrafficGenerator')
789 tg_instance.set_rate_provider_defaults(frame_size, traffic_profile)
790 algorithm = MultipleLossRatioSearch(
791 measurer=tg_instance, final_trial_duration=final_trial_duration,
792 final_relative_width=final_relative_width,
793 number_of_intermediate_phases=number_of_intermediate_phases,
794 initial_trial_duration=initial_trial_duration, timeout=timeout,
796 result = algorithm.narrow_down_ndr_and_pdr(
797 minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio)
801 def perform_soak_search(
802 frame_size, traffic_profile, minimum_transmit_rate,
803 maximum_transmit_rate, plr_target=1e-7, tdpt=0.1,
804 initial_count=50, timeout=1800.0, trace_enabled=False):
805 """Setup initialized TG, perform soak search, return avg and stdev.
807 :param frame_size: Frame size identifier or value [B].
808 :param traffic_profile: Module name as a traffic profile identifier.
809 See resources/traffic_profiles/trex for implemented modules.
810 :param minimum_transmit_rate: Minimal bidirectional
811 target transmit rate [pps].
812 :param maximum_transmit_rate: Maximal bidirectional
813 target transmit rate [pps].
814 :param plr_target: Fraction of packets lost to achieve [1].
815 :param tdpt: Trial duration per trial.
816 The algorithm linearly increases trial duration with trial number,
817 this is the increment between succesive trials, in seconds.
818 :param initial_count: Offset to apply before the first trial.
819 For example initial_count=50 makes first trial to be 51*tdpt long.
820 This is needed because initial "search" phase of integrator
821 takes significant time even without any trial results.
822 :param timeout: The search will stop after this overall time [s].
823 :type frame_size: str or int
824 :type traffic_profile: str
825 :type minimum_transmit_rate: float
826 :type maximum_transmit_rate: float
827 :type plr_target: float
828 :type initial_count: int
830 :returns: Average and stdev of estimated bidirectional rate giving PLR.
831 :rtype: 2-tuple of float
833 tg_instance = BuiltIn().get_library_instance(
834 'resources.libraries.python.TrafficGenerator')
835 tg_instance.set_rate_provider_defaults(frame_size, traffic_profile)
836 algorithm = PLRsearch(
837 measurer=tg_instance, trial_duration_per_trial=tdpt,
838 packet_loss_ratio_target=plr_target,
839 trial_number_offset=initial_count, timeout=timeout,
840 trace_enabled=trace_enabled)
841 result = algorithm.search(minimum_transmit_rate, maximum_transmit_rate)