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