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