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