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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
14 """Performance testing traffic generator library."""
16 from robot.api import logger
17 from robot.libraries.BuiltIn import BuiltIn
19 from .DropRateSearch import DropRateSearch
20 from .constants import Constants
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
29 __all__ = ['TGDropRateSearchImpl', 'TrafficGenerator', 'OptimizedSearch']
32 class TGDropRateSearchImpl(DropRateSearch):
33 """Drop Rate Search implementation."""
36 super(TGDropRateSearchImpl, self).__init__()
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.
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.
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)
57 :raises NotImplementedError: If TG is not supported.
58 :raises RuntimeError: If TG is not specified.
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')
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()
70 tg_instance.trex_stl_start_remote_exec(self.get_duration(),
71 unit_rate, frame_size,
75 tg_instance.trex_stl_start_remote_exec(self.get_duration(),
76 unit_rate, frame_size,
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
83 logger.trace("comparing: {} < {} {}".format(loss,
85 loss_acceptance_type))
86 if float(loss) > float(loss_acceptance):
91 raise NotImplementedError("TG subtype not supported")
93 def get_latency(self):
94 """Returns min/avg/max latency.
96 :returns: Latency stats.
99 tg_instance = BuiltIn().get_library_instance(
100 'resources.libraries.python.TrafficGenerator')
101 return tg_instance.get_latency_int()
104 class TrafficGenerator(AbstractMeasurer):
105 """Traffic Generator.
107 FIXME: Describe API."""
109 # TODO: Decrease friction between various search and rate provider APIs.
110 # TODO: Remove "trex" from lines which could work with other TGs.
112 # Use one instance of TrafficGenerator for all tests in test suite
113 ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
120 self._received = 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
133 :returns: Traffic generator node.
139 """Return number of lost packets.
141 :returns: Number of lost packets.
147 """Return number of sent packets.
149 :returns: Number of sent packets.
154 def get_received(self):
155 """Return number of received packets.
157 :returns: Number of received packets.
160 return self._received
162 def get_latency_int(self):
163 """Return rounded min/avg/max latency.
165 :returns: Latency stats.
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,
174 tg_if1_dst_mac=None, tg_if2_dst_mac=None):
175 """TG initialization.
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.
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
195 :type tg_if1_dst_mac: str
196 :type tg_if2_dst_mac: str
198 :raises RuntimeError: In case of issue during initialization.
200 if tg_node['type'] != NodeType.TG:
201 raise RuntimeError('Node type is not a TG')
204 if tg_node['subtype'] == NodeSubTypeTG.TREX:
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),
214 raise RuntimeError('TRex installation failed.')
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)
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,
227 if2_adj_addr = Topology().get_interface_mac(tg_if2_adj_node,
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,
234 if2_adj_addr = Topology().get_interface_ip4(tg_if2_adj_node,
237 raise ValueError("Unknown Test Type")
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
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
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"
255 " interfaces: [\"{0}\",\"{1}\"]\n"
257 " - dest_mac: [{2}]\n"
259 " - dest_mac: [{4}]\n"
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"
272 " interfaces: [\"{0}\",\"{1}\"]\n"
275 " default_gw: [{3}]\n"
277 " default_gw: [{5}]\n"
279 .format(if1_pci, if2_pci,
280 if1_addr, if1_adj_addr,
281 if2_addr, if2_adj_addr))
283 raise ValueError("Unknown Test Type")
285 raise RuntimeError('TRex config generation error')
287 for _ in range(0, 3):
288 # kill TRex only if it is already running
290 "sh -c 'pgrep t-rex && sudo pkill t-rex && sleep 3'")
293 (ret, _, _) = ssh.exec_command(
294 "sh -c 'cd {0}/scripts/ && sudo ./trex-cfg'"\
295 .format(Constants.TREX_INSTALL_DIR))
297 raise RuntimeError('trex-cfg failed')
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))
313 raise ValueError("Unknown Test Type")
315 ssh.exec_command("sh -c 'cat /tmp/trex.log'")
316 raise RuntimeError('t-rex-64 startup failed')
318 # get TRex server info
319 (ret, _, _) = ssh.exec_command(
321 "{0}/resources/tools/trex/trex_server_info.py'"\
322 .format(Constants.REMOTE_FW_DIR),
325 # If we get info TRex is running
327 # after max retries TRex is still not responding to API
328 # critical error occurred
329 raise RuntimeError('t-rex-64 startup failed')
332 def is_trex_running(node):
333 """Check if TRex is running using pidof.
335 :param node: Traffic generator node.
337 :returns: True if TRex is running otherwise False.
339 :raises RuntimeError: If node type is not a TG.
341 if node['type'] != NodeType.TG:
342 raise RuntimeError('Node type is not a TG')
346 ret, _, _ = ssh.exec_command_sudo("pidof t-rex")
347 return bool(int(ret) == 0)
350 def teardown_traffic_generator(node):
353 :param node: Traffic generator node.
356 :raises RuntimeError: If node type is not a TG,
357 or if TRex teardown fails.
359 if node['type'] != NodeType.TG:
360 raise RuntimeError('Node type is not a TG')
361 if node['subtype'] == NodeSubTypeTG.TREX:
364 (ret, _, _) = ssh.exec_command(
365 "sh -c 'sudo pkill t-rex && sleep 3'")
367 raise RuntimeError('pkill t-rex failed')
370 def trex_stl_stop_remote_exec(node):
371 """Execute script on remote node over ssh to stop running traffic.
373 :param node: TRex generator node.
376 :raises RuntimeError: If stop traffic script fails.
381 (ret, _, _) = ssh.exec_command(
382 "sh -c '{}/resources/tools/trex/"
383 "trex_stateless_stop.py'".format(Constants.REMOTE_FW_DIR))
386 raise RuntimeError('TRex stateless runtime error')
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.
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
404 :type traffic_type: str
405 :type async_call: bool
407 :type warmup_time: float
409 :raises RuntimeError: In case of TG driver issue.
412 ssh.connect(self._node)
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)
418 profile_path = ("{0}/resources/traffic_profiles/trex/"
419 "{1}.py".format(Constants.REMOTE_FW_DIR,
421 (ret, stdout, _) = ssh.exec_command(
423 "'{0}/resources/tools/trex/trex_stateless_profile.py "
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)
438 raise RuntimeError('TRex stateless runtime error')
441 self._received = None
446 # last line from console output
447 line = stdout.splitlines()[-1]
450 logger.info('TrafficGen result: {0}'.format(self._result))
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]
457 self._latency.append(self._result.split(', ')[4].split('=')[1])
458 self._latency.append(self._result.split(', ')[5].split('=')[1])
460 def stop_traffic_on_tg(self):
461 """Stop all traffic on TG.
464 :raises RuntimeError: If TG is not set.
466 if self._node is None:
467 raise RuntimeError("TG is not set")
468 if self._node['subtype'] == NodeSubTypeTG.TREX:
469 self.trex_stl_stop_remote_exec(self._node)
471 def send_traffic_on_tg(self, duration, rate, framesize,
472 traffic_type, warmup_time=5, async_call=False,
474 """Send traffic from all configured interfaces on TG.
476 :param duration: Duration of test traffic generation in seconds.
477 :param rate: Offered load per interface (e.g. 1%, 3gbps, 4mpps, ...).
478 :param framesize: Frame size (L2) in Bytes.
479 :param traffic_type: Module name as a traffic type identifier.
480 See resources/traffic_profiles/trex for implemented modules.
481 :param warmup_time: Warmup phase in seconds.
482 :param async_call: Async mode.
483 :param latency: With latency measurement.
487 :type traffic_type: str
488 :type warmup_time: float
489 :type async_call: bool
493 :raises RuntimeError: If TG is not set, or if node is not TG,
494 or if subtype is not specified.
495 :raises NotImplementedError: If TG is not supported.
500 raise RuntimeError("TG is not set")
502 if node['type'] != NodeType.TG:
503 raise RuntimeError('Node type is not a TG')
505 if node['subtype'] is None:
506 raise RuntimeError('TG subtype not defined')
507 elif node['subtype'] == NodeSubTypeTG.TREX:
508 self.trex_stl_start_remote_exec(duration, rate, framesize,
509 traffic_type, async_call, latency,
510 warmup_time=warmup_time)
512 raise NotImplementedError("TG subtype not supported")
516 def no_traffic_loss_occurred(self):
517 """Fail if loss occurred in traffic run.
520 :raises Exception: If loss occured.
522 if self._loss is None:
523 raise RuntimeError('The traffic generation has not been issued')
524 if self._loss != '0':
525 raise RuntimeError('Traffic loss occurred: {0}'.format(self._loss))
527 def fail_if_no_traffic_forwarded(self):
528 """Fail if no traffic forwarded.
531 :raises Exception: If no traffic forwarded.
533 if self._received is None:
534 raise RuntimeError('The traffic generation has not been issued')
535 if self._received == '0':
536 raise RuntimeError('No traffic forwarded')
538 def partial_traffic_loss_accepted(self, loss_acceptance,
539 loss_acceptance_type):
540 """Fail if loss is higher then accepted in traffic run.
542 :param loss_acceptance: Permitted drop ratio or frames count.
543 :param loss_acceptance_type: Type of permitted loss.
544 :type loss_acceptance: float
545 :type loss_acceptance_type: LossAcceptanceType
547 :raises Exception: If loss is above acceptance criteria.
549 if self._loss is None:
550 raise Exception('The traffic generation has not been issued')
552 if loss_acceptance_type == 'percentage':
553 loss = (float(self._loss) / float(self._sent)) * 100
554 elif loss_acceptance_type == 'frames':
555 loss = float(self._loss)
557 raise Exception('Loss acceptance type not supported')
559 if loss > float(loss_acceptance):
560 raise Exception("Traffic loss {} above loss acceptance: {}".format(
561 loss, loss_acceptance))
563 def set_rate_provider_defaults(self, frame_size, traffic_type,
565 """Store values accessed by measure().
567 :param frame_size: Frame size identifier or value [B].
568 :param traffic_type: Module name as a traffic type identifier.
569 See resources/traffic_profiles/trex for implemented modules.
570 :param warmup_time: Traffic duration before measurement starts [s].
571 :type frame_size: str or int
572 :type traffic_type: str
573 :type warmup_time: float
575 self.frame_size = frame_size
576 self.traffic_type = str(traffic_type)
577 self.warmup_time = float(warmup_time)
579 def measure(self, duration, transmit_rate):
580 """Run bi-directional measurement, parse and return results.
582 :param duration: Trial duration [s].
583 :param transmit_rate: Target bidirectional transmit rate [pps].
584 :type duration: float
585 :type transmit_rate: float
586 :returns: Structure containing the result of the measurement.
587 :rtype: ReceiveRateMeasurement
588 :raises RuntimeError: If TG is not set, or if node is not TG,
589 or if subtype is not specified.
590 :raises NotImplementedError: If TG is not supported.
592 duration = float(duration)
593 transmit_rate = float(transmit_rate)
594 # Trex needs target Tr per stream, but reports aggregate Tx and Dx.
595 unit_rate = str(transmit_rate / 2.0) + "pps"
596 self.send_traffic_on_tg(
597 duration, unit_rate, self.frame_size, self.traffic_type,
598 self.warmup_time, latency=True)
599 transmit_count = int(self.get_sent())
600 loss_count = int(self.get_loss())
601 measurement = ReceiveRateMeasurement(
602 duration, transmit_rate, transmit_count, loss_count)
603 measurement.latency = self.get_latency_int()
607 class OptimizedSearch(object):
608 """Class to be imported as Robot Library, containing a single keyword."""
611 def perform_optimized_ndrpdr_search(
612 frame_size, traffic_type, minimum_transmit_rate,
613 maximum_transmit_rate, packet_loss_ratio=0.005,
614 final_relative_width=0.005, final_trial_duration=30.0,
615 initial_trial_duration=1.0, number_of_intermediate_phases=2,
616 timeout=720.0, doublings=1):
617 """Setup initialized TG, perform optimized search, return intervals.
619 :param frame_size: Frame size identifier or value [B].
620 :param traffic_type: Module name as a traffic type identifier.
621 See resources/traffic_profiles/trex for implemented modules.
622 :param minimum_transmit_rate: Minimal bidirectional
623 target transmit rate [pps].
624 :param maximum_transmit_rate: Maximal bidirectional
625 target transmit rate [pps].
626 :param packet_loss_ratio: Fraction of packets lost, for PDR [1].
627 :param final_relative_width: Final lower bound transmit rate
628 cannot be more distant that this multiple of upper bound [1].
629 :param final_trial_duration: Trial duration for the final phase [s].
630 :param initial_trial_duration: Trial duration for the initial phase
631 and also for the first intermediate phase [s].
632 :param number_of_intermediate_phases: Number of intermediate phases
633 to perform before the final phase [1].
634 :param timeout: The search will fail itself when not finished
635 before this overall time [s].
636 :param doublings: How many doublings to do in external search step.
637 Default 1 is suitable for fairly stable tests,
638 less stable tests might get better overal duration with 2 or more.
639 :type frame_size: str or int
640 :type traffic_type: str
641 :type minimum_transmit_rate: float
642 :type maximum_transmit_rate: float
643 :type packet_loss_ratio: float
644 :type final_relative_width: float
645 :type final_trial_duration: float
646 :type initial_trial_duration: float
647 :type number_of_intermediate_phases: int
650 :returns: Structure containing narrowed down NDR and PDR intervals
651 and their measurements.
653 :raises RuntimeError: If total duration is larger than timeout.
655 # we need instance of TrafficGenerator instantiated by Robot Framework
656 # to be able to use trex_stl-*()
657 tg_instance = BuiltIn().get_library_instance(
658 'resources.libraries.python.TrafficGenerator')
659 tg_instance.set_rate_provider_defaults(frame_size, traffic_type)
660 algorithm = MultipleLossRatioSearch(
661 measurer=tg_instance, final_trial_duration=final_trial_duration,
662 final_relative_width=final_relative_width,
663 number_of_intermediate_phases=number_of_intermediate_phases,
664 initial_trial_duration=initial_trial_duration, timeout=timeout,
666 result = algorithm.narrow_down_ndr_and_pdr(
667 minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio)