Fix pylint part 1
[csit.git] / resources / libraries / python / TrafficGenerator.py
1 # Copyright (c) 2018 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:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
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.
13
14 """Performance testing traffic generator library."""
15
16 from robot.api import logger
17 from robot.libraries.BuiltIn import BuiltIn
18
19 from .DropRateSearch import DropRateSearch
20 from .constants import Constants
21 from .ssh import SSH
22 from .topology import NodeType
23 from .topology import NodeSubTypeTG
24 from .topology import Topology
25 from .MLRsearch.AbstractMeasurer import AbstractMeasurer
26 from .MLRsearch.MultipleLossRatioSearch import MultipleLossRatioSearch
27 from .MLRsearch.ReceiveRateMeasurement import ReceiveRateMeasurement
28
29 __all__ = ['TGDropRateSearchImpl', 'TrafficGenerator', 'OptimizedSearch']
30
31
32 class TGDropRateSearchImpl(DropRateSearch):
33     """Drop Rate Search implementation."""
34
35     def __init__(self):
36         super(TGDropRateSearchImpl, self).__init__()
37
38     def measure_loss(self, rate, frame_size, loss_acceptance,
39                      loss_acceptance_type, traffic_type, skip_warmup=False):
40         """Runs the traffic and evaluate the measured results.
41
42         :param rate: Offered traffic load.
43         :param frame_size: Size of frame.
44         :param loss_acceptance: Permitted drop ratio or frames count.
45         :param loss_acceptance_type: Type of permitted loss.
46         :param traffic_type: Module name as a traffic type identifier.
47             See resources/traffic_profiles/trex for implemented modules.
48         :param skip_warmup: Start TRex without warmup traffic if true.
49         :type rate: float
50         :type frame_size: str
51         :type loss_acceptance: float
52         :type loss_acceptance_type: LossAcceptanceType
53         :type traffic_type: str
54         :type skip_warmup: bool
55         :returns: Drop threshold exceeded? (True/False)
56         :rtype: bool
57         :raises NotImplementedError: If TG is not supported.
58         :raises RuntimeError: If TG is not specified.
59         """
60         # we need instance of TrafficGenerator instantiated by Robot Framework
61         # to be able to use trex_stl-*()
62         tg_instance = BuiltIn().get_library_instance(
63             'resources.libraries.python.TrafficGenerator')
64
65         if tg_instance.node['subtype'] is None:
66             raise RuntimeError('TG subtype not defined')
67         elif tg_instance.node['subtype'] == NodeSubTypeTG.TREX:
68             unit_rate = str(rate) + self.get_rate_type_str()
69             if skip_warmup:
70                 tg_instance.trex_stl_start_remote_exec(self.get_duration(),
71                                                        unit_rate, frame_size,
72                                                        traffic_type,
73                                                        warmup_time=0.0)
74             else:
75                 tg_instance.trex_stl_start_remote_exec(self.get_duration(),
76                                                        unit_rate, frame_size,
77                                                        traffic_type)
78             loss = tg_instance.get_loss()
79             sent = tg_instance.get_sent()
80             if self.loss_acceptance_type_is_percentage():
81                 loss = (float(loss) / float(sent)) * 100
82
83             logger.trace("comparing: {} < {} {}".format(loss,
84                                                         loss_acceptance,
85                                                         loss_acceptance_type))
86             if float(loss) > float(loss_acceptance):
87                 return False
88             else:
89                 return True
90         else:
91             raise NotImplementedError("TG subtype not supported")
92
93     def get_latency(self):
94         """Returns min/avg/max latency.
95
96         :returns: Latency stats.
97         :rtype: list
98         """
99         tg_instance = BuiltIn().get_library_instance(
100             'resources.libraries.python.TrafficGenerator')
101         return tg_instance.get_latency_int()
102
103
104 class TrafficGenerator(AbstractMeasurer):
105     """Traffic Generator.
106
107     FIXME: Describe API."""
108
109     # TODO: Decrease friction between various search and rate provider APIs.
110     # TODO: Remove "trex" from lines which could work with other TGs.
111
112     # Use one instance of TrafficGenerator for all tests in test suite
113     ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
114
115     def __init__(self):
116         self._result = None
117         self._loss = None
118         self._sent = None
119         self._latency = None
120         self._received = None
121         self._node = None
122         # T-REX interface order mapping
123         self._ifaces_reordered = False
124         # Parameters not given by measure().
125         self.frame_size = None
126         self.traffic_type = None
127         self.warmup_time = None
128
129     @property
130     def node(self):
131         """Getter.
132
133         :returns: Traffic generator node.
134         :rtype: dict
135         """
136         return self._node
137
138     def get_loss(self):
139         """Return number of lost packets.
140
141         :returns: Number of lost packets.
142         :rtype: str
143         """
144         return self._loss
145
146     def get_sent(self):
147         """Return number of sent packets.
148
149         :returns: Number of sent packets.
150         :rtype: str
151         """
152         return self._sent
153
154     def get_received(self):
155         """Return number of received packets.
156
157         :returns: Number of received packets.
158         :rtype: str
159         """
160         return self._received
161
162     def get_latency_int(self):
163         """Return rounded min/avg/max latency.
164
165         :returns: Latency stats.
166         :rtype: list
167         """
168         return self._latency
169
170     def initialize_traffic_generator(self, tg_node, tg_if1, tg_if2,
171                                      tg_if1_adj_node, tg_if1_adj_if,
172                                      tg_if2_adj_node, tg_if2_adj_if,
173                                      test_type,
174                                      tg_if1_dst_mac=None, tg_if2_dst_mac=None):
175         """TG initialization.
176
177         :param tg_node: Traffic generator node.
178         :param tg_if1: TG - name of first interface.
179         :param tg_if2: TG - name of second interface.
180         :param tg_if1_adj_node: TG if1 adjecent node.
181         :param tg_if1_adj_if: TG if1 adjecent interface.
182         :param tg_if2_adj_node: TG if2 adjecent node.
183         :param tg_if2_adj_if: TG if2 adjecent interface.
184         :param test_type: 'L2', 'L3' or 'L7' - OSI Layer testing type.
185         :param tg_if1_dst_mac: Interface 1 destination MAC address.
186         :param tg_if2_dst_mac: Interface 2 destination MAC address.
187         :type tg_node: dict
188         :type tg_if1: str
189         :type tg_if2: str
190         :type tg_if1_adj_node: dict
191         :type tg_if1_adj_if: str
192         :type tg_if2_adj_node: dict
193         :type tg_if2_adj_if: str
194         :type test_type: str
195         :type tg_if1_dst_mac: str
196         :type tg_if2_dst_mac: str
197         :returns: nothing
198         :raises RuntimeError: In case of issue during initialization.
199         """
200         if tg_node['type'] != NodeType.TG:
201             raise RuntimeError('Node type is not a TG')
202         self._node = tg_node
203
204         if tg_node['subtype'] == NodeSubTypeTG.TREX:
205             ssh = SSH()
206             ssh.connect(tg_node)
207
208             (ret, _, _) = ssh.exec_command(
209                 "sudo -E sh -c '{0}/resources/tools/trex/"
210                 "trex_installer.sh {1}'".format(Constants.REMOTE_FW_DIR,
211                                                 Constants.TREX_INSTALL_VERSION),
212                 timeout=1800)
213             if int(ret) != 0:
214                 raise RuntimeError('TRex installation failed.')
215
216             if1_pci = Topology().get_interface_pci_addr(tg_node, tg_if1)
217             if2_pci = Topology().get_interface_pci_addr(tg_node, tg_if2)
218             if1_addr = Topology().get_interface_mac(tg_node, tg_if1)
219             if2_addr = Topology().get_interface_mac(tg_node, tg_if2)
220
221             if test_type == 'L2':
222                 if1_adj_addr = if2_addr
223                 if2_adj_addr = if1_addr
224             elif test_type == 'L3':
225                 if1_adj_addr = Topology().get_interface_mac(tg_if1_adj_node,
226                                                             tg_if1_adj_if)
227                 if2_adj_addr = Topology().get_interface_mac(tg_if2_adj_node,
228                                                             tg_if2_adj_if)
229             elif test_type == 'L7':
230                 if1_addr = Topology().get_interface_ip4(tg_node, tg_if1)
231                 if2_addr = Topology().get_interface_ip4(tg_node, tg_if2)
232                 if1_adj_addr = Topology().get_interface_ip4(tg_if1_adj_node,
233                                                             tg_if1_adj_if)
234                 if2_adj_addr = Topology().get_interface_ip4(tg_if2_adj_node,
235                                                             tg_if2_adj_if)
236             else:
237                 raise ValueError("Unknown Test Type")
238
239             # in case of switched environment we can override MAC addresses
240             if tg_if1_dst_mac is not None and tg_if2_dst_mac is not None:
241                 if1_adj_addr = tg_if1_dst_mac
242                 if2_adj_addr = tg_if2_dst_mac
243
244             if min(if1_pci, if2_pci) != if1_pci:
245                 if1_pci, if2_pci = if2_pci, if1_pci
246                 if1_addr, if2_addr = if2_addr, if1_addr
247                 if1_adj_addr, if2_adj_addr = if2_adj_addr, if1_adj_addr
248                 self._ifaces_reordered = True
249
250             if test_type == 'L2' or test_type == 'L3':
251                 (ret, _, _) = ssh.exec_command(
252                     "sudo sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
253                     "- port_limit: 2\n"
254                     "  version: 2\n"
255                     "  interfaces: [\"{0}\",\"{1}\"]\n"
256                     "  port_info:\n"
257                     "      - dest_mac: [{2}]\n"
258                     "        src_mac: [{3}]\n"
259                     "      - dest_mac: [{4}]\n"
260                     "        src_mac: [{5}]\n"
261                     "EOF'"\
262                     .format(if1_pci, if2_pci,
263                             "0x"+if1_adj_addr.replace(":", ",0x"),
264                             "0x"+if1_addr.replace(":", ",0x"),
265                             "0x"+if2_adj_addr.replace(":", ",0x"),
266                             "0x"+if2_addr.replace(":", ",0x")))
267             elif test_type == 'L7':
268                 (ret, _, _) = ssh.exec_command(
269                     "sudo sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
270                     "- port_limit: 2\n"
271                     "  version: 2\n"
272                     "  interfaces: [\"{0}\",\"{1}\"]\n"
273                     "  port_info:\n"
274                     "      - ip: [{2}]\n"
275                     "        default_gw: [{3}]\n"
276                     "      - ip: [{4}]\n"
277                     "        default_gw: [{5}]\n"
278                     "EOF'"\
279                     .format(if1_pci, if2_pci,
280                             if1_addr, if1_adj_addr,
281                             if2_addr, if2_adj_addr))
282             else:
283                 raise ValueError("Unknown Test Type")
284             if int(ret) != 0:
285                 raise RuntimeError('TRex config generation error')
286
287             for _ in range(0, 3):
288                 # kill TRex only if it is already running
289                 ssh.exec_command(
290                     "sh -c 'pgrep t-rex && sudo pkill t-rex && sleep 3'")
291
292                 # configure TRex
293                 (ret, _, _) = ssh.exec_command(
294                     "sh -c 'cd {0}/scripts/ && sudo ./trex-cfg'"\
295                     .format(Constants.TREX_INSTALL_DIR))
296                 if int(ret) != 0:
297                     raise RuntimeError('trex-cfg failed')
298
299                 # start TRex
300                 if test_type == 'L2' or test_type == 'L3':
301                     (ret, _, _) = ssh.exec_command(
302                         "sh -c 'cd {0}/scripts/ && "
303                         "sudo nohup ./t-rex-64 -i -c 7 --iom 0 > /tmp/trex.log "
304                         "2>&1 &' > /dev/null"\
305                         .format(Constants.TREX_INSTALL_DIR))
306                 elif test_type == 'L7':
307                     (ret, _, _) = ssh.exec_command(
308                         "sh -c 'cd {0}/scripts/ && "
309                         "sudo nohup ./t-rex-64 --astf -i -c 7 --iom 0 > "
310                         "/tmp/trex.log 2>&1 &' > /dev/null"\
311                         .format(Constants.TREX_INSTALL_DIR))
312                 else:
313                     raise ValueError("Unknown Test Type")
314                 if int(ret) != 0:
315                     ssh.exec_command("sh -c 'cat /tmp/trex.log'")
316                     raise RuntimeError('t-rex-64 startup failed')
317
318                 # get TRex server info
319                 (ret, _, _) = ssh.exec_command(
320                     "sh -c 'sleep 3; "
321                     "{0}/resources/tools/trex/trex_server_info.py'"\
322                     .format(Constants.REMOTE_FW_DIR),
323                     timeout=120)
324                 if int(ret) == 0:
325                     # If we get info TRex is running
326                     return
327             # after max retries TRex is still not responding to API
328             # critical error occurred
329             raise RuntimeError('t-rex-64 startup failed')
330
331     @staticmethod
332     def is_trex_running(node):
333         """Check if TRex is running using pidof.
334
335         :param node: Traffic generator node.
336         :type node: dict
337         :returns: True if TRex is running otherwise False.
338         :rtype: bool
339         :raises RuntimeError: If node type is not a TG.
340         """
341         if node['type'] != NodeType.TG:
342             raise RuntimeError('Node type is not a TG')
343
344         ssh = SSH()
345         ssh.connect(node)
346         ret, _, _ = ssh.exec_command_sudo("pidof t-rex")
347         return bool(int(ret) == 0)
348
349     @staticmethod
350     def teardown_traffic_generator(node):
351         """TG teardown.
352
353         :param node: Traffic generator node.
354         :type node: dict
355         :returns: nothing
356         :raises RuntimeError: If node type is not a TG,
357             or if TRex teardown fails.
358         """
359         if node['type'] != NodeType.TG:
360             raise RuntimeError('Node type is not a TG')
361         if node['subtype'] == NodeSubTypeTG.TREX:
362             ssh = SSH()
363             ssh.connect(node)
364             (ret, _, _) = ssh.exec_command(
365                 "sh -c 'sudo pkill t-rex && sleep 3'")
366             if int(ret) != 0:
367                 raise RuntimeError('pkill t-rex failed')
368
369     @staticmethod
370     def trex_stl_stop_remote_exec(node):
371         """Execute script on remote node over ssh to stop running traffic.
372
373         :param node: TRex generator node.
374         :type node: dict
375         :returns: Nothing
376         :raises RuntimeError: If stop traffic script fails.
377         """
378         ssh = SSH()
379         ssh.connect(node)
380
381         (ret, _, _) = ssh.exec_command(
382             "sh -c '{}/resources/tools/trex/"
383             "trex_stateless_stop.py'".format(Constants.REMOTE_FW_DIR))
384
385         if int(ret) != 0:
386             raise RuntimeError('TRex stateless runtime error')
387
388     def trex_stl_start_remote_exec(self, duration, rate, framesize,
389                                    traffic_type, async_call=False,
390                                    latency=True, warmup_time=5.0):
391         """Execute script on remote node over ssh to start traffic.
392
393         :param duration: Time expresed in seconds for how long to send traffic.
394         :param rate: Traffic rate expressed with units (pps, %)
395         :param framesize: L2 frame size to send (without padding and IPG).
396         :param traffic_type: Module name as a traffic type identifier.
397             See resources/traffic_profiles/trex for implemented modules.
398         :param async_call: If enabled then don't wait for all incomming trafic.
399         :param latency: With latency measurement.
400         :param warmup_time: Warmup time period.
401         :type duration: float
402         :type rate: str
403         :type framesize: str
404         :type traffic_type: str
405         :type async_call: bool
406         :type latency: bool
407         :type warmup_time: float
408         :returns: Nothing
409         :raises RuntimeError: In case of TG driver issue.
410         """
411         ssh = SSH()
412         ssh.connect(self._node)
413
414         _async = "--async" if async_call else ""
415         _latency = "--latency" if latency else ""
416         _p0, _p1 = (2, 1) if self._ifaces_reordered else (1, 2)
417
418         profile_path = ("{0}/resources/traffic_profiles/trex/"
419                         "{1}.py".format(Constants.REMOTE_FW_DIR,
420                                         traffic_type))
421         (ret, stdout, _) = ssh.exec_command(
422             "sh -c "
423             "'{0}/resources/tools/trex/trex_stateless_profile.py "
424             "--profile {1} "
425             "--duration {2} "
426             "--frame_size {3} "
427             "--rate {4} "
428             "--warmup_time {5} "
429             "--port_0 {6} "
430             "--port_1 {7} "
431             "{8} "   # --async
432             "{9}'".  # --latency
433             format(Constants.REMOTE_FW_DIR, profile_path, duration, framesize,
434                    rate, warmup_time, _p0 - 1, _p1 - 1, _async, _latency),
435             timeout=float(duration) + 60)
436
437         if int(ret) != 0:
438             raise RuntimeError('TRex stateless runtime error')
439         elif async_call:
440             #no result
441             self._received = None
442             self._sent = None
443             self._loss = None
444             self._latency = None
445         else:
446             # last line from console output
447             line = stdout.splitlines()[-1]
448
449             self._result = line
450             logger.info('TrafficGen result: {0}'.format(self._result))
451
452             self._received = self._result.split(', ')[1].split('=')[1]
453             self._sent = self._result.split(', ')[2].split('=')[1]
454             self._loss = self._result.split(', ')[3].split('=')[1]
455
456             self._latency = []
457             self._latency.append(self._result.split(', ')[4].split('=')[1])
458             self._latency.append(self._result.split(', ')[5].split('=')[1])
459
460     def stop_traffic_on_tg(self):
461         """Stop all traffic on TG.
462
463         :returns: Nothing
464         :raises RuntimeError: If TG is not set.
465         """
466         if self._node is None:
467             raise RuntimeError("TG is not set")
468         if self._node['subtype'] == NodeSubTypeTG.TREX:
469             self.trex_stl_stop_remote_exec(self._node)
470
471     def send_traffic_on_tg(self, duration, rate, framesize,
472                            traffic_type, warmup_time=5, async_call=False,
473                            latency=True):
474         """Send traffic from all configured interfaces on TG.
475
476         :param duration: Duration of test traffic generation in seconds.
477         :param rate: Offered load per interface (e.g. 1%, 3gbps, 4mpps, ...).
478         :param framesize: Frame size (L2) in Bytes.
479         :param traffic_type: Module name as a traffic type identifier.
480             See resources/traffic_profiles/trex for implemented modules.
481         :param warmup_time: Warmup phase in seconds.
482         :param async_call: Async mode.
483         :param latency: With latency measurement.
484         :type duration: str
485         :type rate: str
486         :type framesize: str
487         :type traffic_type: str
488         :type warmup_time: float
489         :type async_call: bool
490         :type latency: bool
491         :returns: TG output.
492         :rtype: str
493         :raises RuntimeError: If TG is not set, or if node is not TG,
494             or if subtype is not specified.
495         :raises NotImplementedError: If TG is not supported.
496         """
497
498         node = self._node
499         if node is None:
500             raise RuntimeError("TG is not set")
501
502         if node['type'] != NodeType.TG:
503             raise RuntimeError('Node type is not a TG')
504
505         if node['subtype'] is None:
506             raise RuntimeError('TG subtype not defined')
507         elif node['subtype'] == NodeSubTypeTG.TREX:
508             self.trex_stl_start_remote_exec(duration, rate, framesize,
509                                             traffic_type, async_call, latency,
510                                             warmup_time=warmup_time)
511         else:
512             raise NotImplementedError("TG subtype not supported")
513
514         return self._result
515
516     def no_traffic_loss_occurred(self):
517         """Fail if loss occurred in traffic run.
518
519         :returns: nothing
520         :raises Exception: If loss occured.
521         """
522         if self._loss is None:
523             raise RuntimeError('The traffic generation has not been issued')
524         if self._loss != '0':
525             raise RuntimeError('Traffic loss occurred: {0}'.format(self._loss))
526
527     def fail_if_no_traffic_forwarded(self):
528         """Fail if no traffic forwarded.
529
530         :returns: nothing
531         :raises Exception: If no traffic forwarded.
532         """
533         if self._received is None:
534             raise RuntimeError('The traffic generation has not been issued')
535         if self._received == '0':
536             raise RuntimeError('No traffic forwarded')
537
538     def partial_traffic_loss_accepted(self, loss_acceptance,
539                                       loss_acceptance_type):
540         """Fail if loss is higher then accepted in traffic run.
541
542         :param loss_acceptance: Permitted drop ratio or frames count.
543         :param loss_acceptance_type: Type of permitted loss.
544         :type loss_acceptance: float
545         :type loss_acceptance_type: LossAcceptanceType
546         :returns: nothing
547         :raises Exception: If loss is above acceptance criteria.
548         """
549         if self._loss is None:
550             raise Exception('The traffic generation has not been issued')
551
552         if loss_acceptance_type == 'percentage':
553             loss = (float(self._loss) / float(self._sent)) * 100
554         elif loss_acceptance_type == 'frames':
555             loss = float(self._loss)
556         else:
557             raise Exception('Loss acceptance type not supported')
558
559         if loss > float(loss_acceptance):
560             raise Exception("Traffic loss {} above loss acceptance: {}".format(
561                 loss, loss_acceptance))
562
563     def set_rate_provider_defaults(self, frame_size, traffic_type,
564                                    warmup_time=0.0):
565         """Store values accessed by measure().
566
567         :param frame_size: Frame size identifier or value [B].
568         :param traffic_type: Module name as a traffic type identifier.
569             See resources/traffic_profiles/trex for implemented modules.
570         :param warmup_time: Traffic duration before measurement starts [s].
571         :type frame_size: str or int
572         :type traffic_type: str
573         :type warmup_time: float
574         """
575         self.frame_size = frame_size
576         self.traffic_type = str(traffic_type)
577         self.warmup_time = float(warmup_time)
578
579     def measure(self, duration, transmit_rate):
580         """Run bi-directional measurement, parse and return results.
581
582         :param duration: Trial duration [s].
583         :param transmit_rate: Target bidirectional transmit rate [pps].
584         :type duration: float
585         :type transmit_rate: float
586         :returns: Structure containing the result of the measurement.
587         :rtype: ReceiveRateMeasurement
588         :raises RuntimeError: If TG is not set, or if node is not TG,
589             or if subtype is not specified.
590         :raises NotImplementedError: If TG is not supported.
591         """
592         duration = float(duration)
593         transmit_rate = float(transmit_rate)
594         # Trex needs target Tr per stream, but reports aggregate Tx and Dx.
595         unit_rate = str(transmit_rate / 2.0) + "pps"
596         self.send_traffic_on_tg(
597             duration, unit_rate, self.frame_size, self.traffic_type,
598             self.warmup_time, latency=True)
599         transmit_count = int(self.get_sent())
600         loss_count = int(self.get_loss())
601         measurement = ReceiveRateMeasurement(
602             duration, transmit_rate, transmit_count, loss_count)
603         measurement.latency = self.get_latency_int()
604         return measurement
605
606
607 class OptimizedSearch(object):
608     """Class to be imported as Robot Library, containing a single keyword."""
609
610     @staticmethod
611     def perform_optimized_ndrpdr_search(
612             frame_size, traffic_type, minimum_transmit_rate,
613             maximum_transmit_rate, packet_loss_ratio=0.005,
614             final_relative_width=0.005, final_trial_duration=30.0,
615             initial_trial_duration=1.0, number_of_intermediate_phases=2,
616             timeout=720.0, doublings=1):
617         """Setup initialized TG, perform optimized search, return intervals.
618
619         :param frame_size: Frame size identifier or value [B].
620         :param traffic_type: Module name as a traffic type identifier.
621             See resources/traffic_profiles/trex for implemented modules.
622         :param minimum_transmit_rate: Minimal bidirectional
623             target transmit rate [pps].
624         :param maximum_transmit_rate: Maximal bidirectional
625             target transmit rate [pps].
626         :param packet_loss_ratio: Fraction of packets lost, for PDR [1].
627         :param final_relative_width: Final lower bound transmit rate
628             cannot be more distant that this multiple of upper bound [1].
629         :param final_trial_duration: Trial duration for the final phase [s].
630         :param initial_trial_duration: Trial duration for the initial phase
631             and also for the first intermediate phase [s].
632         :param number_of_intermediate_phases: Number of intermediate phases
633             to perform before the final phase [1].
634         :param timeout: The search will fail itself when not finished
635             before this overall time [s].
636         :param doublings: How many doublings to do in external search step.
637             Default 1 is suitable for fairly stable tests,
638             less stable tests might get better overal duration with 2 or more.
639         :type frame_size: str or int
640         :type traffic_type: str
641         :type minimum_transmit_rate: float
642         :type maximum_transmit_rate: float
643         :type packet_loss_ratio: float
644         :type final_relative_width: float
645         :type final_trial_duration: float
646         :type initial_trial_duration: float
647         :type number_of_intermediate_phases: int
648         :type timeout: float
649         :type doublings: int
650         :returns: Structure containing narrowed down NDR and PDR intervals
651             and their measurements.
652         :rtype: NdrPdrResult
653         :raises RuntimeError: If total duration is larger than timeout.
654         """
655         # we need instance of TrafficGenerator instantiated by Robot Framework
656         # to be able to use trex_stl-*()
657         tg_instance = BuiltIn().get_library_instance(
658             'resources.libraries.python.TrafficGenerator')
659         tg_instance.set_rate_provider_defaults(frame_size, traffic_type)
660         algorithm = MultipleLossRatioSearch(
661             measurer=tg_instance, final_trial_duration=final_trial_duration,
662             final_relative_width=final_relative_width,
663             number_of_intermediate_phases=number_of_intermediate_phases,
664             initial_trial_duration=initial_trial_duration, timeout=timeout,
665             doublings=doublings)
666         result = algorithm.narrow_down_ndr_and_pdr(
667             minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio)
668         return result