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 exec_cmd_no_error, exec_cmd
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)
110 def get_latency(self):
111 """Returns min/avg/max latency.
113 :returns: Latency stats.
116 tg_instance = BuiltIn().get_library_instance(
117 'resources.libraries.python.TrafficGenerator')
118 return tg_instance.get_latency_int()
121 class TrafficGenerator(AbstractMeasurer):
122 """Traffic Generator.
124 FIXME: Describe API."""
126 # TODO: Decrease friction between various search and rate provider APIs.
127 # TODO: Remove "trex" from lines which could work with other TGs.
129 # Use one instance of TrafficGenerator for all tests in test suite
130 ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
133 # TODO: Number of fields will be reduced with CSIT-1378.
135 # T-REX interface order mapping
136 self._ifaces_reordered = False
137 # Result holding fields, to be removed.
142 self._received = None
143 # Measurement input fields, needed for async stop result.
144 self._start_time = None
146 # Other input parameters, not knowable from measure() signature.
147 self.frame_size = None
148 self.traffic_profile = None
149 self.warmup_time = None
155 :returns: Traffic generator node.
161 """Return number of lost packets.
163 :returns: Number of lost packets.
169 """Return number of sent packets.
171 :returns: Number of sent packets.
176 def get_received(self):
177 """Return number of received packets.
179 :returns: Number of received packets.
182 return self._received
184 def get_latency_int(self):
185 """Return rounded min/avg/max latency.
187 :returns: Latency stats.
192 def initialize_traffic_generator(
193 self, tg_node, tg_if1, tg_if2, tg_if1_adj_node, tg_if1_adj_if,
194 tg_if2_adj_node, tg_if2_adj_if, osi_layer, tg_if1_dst_mac=None,
195 tg_if2_dst_mac=None):
196 """TG initialization.
198 TODO: Document why do we need (and how do we use) _ifaces_reordered.
200 :param tg_node: Traffic generator node.
201 :param tg_if1: TG - name of first interface.
202 :param tg_if2: TG - name of second interface.
203 :param tg_if1_adj_node: TG if1 adjecent node.
204 :param tg_if1_adj_if: TG if1 adjecent interface.
205 :param tg_if2_adj_node: TG if2 adjecent node.
206 :param tg_if2_adj_if: TG if2 adjecent interface.
207 :param osi_layer: 'L2', 'L3' or 'L7' - OSI Layer testing type.
208 :param tg_if1_dst_mac: Interface 1 destination MAC address.
209 :param tg_if2_dst_mac: Interface 2 destination MAC address.
213 :type tg_if1_adj_node: dict
214 :type tg_if1_adj_if: str
215 :type tg_if2_adj_node: dict
216 :type tg_if2_adj_if: str
218 :type tg_if1_dst_mac: str
219 :type tg_if2_dst_mac: str
221 :raises RuntimeError: In case of issue during initialization.
223 subtype = check_subtype(tg_node)
224 if subtype == NodeSubTypeTG.TREX:
229 "sh -c '{0}/resources/tools/trex/"
230 "trex_installer.sh {1}'".format(Constants.REMOTE_FW_DIR,
231 Constants.TREX_INSTALL_VERSION),
232 sudo=True, timeout=1800, message='TRex installation failed.')
234 if1_pci = Topology().get_interface_pci_addr(self._node, tg_if1)
235 if2_pci = Topology().get_interface_pci_addr(self._node, tg_if2)
236 if1_addr = Topology().get_interface_mac(self._node, tg_if1)
237 if2_addr = Topology().get_interface_mac(self._node, tg_if2)
239 if osi_layer == 'L2':
240 if1_adj_addr = if2_addr
241 if2_adj_addr = if1_addr
242 elif osi_layer == 'L3':
243 if1_adj_addr = Topology().get_interface_mac(tg_if1_adj_node,
245 if2_adj_addr = Topology().get_interface_mac(tg_if2_adj_node,
247 elif osi_layer == 'L7':
248 if1_addr = Topology().get_interface_ip4(self._node, tg_if1)
249 if2_addr = Topology().get_interface_ip4(self._node, tg_if2)
250 if1_adj_addr = Topology().get_interface_ip4(tg_if1_adj_node,
252 if2_adj_addr = Topology().get_interface_ip4(tg_if2_adj_node,
255 raise ValueError("Unknown Test Type")
257 # in case of switched environment we can override MAC addresses
258 if tg_if1_dst_mac is not None and tg_if2_dst_mac is not None:
259 if1_adj_addr = tg_if1_dst_mac
260 if2_adj_addr = tg_if2_dst_mac
262 if min(if1_pci, if2_pci) != if1_pci:
263 if1_pci, if2_pci = if2_pci, if1_pci
264 if1_addr, if2_addr = if2_addr, if1_addr
265 if1_adj_addr, if2_adj_addr = if2_adj_addr, if1_adj_addr
266 self._ifaces_reordered = True
268 if osi_layer == 'L2' or osi_layer == 'L3':
271 "sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
273 " interfaces: [\"{0}\",\"{1}\"]\n"
275 " - dest_mac: [{2}]\n"
277 " - dest_mac: [{4}]\n"
280 .format(if1_pci, if2_pci,
281 "0x"+if1_adj_addr.replace(":", ",0x"),
282 "0x"+if1_addr.replace(":", ",0x"),
283 "0x"+if2_adj_addr.replace(":", ",0x"),
284 "0x"+if2_addr.replace(":", ",0x")),
285 sudo=True, message='TRex config generation error')
286 elif osi_layer == 'L7':
289 "sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
291 " interfaces: [\"{0}\",\"{1}\"]\n"
294 " default_gw: [{3}]\n"
296 " default_gw: [{5}]\n"
298 .format(if1_pci, if2_pci,
299 if1_addr, if1_adj_addr,
300 if2_addr, if2_adj_addr),
301 sudo=True, message='TRex config generation error')
303 raise ValueError("Unknown Test Type")
305 self._startup_trex(osi_layer)
307 def _startup_trex(self, osi_layer):
308 """Startup sequence for the TRex traffic generator.
310 :param osi_layer: 'L2', 'L3' or 'L7' - OSI Layer testing type.
312 :raises RuntimeError: If node subtype is not a TREX or startup failed.
314 # No need to check subtype, we know it is TREX.
315 for _ in range(0, 3):
316 # Kill TRex only if it is already running.
317 cmd = "sh -c 'pgrep t-rex && pkill t-rex && sleep 3 || true'"
319 self._node, cmd, sudo=True, message='Kill TRex failed!')
323 for port in self._node['interfaces'].values():
324 ports += ' {pci}'.format(pci=port.get('pci_address'))
326 cmd = ("sh -c 'cd {dir}/scripts/ && "
327 "./dpdk_nic_bind.py -u {ports} || true'"
328 .format(dir=Constants.TREX_INSTALL_DIR, ports=ports))
330 self._node, cmd, sudo=True,
331 message='Unbind PCI ports from driver failed!')
333 cmd = ("sh -c 'cd {dir}/scripts/ && ./trex-cfg'"
334 .format(dir=Constants.TREX_INSTALL_DIR))
336 self._node, cmd, sudo=True, message='Config TRex failed!')
339 cmd = ("sh -c 'cd {dir}/scripts/ && "
340 "nohup ./t-rex-64 {mode} -i -c 7 > "
341 "/tmp/trex.log 2>&1 &' > /dev/null"
342 .format(dir=Constants.TREX_INSTALL_DIR,
343 mode='--astf' if osi_layer == 'L7' else ''))
345 exec_cmd_no_error(self._node, cmd, sudo=True)
347 cmd = "sh -c 'cat /tmp/trex.log'"
349 self._node, cmd, sudo=True, message='Get TRex logs failed!')
350 raise RuntimeError('Start TRex failed!')
352 # Test if TRex starts successfuly.
353 cmd = ("sh -c '{dir}/resources/tools/trex/trex_server_info.py'"
354 .format(dir=Constants.REMOTE_FW_DIR))
357 self._node, cmd, sudo=True, message='Test TRex failed!',
362 # After max retries TRex is still not responding to API critical error
364 raise RuntimeError('Start TRex failed after multiple retries!')
367 def is_trex_running(node):
368 """Check if TRex is running using pidof.
370 :param node: Traffic generator node.
372 :returns: True if TRex is running otherwise False.
374 :raises RuntimeError: If node type is not a TG.
376 # No need to check subtype, we know it is TREX.
378 ret, _, _ = exec_cmd(node, "pidof t-rex", sudo=True)
379 return bool(int(ret) == 0)
382 def teardown_traffic_generator(node):
385 :param node: Traffic generator node.
388 :raises RuntimeError: If node type is not a TG,
389 or if TRex teardown fails.
391 subtype = check_subtype(node)
392 if subtype == NodeSubTypeTG.TREX:
394 node, "sh -c 'sudo pkill t-rex && sleep 3'",
395 sudo=False, message='pkill t-rex failed')
397 def _parse_traffic_results(self, stdout):
398 """Parse stdout of scripts into fieds of self.
400 Block of code to reuse, by sync start, or stop after async.
401 TODO: Is the output TG subtype dependent?
403 :param stdout: Text containing the standard output.
406 # last line from console output
407 line = stdout.splitlines()[-1]
409 logger.info('TrafficGen result: {0}'.format(self._result))
410 self._received = self._result.split(', ')[1].split('=')[1]
411 self._sent = self._result.split(', ')[2].split('=')[1]
412 self._loss = self._result.split(', ')[3].split('=')[1]
414 self._latency.append(self._result.split(', ')[4].split('=')[1])
415 self._latency.append(self._result.split(', ')[5].split('=')[1])
417 def trex_stl_stop_remote_exec(self, node):
418 """Execute script on remote node over ssh to stop running traffic.
420 Internal state is updated with results.
422 :param node: TRex generator node.
425 :raises RuntimeError: If stop traffic script fails.
427 # No need to check subtype, we know it is TREX.
428 stdout, _ = exec_cmd_no_error(
430 "sh -c '{}/resources/tools/trex/"
431 "trex_stateless_stop.py'".format(Constants.REMOTE_FW_DIR),
432 message='TRex stateless runtime error')
433 self._parse_traffic_results(stdout)
435 def trex_stl_start_remote_exec(
436 self, duration, rate, frame_size, traffic_profile, async_call=False,
437 latency=True, warmup_time=5.0, unidirection=False, tx_port=0,
439 """Execute script on remote node over ssh to start traffic.
441 :param duration: Time expresed in seconds for how long to send traffic.
442 :param rate: Traffic rate expressed with units (pps, %)
443 :param frame_size: L2 frame size to send (without padding and IPG).
444 :param traffic_profile: Module name as a traffic profile identifier.
445 See resources/traffic_profiles/trex for implemented modules.
446 :param async_call: If enabled then don't wait for all incomming trafic.
447 :param latency: With latency measurement.
448 :param warmup_time: Warmup time period.
449 :param unidirection: Traffic is unidirectional. Default: False
450 :param tx_port: Traffic generator transmit port for first flow.
452 :param rx_port: Traffic generator receive port for first flow.
454 :type duration: float
456 :type frame_size: str
457 :type traffic_profile: str
458 :type async_call: bool
460 :type warmup_time: float
461 :type unidirection: bool
464 :raises RuntimeError: In case of TG driver issue.
466 # No need to check subtype, we know it is TREX.
467 reorder = self._ifaces_reordered # Just to make the next line fit.
468 p_0, p_1 = (rx_port, tx_port) if reorder else (tx_port, rx_port)
469 # Values from Robot can introduce type unicode,
470 # we need to encode them, so that repr() does not lead with 'u'.
471 if isinstance(rate, unicode):
472 rate = rate.encode("utf-8")
473 if not isinstance(duration, (float, int)):
474 duration = float(duration)
475 if not isinstance(warmup_time, (float, int)):
476 warmup_time = float(warmup_time)
478 "sh -c '{tool}/resources/tools/trex/trex_stateless_profile.py"
479 " --profile {prof}/resources/traffic_profiles/trex/{traffic}.py"
480 " --duration {duration!r} --frame_size {frame_size} --rate {rate!r}"
481 " --warmup_time {warmup!r} --port_0 {p_0} --port_1 {p_1}").format(
482 tool=Constants.REMOTE_FW_DIR, prof=Constants.REMOTE_FW_DIR,
483 traffic=traffic_profile, duration=duration,
484 frame_size=frame_size, rate=rate, warmup=warmup_time, p_0=p_0,
487 command += " --async"
489 command += " --latency"
491 command += " --unidirection"
494 stdout, _ = exec_cmd_no_error(
495 self._node, command, timeout=float(duration) + 60,
496 message='TRex stateless runtime error')
500 self._start_time = time.time()
501 self._rate = float(rate[:-3]) if "pps" in rate else rate
502 self._received = None
507 self._parse_traffic_results(stdout)
508 self._start_time = None
511 def stop_traffic_on_tg(self):
512 """Stop all traffic on TG.
515 :raises RuntimeError: If TG is not set.
517 subtype = check_subtype(self._node)
518 if subtype == NodeSubTypeTG.TREX:
519 self.trex_stl_stop_remote_exec(self._node)
521 def send_traffic_on_tg(
522 self, duration, rate, frame_size, traffic_profile, warmup_time=5,
523 async_call=False, latency=True, unidirection=False, tx_port=0,
525 """Send traffic from all configured interfaces on TG.
527 Note that bidirectional traffic also contains flows
528 transmitted from rx_port and received in tx_port.
529 But some tests use asymmetric traffic, so those arguments are relevant.
531 Also note that traffic generator uses DPDK driver which might
532 reorder port numbers based on wiring and PCI numbering.
533 This method handles that, so argument values are invariant,
534 but you can see swapped valued in debug logs.
536 TODO: Is it better to have less descriptive argument names
537 just to make them less probable to be viewed as misleading or confusing?
538 See https://gerrit.fd.io/r/#/c/17625/11/resources/libraries/python\
539 /TrafficGenerator.py@406
541 :param duration: Duration of test traffic generation in seconds.
542 :param rate: Offered load per interface (e.g. 1%, 3gbps, 4mpps, ...).
543 :param frame_size: Frame size (L2) in Bytes.
544 :param traffic_profile: Module name as a traffic profile identifier.
545 See resources/traffic_profiles/trex for implemented modules.
546 :param warmup_time: Warmup phase in seconds.
547 :param async_call: Async mode.
548 :param latency: With latency measurement.
549 :param unidirection: Traffic is unidirectional. Default: False
550 :param tx_port: Traffic generator transmit port for first flow.
552 :param rx_port: Traffic generator receive port for first flow.
556 :type frame_size: str
557 :type traffic_profile: str
558 :type warmup_time: float
559 :type async_call: bool
561 :type unidirection: bool
566 :raises RuntimeError: If TG is not set, or if node is not TG,
567 or if subtype is not specified.
568 :raises NotImplementedError: If TG is not supported.
570 subtype = check_subtype(self._node)
571 if subtype == NodeSubTypeTG.TREX:
572 self.trex_stl_start_remote_exec(
573 duration, rate, frame_size, traffic_profile, async_call,
574 latency, warmup_time, unidirection, tx_port, rx_port)
578 def no_traffic_loss_occurred(self):
579 """Fail if loss occurred in traffic run.
582 :raises Exception: If loss occured.
584 if self._loss is None:
585 raise RuntimeError('The traffic generation has not been issued')
586 if self._loss != '0':
587 raise RuntimeError('Traffic loss occurred: {0}'.format(self._loss))
589 def fail_if_no_traffic_forwarded(self):
590 """Fail if no traffic forwarded.
593 :raises Exception: If no traffic forwarded.
595 if self._received is None:
596 raise RuntimeError('The traffic generation has not been issued')
597 if self._received == '0':
598 raise RuntimeError('No traffic forwarded')
600 def partial_traffic_loss_accepted(self, loss_acceptance,
601 loss_acceptance_type):
602 """Fail if loss is higher then accepted in traffic run.
604 :param loss_acceptance: Permitted drop ratio or frames count.
605 :param loss_acceptance_type: Type of permitted loss.
606 :type loss_acceptance: float
607 :type loss_acceptance_type: LossAcceptanceType
609 :raises Exception: If loss is above acceptance criteria.
611 if self._loss is None:
612 raise Exception('The traffic generation has not been issued')
614 if loss_acceptance_type == 'percentage':
615 loss = (float(self._loss) / float(self._sent)) * 100
616 elif loss_acceptance_type == 'frames':
617 loss = float(self._loss)
619 raise Exception('Loss acceptance type not supported')
621 if loss > float(loss_acceptance):
622 raise Exception("Traffic loss {} above loss acceptance: {}".format(
623 loss, loss_acceptance))
625 def set_rate_provider_defaults(self, frame_size, traffic_profile,
627 """Store values accessed by measure().
629 :param frame_size: Frame size identifier or value [B].
630 :param traffic_profile: Module name as a traffic profile identifier.
631 See resources/traffic_profiles/trex for implemented modules.
632 :param warmup_time: Traffic duration before measurement starts [s].
633 :type frame_size: str or int
634 :type traffic_profile: str
635 :type warmup_time: float
637 self.frame_size = frame_size
638 self.traffic_profile = str(traffic_profile)
639 self.warmup_time = float(warmup_time)
641 def get_measurement_result(self, duration=None, transmit_rate=None):
642 """Return the result of last measurement as ReceiveRateMeasurement.
644 Separate function, as measurements can end either by time
645 or by explicit call, this is the common block at the end.
647 TODO: Fail on running or already reported measurement.
649 :param duration: Measurement duration [s] if known beforehand.
650 For explicitly stopped measurement it is estimated.
651 :param transmit_rate: Target aggregate transmit rate [pps].
652 If not given, computed assuming it was bidirectional.
653 :type duration: float or NoneType
654 :type transmit_rate: float or NoneType
655 :returns: Structure containing the result of the measurement.
656 :rtype: ReceiveRateMeasurement
659 duration = time.time() - self._start_time
660 self._start_time = None
661 if transmit_rate is None:
662 # Assuming bi-directional traffic here.
663 transmit_rate = self._rate * 2.0
664 transmit_count = int(self.get_sent())
665 loss_count = int(self.get_loss())
666 measurement = ReceiveRateMeasurement(
667 duration, transmit_rate, transmit_count, loss_count)
668 measurement.latency = self.get_latency_int()
671 def measure(self, duration, transmit_rate):
672 """Run bi-directional measurement, parse and return results.
674 :param duration: Trial duration [s].
675 :param transmit_rate: Target bidirectional transmit rate [pps].
676 :type duration: float
677 :type transmit_rate: float
678 :returns: Structure containing the result of the measurement.
679 :rtype: ReceiveRateMeasurement
680 :raises RuntimeError: If TG is not set, or if node is not TG,
681 or if subtype is not specified.
682 :raises NotImplementedError: If TG is not supported.
684 duration = float(duration)
685 transmit_rate = float(transmit_rate)
686 # TG needs target Tr per stream, but reports aggregate Tx and Dx.
687 unit_rate = str(transmit_rate / 2.0) + "pps"
688 self.send_traffic_on_tg(
689 duration, unit_rate, self.frame_size, self.traffic_profile,
690 warmup_time=self.warmup_time, latency=True)
691 return self.get_measurement_result(duration, transmit_rate)
694 class OptimizedSearch(object):
695 """Class to be imported as Robot Library, containing a single keyword."""
698 def perform_optimized_ndrpdr_search(
699 frame_size, traffic_profile, minimum_transmit_rate,
700 maximum_transmit_rate, packet_loss_ratio=0.005,
701 final_relative_width=0.005, final_trial_duration=30.0,
702 initial_trial_duration=1.0, number_of_intermediate_phases=2,
703 timeout=720.0, doublings=1):
704 """Setup initialized TG, perform optimized search, return intervals.
706 :param frame_size: Frame size identifier or value [B].
707 :param traffic_profile: Module name as a traffic profile identifier.
708 See resources/traffic_profiles/trex for implemented modules.
709 :param minimum_transmit_rate: Minimal bidirectional
710 target transmit rate [pps].
711 :param maximum_transmit_rate: Maximal bidirectional
712 target transmit rate [pps].
713 :param packet_loss_ratio: Fraction of packets lost, for PDR [1].
714 :param final_relative_width: Final lower bound transmit rate
715 cannot be more distant that this multiple of upper bound [1].
716 :param final_trial_duration: Trial duration for the final phase [s].
717 :param initial_trial_duration: Trial duration for the initial phase
718 and also for the first intermediate phase [s].
719 :param number_of_intermediate_phases: Number of intermediate phases
720 to perform before the final phase [1].
721 :param timeout: The search will fail itself when not finished
722 before this overall time [s].
723 :param doublings: How many doublings to do in external search step.
724 Default 1 is suitable for fairly stable tests,
725 less stable tests might get better overal duration with 2 or more.
726 :type frame_size: str or int
727 :type traffic_profile: str
728 :type minimum_transmit_rate: float
729 :type maximum_transmit_rate: float
730 :type packet_loss_ratio: float
731 :type final_relative_width: float
732 :type final_trial_duration: float
733 :type initial_trial_duration: float
734 :type number_of_intermediate_phases: int
737 :returns: Structure containing narrowed down NDR and PDR intervals
738 and their measurements.
740 :raises RuntimeError: If total duration is larger than timeout.
742 # we need instance of TrafficGenerator instantiated by Robot Framework
743 # to be able to use trex_stl-*()
744 tg_instance = BuiltIn().get_library_instance(
745 'resources.libraries.python.TrafficGenerator')
746 tg_instance.set_rate_provider_defaults(frame_size, traffic_profile)
747 algorithm = MultipleLossRatioSearch(
748 measurer=tg_instance, final_trial_duration=final_trial_duration,
749 final_relative_width=final_relative_width,
750 number_of_intermediate_phases=number_of_intermediate_phases,
751 initial_trial_duration=initial_trial_duration, timeout=timeout,
753 result = algorithm.narrow_down_ndr_and_pdr(
754 minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio)
758 def perform_soak_search(
759 frame_size, traffic_profile, minimum_transmit_rate,
760 maximum_transmit_rate, plr_target=1e-7, tdpt=0.1,
761 initial_count=50, timeout=1800.0, trace_enabled=False):
762 """Setup initialized TG, perform soak search, return avg and stdev.
764 :param frame_size: Frame size identifier or value [B].
765 :param traffic_profile: Module name as a traffic profile identifier.
766 See resources/traffic_profiles/trex for implemented modules.
767 :param minimum_transmit_rate: Minimal bidirectional
768 target transmit rate [pps].
769 :param maximum_transmit_rate: Maximal bidirectional
770 target transmit rate [pps].
771 :param plr_target: Fraction of packets lost to achieve [1].
772 :param tdpt: Trial duration per trial.
773 The algorithm linearly increases trial duration with trial number,
774 this is the increment between succesive trials, in seconds.
775 :param initial_count: Offset to apply before the first trial.
776 For example initial_count=50 makes first trial to be 51*tdpt long.
777 This is needed because initial "search" phase of integrator
778 takes significant time even without any trial results.
779 :param timeout: The search will stop after this overall time [s].
780 :type frame_size: str or int
781 :type traffic_profile: str
782 :type minimum_transmit_rate: float
783 :type maximum_transmit_rate: float
784 :type plr_target: float
785 :type initial_count: int
787 :returns: Average and stdev of estimated bidirectional rate giving PLR.
788 :rtype: 2-tuple of float
790 tg_instance = BuiltIn().get_library_instance(
791 'resources.libraries.python.TrafficGenerator')
792 tg_instance.set_rate_provider_defaults(frame_size, traffic_profile)
793 algorithm = PLRsearch(
794 measurer=tg_instance, trial_duration_per_trial=tdpt,
795 packet_loss_ratio_target=plr_target,
796 trial_number_offset=initial_count, timeout=timeout,
797 trace_enabled=trace_enabled)
798 result = algorithm.search(minimum_transmit_rate, maximum_transmit_rate)