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
150 self.traffic_directions = None
156 :returns: Traffic generator node.
162 """Return number of lost packets.
164 :returns: Number of lost packets.
170 """Return number of sent packets.
172 :returns: Number of sent packets.
177 def get_received(self):
178 """Return number of received packets.
180 :returns: Number of received packets.
183 return self._received
185 def get_latency_int(self):
186 """Return rounded min/avg/max latency.
188 :returns: Latency stats.
193 def initialize_traffic_generator(
194 self, tg_node, tg_if1, tg_if2, tg_if1_adj_node, tg_if1_adj_if,
195 tg_if2_adj_node, tg_if2_adj_if, osi_layer, tg_if1_dst_mac=None,
196 tg_if2_dst_mac=None):
197 """TG initialization.
199 TODO: Document why do we need (and how do we use) _ifaces_reordered.
201 :param tg_node: Traffic generator node.
202 :param tg_if1: TG - name of first interface.
203 :param tg_if2: TG - name of second interface.
204 :param tg_if1_adj_node: TG if1 adjecent node.
205 :param tg_if1_adj_if: TG if1 adjecent interface.
206 :param tg_if2_adj_node: TG if2 adjecent node.
207 :param tg_if2_adj_if: TG if2 adjecent interface.
208 :param osi_layer: 'L2', 'L3' or 'L7' - OSI Layer testing type.
209 :param tg_if1_dst_mac: Interface 1 destination MAC address.
210 :param tg_if2_dst_mac: Interface 2 destination MAC address.
214 :type tg_if1_adj_node: dict
215 :type tg_if1_adj_if: str
216 :type tg_if2_adj_node: dict
217 :type tg_if2_adj_if: str
219 :type tg_if1_dst_mac: str
220 :type tg_if2_dst_mac: str
222 :raises RuntimeError: In case of issue during initialization.
224 subtype = check_subtype(tg_node)
225 if subtype == NodeSubTypeTG.TREX:
228 if1_pci = Topology().get_interface_pci_addr(self._node, tg_if1)
229 if2_pci = Topology().get_interface_pci_addr(self._node, tg_if2)
230 if1_addr = Topology().get_interface_mac(self._node, tg_if1)
231 if2_addr = Topology().get_interface_mac(self._node, tg_if2)
233 if osi_layer == 'L2':
234 if1_adj_addr = if2_addr
235 if2_adj_addr = if1_addr
236 elif osi_layer == 'L3':
237 if1_adj_addr = Topology().get_interface_mac(tg_if1_adj_node,
239 if2_adj_addr = Topology().get_interface_mac(tg_if2_adj_node,
241 elif osi_layer == 'L7':
242 if1_addr = Topology().get_interface_ip4(self._node, tg_if1)
243 if2_addr = Topology().get_interface_ip4(self._node, tg_if2)
244 if1_adj_addr = Topology().get_interface_ip4(tg_if1_adj_node,
246 if2_adj_addr = Topology().get_interface_ip4(tg_if2_adj_node,
249 raise ValueError("Unknown Test Type")
251 # in case of switched environment we can override MAC addresses
252 if tg_if1_dst_mac is not None and tg_if2_dst_mac is not None:
253 if1_adj_addr = tg_if1_dst_mac
254 if2_adj_addr = tg_if2_dst_mac
256 if min(if1_pci, if2_pci) != if1_pci:
257 if1_pci, if2_pci = if2_pci, if1_pci
258 if1_addr, if2_addr = if2_addr, if1_addr
259 if1_adj_addr, if2_adj_addr = if2_adj_addr, if1_adj_addr
260 self._ifaces_reordered = True
262 if osi_layer == 'L2' or osi_layer == 'L3':
265 "sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
267 " interfaces: [\"{0}\",\"{1}\"]\n"
269 " - dest_mac: [{2}]\n"
271 " - dest_mac: [{4}]\n"
274 .format(if1_pci, if2_pci,
275 "0x"+if1_adj_addr.replace(":", ",0x"),
276 "0x"+if1_addr.replace(":", ",0x"),
277 "0x"+if2_adj_addr.replace(":", ",0x"),
278 "0x"+if2_addr.replace(":", ",0x")),
279 sudo=True, message='TRex config generation error')
280 elif osi_layer == 'L7':
283 "sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
285 " interfaces: [\"{0}\",\"{1}\"]\n"
288 " default_gw: [{3}]\n"
290 " default_gw: [{5}]\n"
292 .format(if1_pci, if2_pci,
293 if1_addr, if1_adj_addr,
294 if2_addr, if2_adj_addr),
295 sudo=True, message='TRex config generation error')
297 raise ValueError("Unknown Test Type")
299 self._startup_trex(osi_layer)
301 def _startup_trex(self, osi_layer):
302 """Startup sequence for the TRex traffic generator.
304 :param osi_layer: 'L2', 'L3' or 'L7' - OSI Layer testing type.
306 :raises RuntimeError: If node subtype is not a TREX or startup failed.
308 # No need to check subtype, we know it is TREX.
309 for _ in range(0, 3):
310 # Kill TRex only if it is already running.
311 cmd = "sh -c 'pgrep t-rex && pkill t-rex && sleep 3 || true'"
313 self._node, cmd, sudo=True, message='Kill TRex failed!')
317 for port in self._node['interfaces'].values():
318 ports += ' {pci}'.format(pci=port.get('pci_address'))
320 cmd = ("sh -c 'cd {dir}/scripts/ && "
321 "./dpdk_nic_bind.py -u {ports} || true'"
322 .format(dir=Constants.TREX_INSTALL_DIR, ports=ports))
324 self._node, cmd, sudo=True,
325 message='Unbind PCI ports from driver failed!')
327 cmd = ("sh -c 'cd {dir}/scripts/ && ./trex-cfg "
328 "--unbind-unused-ports'"
329 .format(dir=Constants.TREX_INSTALL_DIR))
331 self._node, cmd, sudo=True, message='Config TRex failed!')
334 cmd = ("sh -c 'cd {dir}/scripts/ && "
335 "nohup ./t-rex-64 {mode} -i -c 7 > "
336 "/tmp/trex.log 2>&1 &' > /dev/null"
337 .format(dir=Constants.TREX_INSTALL_DIR,
338 mode='--astf' if osi_layer == 'L7' else ''))
340 exec_cmd_no_error(self._node, cmd, sudo=True)
342 cmd = "sh -c 'cat /tmp/trex.log'"
344 self._node, cmd, sudo=True, message='Get TRex logs failed!')
345 raise RuntimeError('Start TRex failed!')
347 # Test if TRex starts successfuly.
348 cmd = ("sh -c '{dir}/resources/tools/trex/trex_server_info.py'"
349 .format(dir=Constants.REMOTE_FW_DIR))
352 self._node, cmd, sudo=True, message='Test TRex failed!',
357 # After max retries TRex is still not responding to API critical error
359 raise RuntimeError('Start TRex failed after multiple retries!')
362 def is_trex_running(node):
363 """Check if TRex is running using pidof.
365 :param node: Traffic generator node.
367 :returns: True if TRex is running otherwise False.
369 :raises RuntimeError: If node type is not a TG.
371 # No need to check subtype, we know it is TREX.
373 ret, _, _ = exec_cmd(node, "pidof t-rex", sudo=True)
374 return bool(int(ret) == 0)
377 def teardown_traffic_generator(node):
380 :param node: Traffic generator node.
383 :raises RuntimeError: If node type is not a TG,
384 or if TRex teardown fails.
386 subtype = check_subtype(node)
387 if subtype == NodeSubTypeTG.TREX:
389 node, "sh -c 'sudo pkill t-rex && sleep 3'",
390 sudo=False, message='pkill t-rex failed')
392 def _parse_traffic_results(self, stdout):
393 """Parse stdout of scripts into fieds of self.
395 Block of code to reuse, by sync start, or stop after async.
396 TODO: Is the output TG subtype dependent?
398 :param stdout: Text containing the standard output.
401 # last line from console output
402 line = stdout.splitlines()[-1]
404 logger.info('TrafficGen result: {0}'.format(self._result))
405 self._received = self._result.split(', ')[1].split('=')[1]
406 self._sent = self._result.split(', ')[2].split('=')[1]
407 self._loss = self._result.split(', ')[3].split('=')[1]
409 self._latency.append(self._result.split(', ')[4].split('=')[1])
410 self._latency.append(self._result.split(', ')[5].split('=')[1])
412 def trex_stl_stop_remote_exec(self, node):
413 """Execute script on remote node over ssh to stop running traffic.
415 Internal state is updated with results.
417 :param node: TRex generator node.
420 :raises RuntimeError: If stop traffic script fails.
422 # No need to check subtype, we know it is TREX.
423 stdout, _ = exec_cmd_no_error(
425 "sh -c '{}/resources/tools/trex/"
426 "trex_stateless_stop.py'".format(Constants.REMOTE_FW_DIR),
427 message='TRex stateless runtime error')
428 self._parse_traffic_results(stdout)
430 def trex_stl_start_remote_exec(
431 self, duration, rate, frame_size, traffic_profile, async_call=False,
432 latency=True, warmup_time=5.0, traffic_directions=2, tx_port=0,
434 """Execute script on remote node over ssh to start traffic.
436 :param duration: Time expresed in seconds for how long to send traffic.
437 :param rate: Traffic rate expressed with units (pps, %)
438 :param frame_size: L2 frame size to send (without padding and IPG).
439 :param traffic_profile: Module name as a traffic profile identifier.
440 See resources/traffic_profiles/trex for implemented modules.
441 :param async_call: If enabled then don't wait for all incomming trafic.
442 :param latency: With latency measurement.
443 :param warmup_time: Warmup time period.
444 :param traffic_directions: Traffic is bi- (2) or uni- (1) directional.
446 :param tx_port: Traffic generator transmit port for first flow.
448 :param rx_port: Traffic generator receive port for first flow.
450 :type duration: float
452 :type frame_size: str
453 :type traffic_profile: str
454 :type async_call: bool
456 :type warmup_time: float
457 :type traffic_directions: int
460 :raises RuntimeError: In case of TG driver issue.
462 # No need to check subtype, we know it is TREX.
463 reorder = self._ifaces_reordered # Just to make the next line fit.
464 p_0, p_1 = (rx_port, tx_port) if reorder else (tx_port, rx_port)
465 # Values from Robot can introduce type unicode,
466 # we need to encode them, so that repr() does not lead with 'u'.
467 if isinstance(rate, unicode):
468 rate = rate.encode("utf-8")
469 if not isinstance(duration, (float, int)):
470 duration = float(duration)
471 if not isinstance(warmup_time, (float, int)):
472 warmup_time = float(warmup_time)
474 "sh -c '{tool}/resources/tools/trex/trex_stateless_profile.py"
475 " --profile {prof}/resources/traffic_profiles/trex/{traffic}.py"
476 " --duration {duration!r} --frame_size {frame_size} --rate {rate!r}"
477 " --warmup_time {warmup!r} --port_0 {p_0} --port_1 {p_1}"
478 " --traffic_directions {dirs}").format(
479 tool=Constants.REMOTE_FW_DIR, prof=Constants.REMOTE_FW_DIR,
480 traffic=traffic_profile, duration=duration,
481 frame_size=frame_size, rate=rate, warmup=warmup_time, p_0=p_0,
482 p_1=p_1, dirs=traffic_directions)
484 command += " --async"
486 command += " --latency"
489 stdout, _ = exec_cmd_no_error(
490 self._node, command, timeout=float(duration) + 60,
491 message='TRex stateless runtime error')
495 self._start_time = time.time()
496 self._rate = float(rate[:-3]) if "pps" in rate else rate
497 self._received = None
502 self._parse_traffic_results(stdout)
503 self._start_time = None
506 def stop_traffic_on_tg(self):
507 """Stop all traffic on TG.
510 :raises RuntimeError: If TG is not set.
512 subtype = check_subtype(self._node)
513 if subtype == NodeSubTypeTG.TREX:
514 self.trex_stl_stop_remote_exec(self._node)
516 def send_traffic_on_tg(
517 self, duration, rate, frame_size, traffic_profile, warmup_time=5,
518 async_call=False, latency=True, traffic_directions=2, tx_port=0,
520 """Send traffic from all configured interfaces on TG.
522 Note that bidirectional traffic also contains flows
523 transmitted from rx_port and received in tx_port.
524 But some tests use asymmetric traffic, so those arguments are relevant.
526 Also note that traffic generator uses DPDK driver which might
527 reorder port numbers based on wiring and PCI numbering.
528 This method handles that, so argument values are invariant,
529 but you can see swapped valued in debug logs.
531 TODO: Is it better to have less descriptive argument names
532 just to make them less probable to be viewed as misleading or confusing?
533 See https://gerrit.fd.io/r/#/c/17625/11/resources/libraries/python\
534 /TrafficGenerator.py@406
536 :param duration: Duration of test traffic generation in seconds.
537 :param rate: Offered load per interface (e.g. 1%, 3gbps, 4mpps, ...).
538 :param frame_size: Frame size (L2) in Bytes.
539 :param traffic_profile: Module name as a traffic profile identifier.
540 See resources/traffic_profiles/trex for implemented modules.
541 :param warmup_time: Warmup phase in seconds.
542 :param async_call: Async mode.
543 :param latency: With latency measurement.
544 :param traffic_directions: Traffic is bi- (2) or uni- (1) directional.
546 :param tx_port: Traffic generator transmit port for first flow.
548 :param rx_port: Traffic generator receive port for first flow.
552 :type frame_size: str
553 :type traffic_profile: str
554 :type warmup_time: float
555 :type async_call: bool
557 :type traffic_directions: int
562 :raises RuntimeError: If TG is not set, or if node is not TG,
563 or if subtype is not specified.
564 :raises NotImplementedError: If TG is not supported.
566 subtype = check_subtype(self._node)
567 if subtype == NodeSubTypeTG.TREX:
568 self.trex_stl_start_remote_exec(
569 duration, rate, frame_size, traffic_profile, async_call,
570 latency, warmup_time, traffic_directions, tx_port, rx_port)
574 def no_traffic_loss_occurred(self):
575 """Fail if loss occurred in traffic run.
578 :raises Exception: If loss occured.
580 if self._loss is None:
581 raise RuntimeError('The traffic generation has not been issued')
582 if self._loss != '0':
583 raise RuntimeError('Traffic loss occurred: {0}'.format(self._loss))
585 def fail_if_no_traffic_forwarded(self):
586 """Fail if no traffic forwarded.
589 :raises Exception: If no traffic forwarded.
591 if self._received is None:
592 raise RuntimeError('The traffic generation has not been issued')
593 if self._received == '0':
594 raise RuntimeError('No traffic forwarded')
596 def partial_traffic_loss_accepted(self, loss_acceptance,
597 loss_acceptance_type):
598 """Fail if loss is higher then accepted in traffic run.
600 :param loss_acceptance: Permitted drop ratio or frames count.
601 :param loss_acceptance_type: Type of permitted loss.
602 :type loss_acceptance: float
603 :type loss_acceptance_type: LossAcceptanceType
605 :raises Exception: If loss is above acceptance criteria.
607 if self._loss is None:
608 raise Exception('The traffic generation has not been issued')
610 if loss_acceptance_type == 'percentage':
611 loss = (float(self._loss) / float(self._sent)) * 100
612 elif loss_acceptance_type == 'frames':
613 loss = float(self._loss)
615 raise Exception('Loss acceptance type not supported')
617 if loss > float(loss_acceptance):
618 raise Exception("Traffic loss {} above loss acceptance: {}".format(
619 loss, loss_acceptance))
621 def set_rate_provider_defaults(self, frame_size, traffic_profile,
622 warmup_time=0.0, traffic_directions=2):
623 """Store values accessed by measure().
625 :param frame_size: Frame size identifier or value [B].
626 :param traffic_profile: Module name as a traffic profile identifier.
627 See resources/traffic_profiles/trex for implemented modules.
628 :param warmup_time: Traffic duration before measurement starts [s].
629 :param traffic_directions: Traffic is bi- (2) or uni- (1) directional.
631 :type frame_size: str or int
632 :type traffic_profile: str
633 :type warmup_time: float
634 :type traffic_directions: int
636 self.frame_size = frame_size
637 self.traffic_profile = str(traffic_profile)
638 self.warmup_time = float(warmup_time)
639 self.traffic_directions = traffic_directions
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 transmit_rate = self._rate * self.traffic_directions
663 transmit_count = int(self.get_sent())
664 loss_count = int(self.get_loss())
665 measurement = ReceiveRateMeasurement(
666 duration, transmit_rate, transmit_count, loss_count)
667 measurement.latency = self.get_latency_int()
670 def measure(self, duration, transmit_rate):
671 """Run trial measurement, parse and return aggregate results.
673 Aggregate means sum over traffic directions.
675 :param duration: Trial duration [s].
676 :param transmit_rate: Target aggregate transmit rate [pps].
677 :type duration: float
678 :type transmit_rate: float
679 :returns: Structure containing the result of the measurement.
680 :rtype: ReceiveRateMeasurement
681 :raises RuntimeError: If TG is not set, or if node is not TG,
682 or if subtype is not specified.
683 :raises NotImplementedError: If TG is not supported.
685 duration = float(duration)
686 transmit_rate = float(transmit_rate)
687 # TG needs target Tr per stream, but reports aggregate Tx and Dx.
688 unit_rate_int = transmit_rate / float(self.traffic_directions)
689 unit_rate_str = str(unit_rate_int) + "pps"
690 self.send_traffic_on_tg(
691 duration, unit_rate_str, self.frame_size, self.traffic_profile,
692 warmup_time=self.warmup_time, latency=True,
693 traffic_directions=self.traffic_directions)
694 return self.get_measurement_result(duration, transmit_rate)
697 class OptimizedSearch(object):
698 """Class to be imported as Robot Library, containing search keywords.
700 Aside of setting up measurer and forwarding arguments,
701 the main business is to translate min/max rate from unidir to aggregate.
705 def perform_optimized_ndrpdr_search(
706 frame_size, traffic_profile, minimum_transmit_rate,
707 maximum_transmit_rate, packet_loss_ratio=0.005,
708 final_relative_width=0.005, final_trial_duration=30.0,
709 initial_trial_duration=1.0, number_of_intermediate_phases=2,
710 timeout=720.0, doublings=1, traffic_directions=2):
711 """Setup initialized TG, perform optimized search, return intervals.
713 :param frame_size: Frame size identifier or value [B].
714 :param traffic_profile: Module name as a traffic profile identifier.
715 See resources/traffic_profiles/trex for implemented modules.
716 :param minimum_transmit_rate: Minimal uni-directional
717 target transmit rate [pps].
718 :param maximum_transmit_rate: Maximal uni-directional
719 target transmit rate [pps].
720 :param packet_loss_ratio: Fraction of packets lost, for PDR [1].
721 :param final_relative_width: Final lower bound transmit rate
722 cannot be more distant that this multiple of upper bound [1].
723 :param final_trial_duration: Trial duration for the final phase [s].
724 :param initial_trial_duration: Trial duration for the initial phase
725 and also for the first intermediate phase [s].
726 :param number_of_intermediate_phases: Number of intermediate phases
727 to perform before the final phase [1].
728 :param timeout: The search will fail itself when not finished
729 before this overall time [s].
730 :param doublings: How many doublings to do in external search step.
731 Default 1 is suitable for fairly stable tests,
732 less stable tests might get better overal duration with 2 or more.
733 :param traffic_directions: Traffic is bi- (2) or uni- (1) directional.
735 :type frame_size: str or int
736 :type traffic_profile: str
737 :type minimum_transmit_rate: float
738 :type maximum_transmit_rate: float
739 :type packet_loss_ratio: float
740 :type final_relative_width: float
741 :type final_trial_duration: float
742 :type initial_trial_duration: float
743 :type number_of_intermediate_phases: int
746 :type traffic_directions: int
747 :returns: Structure containing narrowed down NDR and PDR intervals
748 and their measurements.
750 :raises RuntimeError: If total duration is larger than timeout.
752 minimum_transmit_rate *= traffic_directions
753 maximum_transmit_rate *= traffic_directions
754 # we need instance of TrafficGenerator instantiated by Robot Framework
755 # to be able to use trex_stl-*()
756 tg_instance = BuiltIn().get_library_instance(
757 'resources.libraries.python.TrafficGenerator')
758 tg_instance.set_rate_provider_defaults(
759 frame_size, traffic_profile, traffic_directions=traffic_directions)
760 algorithm = MultipleLossRatioSearch(
761 measurer=tg_instance, final_trial_duration=final_trial_duration,
762 final_relative_width=final_relative_width,
763 number_of_intermediate_phases=number_of_intermediate_phases,
764 initial_trial_duration=initial_trial_duration, timeout=timeout,
766 result = algorithm.narrow_down_ndr_and_pdr(
767 minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio)
771 def perform_soak_search(
772 frame_size, traffic_profile, minimum_transmit_rate,
773 maximum_transmit_rate, plr_target=1e-7, tdpt=0.1,
774 initial_count=50, timeout=1800.0, trace_enabled=False,
775 traffic_directions=2):
776 """Setup initialized TG, perform soak search, return avg and stdev.
778 :param frame_size: Frame size identifier or value [B].
779 :param traffic_profile: Module name as a traffic profile identifier.
780 See resources/traffic_profiles/trex for implemented modules.
781 :param minimum_transmit_rate: Minimal uni-directional
782 target transmit rate [pps].
783 :param maximum_transmit_rate: Maximal uni-directional
784 target transmit rate [pps].
785 :param plr_target: Fraction of packets lost to achieve [1].
786 :param tdpt: Trial duration per trial.
787 The algorithm linearly increases trial duration with trial number,
788 this is the increment between succesive trials, in seconds.
789 :param initial_count: Offset to apply before the first trial.
790 For example initial_count=50 makes first trial to be 51*tdpt long.
791 This is needed because initial "search" phase of integrator
792 takes significant time even without any trial results.
793 :param timeout: The search will stop after this overall time [s].
794 :param traffic_directions: Traffic is bi- (2) or uni- (1) directional.
796 :type frame_size: str or int
797 :type traffic_profile: str
798 :type minimum_transmit_rate: float
799 :type maximum_transmit_rate: float
800 :type plr_target: float
801 :type initial_count: int
803 :type traffic_directions: int
804 :returns: Average and stdev of estimated aggregate rate giving PLR.
805 :rtype: 2-tuple of float
807 minimum_transmit_rate *= traffic_directions
808 maximum_transmit_rate *= traffic_directions
809 tg_instance = BuiltIn().get_library_instance(
810 'resources.libraries.python.TrafficGenerator')
811 tg_instance.set_rate_provider_defaults(
812 frame_size, traffic_profile, traffic_directions=traffic_directions)
813 algorithm = PLRsearch(
814 measurer=tg_instance, trial_duration_per_trial=tdpt,
815 packet_loss_ratio_target=plr_target,
816 trial_number_offset=initial_count, timeout=timeout,
817 trace_enabled=trace_enabled)
818 result = algorithm.search(minimum_transmit_rate, maximum_transmit_rate)