FIX: CPU util for NF
[csit.git] / resources / libraries / python / TrafficGenerator.py
1 # Copyright (c) 2018 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 from robot.api import logger
17 from robot.libraries.BuiltIn import BuiltIn
18
19 from .DropRateSearch import DropRateSearch
20 from .constants import Constants
21 from .ssh import SSH
22 from .topology import NodeType
23 from .topology import NodeSubTypeTG
24 from .topology import Topology
25 from .MLRsearch.AbstractMeasurer import AbstractMeasurer
26 from .MLRsearch.MultipleLossRatioSearch import MultipleLossRatioSearch
27 from .MLRsearch.ReceiveRateMeasurement import ReceiveRateMeasurement
28
29 __all__ = ['TGDropRateSearchImpl', 'TrafficGenerator', 'OptimizedSearch']
30
31
32 class TGDropRateSearchImpl(DropRateSearch):
33     """Drop Rate Search implementation."""
34
35     def __init__(self):
36         super(TGDropRateSearchImpl, self).__init__()
37
38     def measure_loss(self, rate, frame_size, loss_acceptance,
39                      loss_acceptance_type, traffic_type, skip_warmup=False):
40         """Runs the traffic and evaluate the measured results.
41
42         :param rate: Offered traffic load.
43         :param frame_size: Size of frame.
44         :param loss_acceptance: Permitted drop ratio or frames count.
45         :param loss_acceptance_type: Type of permitted loss.
46         :param traffic_type: Module name as a traffic type identifier.
47             See resources/traffic_profiles/trex for implemented modules.
48         :param skip_warmup: Start TRex without warmup traffic if true.
49         :type rate: float
50         :type frame_size: str
51         :type loss_acceptance: float
52         :type loss_acceptance_type: LossAcceptanceType
53         :type traffic_type: str
54         :type skip_warmup: bool
55         :returns: Drop threshold exceeded? (True/False)
56         :rtype: bool
57         :raises NotImplementedError: If TG is not supported.
58         :raises RuntimeError: If TG is not specified.
59         """
60         # we need instance of TrafficGenerator instantiated by Robot Framework
61         # to be able to use trex_stl-*()
62         tg_instance = BuiltIn().get_library_instance(
63             'resources.libraries.python.TrafficGenerator')
64
65         if tg_instance.node['subtype'] is None:
66             raise RuntimeError('TG subtype not defined')
67         elif tg_instance.node['subtype'] == NodeSubTypeTG.TREX:
68             unit_rate = str(rate) + self.get_rate_type_str()
69             if skip_warmup:
70                 tg_instance.trex_stl_start_remote_exec(self.get_duration(),
71                                                        unit_rate, frame_size,
72                                                        traffic_type,
73                                                        warmup_time=0.0)
74             else:
75                 tg_instance.trex_stl_start_remote_exec(self.get_duration(),
76                                                        unit_rate, frame_size,
77                                                        traffic_type)
78             loss = tg_instance.get_loss()
79             sent = tg_instance.get_sent()
80             if self.loss_acceptance_type_is_percentage():
81                 loss = (float(loss) / float(sent)) * 100
82
83             logger.trace("comparing: {} < {} {}".format(loss,
84                                                         loss_acceptance,
85                                                         loss_acceptance_type))
86             if float(loss) > float(loss_acceptance):
87                 return False
88             else:
89                 return True
90         else:
91             raise NotImplementedError("TG subtype not supported")
92
93     def get_latency(self):
94         """Returns min/avg/max latency.
95
96         :returns: Latency stats.
97         :rtype: list
98         """
99         tg_instance = BuiltIn().get_library_instance(
100             'resources.libraries.python.TrafficGenerator')
101         return tg_instance.get_latency_int()
102
103
104 class TrafficGenerator(AbstractMeasurer):
105     """Traffic Generator.
106
107     FIXME: Describe API."""
108
109     # TODO: Decrease friction between various search and rate provider APIs.
110     # TODO: Remove "trex" from lines which could work with other TGs.
111
112     # Use one instance of TrafficGenerator for all tests in test suite
113     ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
114
115     def __init__(self):
116         self._result = None
117         self._loss = None
118         self._sent = None
119         self._latency = None
120         self._received = None
121         self._node = None
122         # T-REX interface order mapping
123         self._ifaces_reordered = False
124         # Parameters not given by measure().
125         self.frame_size = None
126         self.traffic_type = None
127         self.warmup_time = None
128
129     @property
130     def node(self):
131         """Getter.
132
133         :returns: Traffic generator node.
134         :rtype: dict
135         """
136         return self._node
137
138     def get_loss(self):
139         """Return number of lost packets.
140
141         :returns: Number of lost packets.
142         :rtype: str
143         """
144         return self._loss
145
146     def get_sent(self):
147         """Return number of sent packets.
148
149         :returns: Number of sent packets.
150         :rtype: str
151         """
152         return self._sent
153
154     def get_received(self):
155         """Return number of received packets.
156
157         :returns: Number of received packets.
158         :rtype: str
159         """
160         return self._received
161
162     def get_latency_int(self):
163         """Return rounded min/avg/max latency.
164
165         :returns: Latency stats.
166         :rtype: list
167         """
168         return self._latency
169
170     def initialize_traffic_generator(self, tg_node, tg_if1, tg_if2,
171                                      tg_if1_adj_node, tg_if1_adj_if,
172                                      tg_if2_adj_node, tg_if2_adj_if,
173                                      test_type,
174                                      tg_if1_dst_mac=None, tg_if2_dst_mac=None):
175         """TG initialization.
176
177         :param tg_node: Traffic generator node.
178         :param tg_if1: TG - name of first interface.
179         :param tg_if2: TG - name of second interface.
180         :param tg_if1_adj_node: TG if1 adjecent node.
181         :param tg_if1_adj_if: TG if1 adjecent interface.
182         :param tg_if2_adj_node: TG if2 adjecent node.
183         :param tg_if2_adj_if: TG if2 adjecent interface.
184         :param test_type: 'L2', 'L3' or 'L7' - OSI Layer testing type.
185         :param tg_if1_dst_mac: Interface 1 destination MAC address.
186         :param tg_if2_dst_mac: Interface 2 destination MAC address.
187         :type tg_node: dict
188         :type tg_if1: str
189         :type tg_if2: str
190         :type tg_if1_adj_node: dict
191         :type tg_if1_adj_if: str
192         :type tg_if2_adj_node: dict
193         :type tg_if2_adj_if: str
194         :type test_type: str
195         :type tg_if1_dst_mac: str
196         :type tg_if2_dst_mac: str
197         :returns: nothing
198         :raises RuntimeError: In case of issue during initialization.
199         """
200         if tg_node['type'] != NodeType.TG:
201             raise RuntimeError('Node type is not a TG')
202         self._node = tg_node
203
204         if tg_node['subtype'] == NodeSubTypeTG.TREX:
205             ssh = SSH()
206             ssh.connect(tg_node)
207
208             (ret, _, _) = ssh.exec_command(
209                 "sudo -E sh -c '{0}/resources/tools/trex/"
210                 "trex_installer.sh {1}'".format(Constants.REMOTE_FW_DIR,
211                                                 Constants.TREX_INSTALL_VERSION),
212                 timeout=1800)
213             if int(ret) != 0:
214                 raise RuntimeError('TRex installation failed.')
215
216             if1_pci = Topology().get_interface_pci_addr(tg_node, tg_if1)
217             if2_pci = Topology().get_interface_pci_addr(tg_node, tg_if2)
218             if1_addr = Topology().get_interface_mac(tg_node, tg_if1)
219             if2_addr = Topology().get_interface_mac(tg_node, tg_if2)
220
221             if test_type == 'L2':
222                 if1_adj_addr = if2_addr
223                 if2_adj_addr = if1_addr
224             elif test_type == 'L3':
225                 if1_adj_addr = Topology().get_interface_mac(tg_if1_adj_node,
226                                                             tg_if1_adj_if)
227                 if2_adj_addr = Topology().get_interface_mac(tg_if2_adj_node,
228                                                             tg_if2_adj_if)
229             elif test_type == 'L7':
230                 if1_addr = Topology().get_interface_ip4(tg_node, tg_if1)
231                 if2_addr = Topology().get_interface_ip4(tg_node, tg_if2)
232                 if1_adj_addr = Topology().get_interface_ip4(tg_if1_adj_node,
233                                                             tg_if1_adj_if)
234                 if2_adj_addr = Topology().get_interface_ip4(tg_if2_adj_node,
235                                                             tg_if2_adj_if)
236             else:
237                 raise ValueError("Unknown Test Type")
238
239             # in case of switched environment we can override MAC addresses
240             if tg_if1_dst_mac is not None and tg_if2_dst_mac is not None:
241                 if1_adj_addr = tg_if1_dst_mac
242                 if2_adj_addr = tg_if2_dst_mac
243
244             if min(if1_pci, if2_pci) != if1_pci:
245                 if1_pci, if2_pci = if2_pci, if1_pci
246                 if1_addr, if2_addr = if2_addr, if1_addr
247                 if1_adj_addr, if2_adj_addr = if2_adj_addr, if1_adj_addr
248                 self._ifaces_reordered = True
249
250             if test_type == 'L2' or test_type == 'L3':
251                 (ret, _, _) = ssh.exec_command(
252                     "sudo sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
253                     "- port_limit: 2\n"
254                     "  version: 2\n"
255                     "  interfaces: [\"{0}\",\"{1}\"]\n"
256                     "  port_info:\n"
257                     "      - dest_mac: [{2}]\n"
258                     "        src_mac: [{3}]\n"
259                     "      - dest_mac: [{4}]\n"
260                     "        src_mac: [{5}]\n"
261                     "EOF'"\
262                     .format(if1_pci, if2_pci,
263                             "0x"+if1_adj_addr.replace(":", ",0x"),
264                             "0x"+if1_addr.replace(":", ",0x"),
265                             "0x"+if2_adj_addr.replace(":", ",0x"),
266                             "0x"+if2_addr.replace(":", ",0x")))
267             elif test_type == 'L7':
268                 (ret, _, _) = ssh.exec_command(
269                     "sudo sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
270                     "- port_limit: 2\n"
271                     "  version: 2\n"
272                     "  interfaces: [\"{0}\",\"{1}\"]\n"
273                     "  port_info:\n"
274                     "      - ip: [{2}]\n"
275                     "        default_gw: [{3}]\n"
276                     "      - ip: [{4}]\n"
277                     "        default_gw: [{5}]\n"
278                     "EOF'"\
279                     .format(if1_pci, if2_pci,
280                             if1_addr, if1_adj_addr,
281                             if2_addr, if2_adj_addr))
282             else:
283                 raise ValueError("Unknown Test Type")
284             if int(ret) != 0:
285                 raise RuntimeError('TRex config generation error')
286
287             for _ in range(0, 3):
288                 # kill TRex only if it is already running
289                 ssh.exec_command(
290                     "sh -c 'pgrep t-rex && sudo pkill t-rex && sleep 3'")
291
292                 # configure TRex
293                 (ret, _, _) = ssh.exec_command(
294                     "sh -c 'cd {0}/scripts/ && sudo ./trex-cfg'"\
295                     .format(Constants.TREX_INSTALL_DIR))
296                 if int(ret) != 0:
297                     raise RuntimeError('trex-cfg failed')
298
299                 # start TRex
300                 if test_type == 'L2' or test_type == 'L3':
301                     (ret, _, _) = ssh.exec_command(
302                         "sh -c 'cd {0}/scripts/ && "
303                         "sudo nohup ./t-rex-64 -i -c 7 --iom 0 > /tmp/trex.log "
304                         "2>&1 &' > /dev/null"\
305                         .format(Constants.TREX_INSTALL_DIR))
306                 elif test_type == 'L7':
307                     (ret, _, _) = ssh.exec_command(
308                         "sh -c 'cd {0}/scripts/ && "
309                         "sudo nohup ./t-rex-64 --astf -i -c 7 --iom 0 > "
310                         "/tmp/trex.log 2>&1 &' > /dev/null"\
311                         .format(Constants.TREX_INSTALL_DIR))
312                 else:
313                     raise ValueError("Unknown Test Type")
314                 if int(ret) != 0:
315                     ssh.exec_command("sh -c 'cat /tmp/trex.log'")
316                     raise RuntimeError('t-rex-64 startup failed')
317
318                 # get TRex server info
319                 (ret, _, _) = ssh.exec_command(
320                     "sh -c 'sleep 3; "
321                     "{0}/resources/tools/trex/trex_server_info.py'"\
322                     .format(Constants.REMOTE_FW_DIR),
323                     timeout=120)
324                 if int(ret) == 0:
325                     # If we get info TRex is running
326                     return
327             # after max retries TRex is still not responding to API
328             # critical error occurred
329             raise RuntimeError('t-rex-64 startup failed')
330
331     @staticmethod
332     def is_trex_running(node):
333         """Check if TRex is running using pidof.
334
335         :param node: Traffic generator node.
336         :type node: dict
337         :returns: True if TRex is running otherwise False.
338         :rtype: bool
339         :raises RuntimeError: If node type is not a TG.
340         """
341         if node['type'] != NodeType.TG:
342             raise RuntimeError('Node type is not a TG')
343
344         ssh = SSH()
345         ssh.connect(node)
346         ret, _, _ = ssh.exec_command_sudo("pidof t-rex")
347         return bool(int(ret) == 0)
348
349     @staticmethod
350     def teardown_traffic_generator(node):
351         """TG teardown.
352
353         :param node: Traffic generator node.
354         :type node: dict
355         :returns: nothing
356         :raises RuntimeError: If node type is not a TG,
357             or if TRex teardown fails.
358         """
359         if node['type'] != NodeType.TG:
360             raise RuntimeError('Node type is not a TG')
361         if node['subtype'] == NodeSubTypeTG.TREX:
362             ssh = SSH()
363             ssh.connect(node)
364             (ret, _, _) = ssh.exec_command(
365                 "sh -c 'sudo pkill t-rex && sleep 3'")
366             if int(ret) != 0:
367                 raise RuntimeError('pkill t-rex failed')
368
369     @staticmethod
370     def trex_stl_stop_remote_exec(node):
371         """Execute script on remote node over ssh to stop running traffic.
372
373         :param node: TRex generator node.
374         :type node: dict
375         :returns: Nothing
376         :raises RuntimeError: If stop traffic script fails.
377         """
378         ssh = SSH()
379         ssh.connect(node)
380
381         (ret, _, _) = ssh.exec_command(
382             "sh -c '{}/resources/tools/trex/"
383             "trex_stateless_stop.py'".format(Constants.REMOTE_FW_DIR))
384
385         if int(ret) != 0:
386             raise RuntimeError('TRex stateless runtime error')
387
388     def trex_stl_start_remote_exec(self, duration, rate, framesize,
389                                    traffic_type, async_call=False,
390                                    latency=True, warmup_time=5.0):
391         """Execute script on remote node over ssh to start traffic.
392
393         :param duration: Time expresed in seconds for how long to send traffic.
394         :param rate: Traffic rate expressed with units (pps, %)
395         :param framesize: L2 frame size to send (without padding and IPG).
396         :param traffic_type: Module name as a traffic type identifier.
397             See resources/traffic_profiles/trex for implemented modules.
398         :param async_call: If enabled then don't wait for all incomming trafic.
399         :param latency: With latency measurement.
400         :param warmup_time: Warmup time period.
401         :type duration: float
402         :type rate: str
403         :type framesize: str
404         :type traffic_type: str
405         :type async_call: bool
406         :type latency: bool
407         :type warmup_time: float
408         :returns: Nothing
409         :raises RuntimeError: In case of TG driver issue.
410         """
411         ssh = SSH()
412         ssh.connect(self._node)
413
414         _async = "--async" if async_call else ""
415         _latency = "--latency" if latency else ""
416         _p0, _p1 = (2, 1) if self._ifaces_reordered else (1, 2)
417
418         profile_path = ("{0}/resources/traffic_profiles/trex/"
419                         "{1}.py".format(Constants.REMOTE_FW_DIR,
420                                         traffic_type))
421         (ret, stdout, _) = ssh.exec_command(
422             "sh -c "
423             "'{0}/resources/tools/trex/trex_stateless_profile.py "
424             "--profile {1} "
425             "--duration {2} "
426             "--frame_size {3} "
427             "--rate {4} "
428             "--warmup_time {5} "
429             "--port_0 {6} "
430             "--port_1 {7} "
431             "{8} "   # --async
432             "{9}'".  # --latency
433             format(Constants.REMOTE_FW_DIR, profile_path, duration, framesize,
434                    rate, warmup_time, _p0 - 1, _p1 - 1, _async, _latency),
435             timeout=float(duration) + 60)
436
437         if int(ret) != 0:
438             raise RuntimeError('TRex stateless runtime error')
439         elif async_call:
440             #no result
441             self._received = None
442             self._sent = None
443             self._loss = None
444             self._latency = None
445         else:
446             # last line from console output
447             line = stdout.splitlines()[-1]
448
449             self._result = line
450             logger.info('TrafficGen result: {0}'.format(self._result))
451
452             self._received = self._result.split(', ')[1].split('=')[1]
453             self._sent = self._result.split(', ')[2].split('=')[1]
454             self._loss = self._result.split(', ')[3].split('=')[1]
455
456             self._latency = []
457             self._latency.append(self._result.split(', ')[4].split('=')[1])
458             self._latency.append(self._result.split(', ')[5].split('=')[1])
459
460     def trex_stl_start_unidirection(self, duration, rate, framesize,
461                                     traffic_type, tx_port=0, rx_port=1,
462                                     async_call=False, latency=False,
463                                     warmup_time=5.0):
464         """Execute script on remote node over ssh to start unidirection traffic.
465         The purpose of this function is to support performance test that need to
466         measure unidirectional traffic, e.g. Load balancer maglev mode and l3dsr
467         mode test.
468
469         :param duration: Time expresed in seconds for how long to send traffic.
470         :param rate: Traffic rate expressed with units (pps, %)
471         :param framesize: L2 frame size to send (without padding and IPG).
472         :param traffic_type: Module name as a traffic type identifier.
473             See resources/traffic_profiles/trex for implemented modules.
474         :param tx_port: Traffic generator transmit port.
475         :param rx_port: Traffic generator receive port.
476         :param latency: With latency measurement.
477         :param async_call: If enabled then don't wait for all incomming trafic.
478         :param warmup_time: Warmup time period.
479         :type duration: float
480         :type rate: str
481         :type framesize: str
482         :type traffic_type: str
483         :type tx_port: integer
484         :type rx_port: integer
485         :type latency: bool
486         :type async_call: bool
487         :type warmup_time: float
488         :returns: Nothing
489         :raises RuntimeError: In case of TG driver issue.
490         """
491         ssh = SSH()
492         ssh.connect(self._node)
493
494         _latency = "--latency" if latency else ""
495         _async = "--async" if async_call else ""
496
497         profile_path = ("{0}/resources/traffic_profiles/trex/"
498                         "{1}.py".format(Constants.REMOTE_FW_DIR,
499                                         traffic_type))
500         (ret, stdout, _) = ssh.exec_command(
501             "sh -c "
502             "'{0}/resources/tools/trex/trex_stateless_profile.py "
503             "--profile {1} "
504             "--duration {2} "
505             "--frame_size {3} "
506             "--rate {4} "
507             "--warmup_time {5} "
508             "--port_0 {6} "
509             "--port_1 {7} "
510             "{8} "  # --async
511             "{9} "  # --latency
512             "{10}'".  # --unidirection
513             format(Constants.REMOTE_FW_DIR, profile_path, duration, framesize,
514                    rate, warmup_time, tx_port, rx_port, _async, _latency,
515                    "--unidirection"),
516             timeout=float(duration) + 60)
517
518         if int(ret) != 0:
519             raise RuntimeError('TRex unidirection runtime error')
520         elif async_call:
521             #no result
522             self._received = None
523             self._sent = None
524             self._loss = None
525             self._latency = None
526         else:
527             # last line from console output
528             line = stdout.splitlines()[-1]
529
530             self._result = line
531             logger.info('TrafficGen result: {0}'.format(self._result))
532
533             self._received = self._result.split(', ')[1].split('=')[1]
534             self._sent = self._result.split(', ')[2].split('=')[1]
535             self._loss = self._result.split(', ')[3].split('=')[1]
536             self._latency = []
537             self._latency.append(self._result.split(', ')[4].split('=')[1])
538
539     def stop_traffic_on_tg(self):
540         """Stop all traffic on TG.
541
542         :returns: Nothing
543         :raises RuntimeError: If TG is not set.
544         """
545         if self._node is None:
546             raise RuntimeError("TG is not set")
547         if self._node['subtype'] == NodeSubTypeTG.TREX:
548             self.trex_stl_stop_remote_exec(self._node)
549
550     def send_traffic_on_tg(self, duration, rate, framesize, traffic_type,
551                            unidirection=False, tx_port=0, rx_port=1,
552                            warmup_time=5, async_call=False, latency=True):
553         """Send traffic from all configured interfaces on TG.
554
555         :param duration: Duration of test traffic generation in seconds.
556         :param rate: Offered load per interface (e.g. 1%, 3gbps, 4mpps, ...).
557         :param framesize: Frame size (L2) in Bytes.
558         :param traffic_type: Module name as a traffic type identifier.
559             See resources/traffic_profiles/trex for implemented modules.
560         :param unidirection: Traffic is unidirectional.
561         :param tx_port: Traffic generator transmit port.
562         :param rx_port: Traffic generator receive port.
563         :param warmup_time: Warmup phase in seconds.
564         :param async_call: Async mode.
565         :param latency: With latency measurement.
566         :type duration: str
567         :type rate: str
568         :type framesize: str
569         :type traffic_type: str
570         :type unidirection: bool
571         :type tx_port: integer
572         :type rx_port: integer
573         :type warmup_time: float
574         :type async_call: bool
575         :type latency: bool
576         :returns: TG output.
577         :rtype: str
578         :raises RuntimeError: If TG is not set, or if node is not TG,
579             or if subtype is not specified.
580         :raises NotImplementedError: If TG is not supported.
581         """
582
583         node = self._node
584         if node is None:
585             raise RuntimeError("TG is not set")
586
587         if node['type'] != NodeType.TG:
588             raise RuntimeError('Node type is not a TG')
589
590         if node['subtype'] is None:
591             raise RuntimeError('TG subtype not defined')
592         elif node['subtype'] == NodeSubTypeTG.TREX:
593             if unidirection:
594                 self.trex_stl_start_unidirection(duration, rate, framesize,
595                                                  traffic_type, tx_port,
596                                                  rx_port, async_call, latency,
597                                                  warmup_time)
598             else:
599                 self.trex_stl_start_remote_exec(duration, rate, framesize,
600                                                 traffic_type, async_call,
601                                                 latency, warmup_time)
602         else:
603             raise NotImplementedError("TG subtype not supported")
604
605         return self._result
606
607     def no_traffic_loss_occurred(self):
608         """Fail if loss occurred in traffic run.
609
610         :returns: nothing
611         :raises Exception: If loss occured.
612         """
613         if self._loss is None:
614             raise RuntimeError('The traffic generation has not been issued')
615         if self._loss != '0':
616             raise RuntimeError('Traffic loss occurred: {0}'.format(self._loss))
617
618     def fail_if_no_traffic_forwarded(self):
619         """Fail if no traffic forwarded.
620
621         :returns: nothing
622         :raises Exception: If no traffic forwarded.
623         """
624         if self._received is None:
625             raise RuntimeError('The traffic generation has not been issued')
626         if self._received == '0':
627             raise RuntimeError('No traffic forwarded')
628
629     def partial_traffic_loss_accepted(self, loss_acceptance,
630                                       loss_acceptance_type):
631         """Fail if loss is higher then accepted in traffic run.
632
633         :param loss_acceptance: Permitted drop ratio or frames count.
634         :param loss_acceptance_type: Type of permitted loss.
635         :type loss_acceptance: float
636         :type loss_acceptance_type: LossAcceptanceType
637         :returns: nothing
638         :raises Exception: If loss is above acceptance criteria.
639         """
640         if self._loss is None:
641             raise Exception('The traffic generation has not been issued')
642
643         if loss_acceptance_type == 'percentage':
644             loss = (float(self._loss) / float(self._sent)) * 100
645         elif loss_acceptance_type == 'frames':
646             loss = float(self._loss)
647         else:
648             raise Exception('Loss acceptance type not supported')
649
650         if loss > float(loss_acceptance):
651             raise Exception("Traffic loss {} above loss acceptance: {}".format(
652                 loss, loss_acceptance))
653
654     def set_rate_provider_defaults(self, frame_size, traffic_type,
655                                    warmup_time=0.0):
656         """Store values accessed by measure().
657
658         :param frame_size: Frame size identifier or value [B].
659         :param traffic_type: Module name as a traffic type identifier.
660             See resources/traffic_profiles/trex for implemented modules.
661         :param warmup_time: Traffic duration before measurement starts [s].
662         :type frame_size: str or int
663         :type traffic_type: str
664         :type warmup_time: float
665         """
666         self.frame_size = frame_size
667         self.traffic_type = str(traffic_type)
668         self.warmup_time = float(warmup_time)
669
670     def measure(self, duration, transmit_rate):
671         """Run bi-directional measurement, parse and return results.
672
673         :param duration: Trial duration [s].
674         :param transmit_rate: Target bidirectional transmit rate [pps].
675         :type duration: float
676         :type transmit_rate: float
677         :returns: Structure containing the result of the measurement.
678         :rtype: ReceiveRateMeasurement
679         :raises RuntimeError: If TG is not set, or if node is not TG,
680             or if subtype is not specified.
681         :raises NotImplementedError: If TG is not supported.
682         """
683         duration = float(duration)
684         transmit_rate = float(transmit_rate)
685         # Trex needs target Tr per stream, but reports aggregate Tx and Dx.
686         unit_rate = str(transmit_rate / 2.0) + "pps"
687         self.send_traffic_on_tg(
688             duration, unit_rate, self.frame_size, self.traffic_type,
689             self.warmup_time, latency=True)
690         transmit_count = int(self.get_sent())
691         loss_count = int(self.get_loss())
692         measurement = ReceiveRateMeasurement(
693             duration, transmit_rate, transmit_count, loss_count)
694         measurement.latency = self.get_latency_int()
695         return measurement
696
697
698 class OptimizedSearch(object):
699     """Class to be imported as Robot Library, containing a single keyword."""
700
701     @staticmethod
702     def perform_optimized_ndrpdr_search(
703             frame_size, traffic_type, minimum_transmit_rate,
704             maximum_transmit_rate, packet_loss_ratio=0.005,
705             final_relative_width=0.005, final_trial_duration=30.0,
706             initial_trial_duration=1.0, number_of_intermediate_phases=2,
707             timeout=720.0, doublings=1):
708         """Setup initialized TG, perform optimized search, return intervals.
709
710         :param frame_size: Frame size identifier or value [B].
711         :param traffic_type: Module name as a traffic type identifier.
712             See resources/traffic_profiles/trex for implemented modules.
713         :param minimum_transmit_rate: Minimal bidirectional
714             target transmit rate [pps].
715         :param maximum_transmit_rate: Maximal bidirectional
716             target transmit rate [pps].
717         :param packet_loss_ratio: Fraction of packets lost, for PDR [1].
718         :param final_relative_width: Final lower bound transmit rate
719             cannot be more distant that this multiple of upper bound [1].
720         :param final_trial_duration: Trial duration for the final phase [s].
721         :param initial_trial_duration: Trial duration for the initial phase
722             and also for the first intermediate phase [s].
723         :param number_of_intermediate_phases: Number of intermediate phases
724             to perform before the final phase [1].
725         :param timeout: The search will fail itself when not finished
726             before this overall time [s].
727         :param doublings: How many doublings to do in external search step.
728             Default 1 is suitable for fairly stable tests,
729             less stable tests might get better overal duration with 2 or more.
730         :type frame_size: str or int
731         :type traffic_type: str
732         :type minimum_transmit_rate: float
733         :type maximum_transmit_rate: float
734         :type packet_loss_ratio: float
735         :type final_relative_width: float
736         :type final_trial_duration: float
737         :type initial_trial_duration: float
738         :type number_of_intermediate_phases: int
739         :type timeout: float
740         :type doublings: int
741         :returns: Structure containing narrowed down NDR and PDR intervals
742             and their measurements.
743         :rtype: NdrPdrResult
744         :raises RuntimeError: If total duration is larger than timeout.
745         """
746         # we need instance of TrafficGenerator instantiated by Robot Framework
747         # to be able to use trex_stl-*()
748         tg_instance = BuiltIn().get_library_instance(
749             'resources.libraries.python.TrafficGenerator')
750         tg_instance.set_rate_provider_defaults(frame_size, traffic_type)
751         algorithm = MultipleLossRatioSearch(
752             measurer=tg_instance, final_trial_duration=final_trial_duration,
753             final_relative_width=final_relative_width,
754             number_of_intermediate_phases=number_of_intermediate_phases,
755             initial_trial_duration=initial_trial_duration, timeout=timeout,
756             doublings=doublings)
757         result = algorithm.narrow_down_ndr_and_pdr(
758             minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio)
759         return result