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