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