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