HC Test: update routing test keyword due to namespace changes
[csit.git] / resources / libraries / python / TrafficGenerator.py
1 # Copyright (c) 2016 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 resources.libraries.python.constants import Constants
20 from resources.libraries.python.ssh import SSH
21 from resources.libraries.python.topology import NodeType
22 from resources.libraries.python.topology import NodeSubTypeTG
23 from resources.libraries.python.topology import Topology
24 from resources.libraries.python.DropRateSearch import DropRateSearch
25
26 __all__ = ['TrafficGenerator', 'TGDropRateSearchImpl']
27
28
29 class TGDropRateSearchImpl(DropRateSearch):
30     """Drop Rate Search implementation."""
31
32     def __init__(self):
33         super(TGDropRateSearchImpl, self).__init__()
34
35     def measure_loss(self, rate, frame_size, loss_acceptance,
36                      loss_acceptance_type, traffic_type):
37         """Runs the traffic and evaluate the measured results.
38
39         :param rate: Offered traffic load.
40         :param frame_size: Size of frame.
41         :param loss_acceptance: Permitted drop ratio or frames count.
42         :param loss_acceptance_type: Type of permitted loss.
43         :param traffic_type: Traffic profile ([2,3]-node-L[2,3], ...).
44         :type rate: int
45         :type frame_size: str
46         :type loss_acceptance: float
47         :type loss_acceptance_type: LossAcceptanceType
48         :type traffic_type: str
49         :returns: Drop threshold exceeded? (True/False)
50         :rtype: bool
51         :raises: NotImplementedError if TG is not supported.
52         :raises: RuntimeError if TG is not specified.
53         """
54         # we need instance of TrafficGenerator instantiated by Robot Framework
55         # to be able to use trex_stl-*()
56         tg_instance = BuiltIn().get_library_instance(
57             'resources.libraries.python.TrafficGenerator')
58
59         if tg_instance.node['subtype'] is None:
60             raise RuntimeError('TG subtype not defined')
61         elif tg_instance.node['subtype'] == NodeSubTypeTG.TREX:
62             unit_rate = str(rate) + self.get_rate_type_str()
63             tg_instance.trex_stl_start_remote_exec(self.get_duration(),
64                                                    unit_rate, frame_size,
65                                                    traffic_type)
66             loss = tg_instance.get_loss()
67             sent = tg_instance.get_sent()
68             if self.loss_acceptance_type_is_percentage():
69                 loss = (float(loss) / float(sent)) * 100
70
71             logger.trace("comparing: {} < {} {}".format(loss,
72                                                         loss_acceptance,
73                                                         loss_acceptance_type))
74             if float(loss) > float(loss_acceptance):
75                 return False
76             else:
77                 return True
78         else:
79             raise NotImplementedError("TG subtype not supported")
80
81     def get_latency(self):
82         """Returns min/avg/max latency.
83
84         :returns: Latency stats.
85         :rtype: list
86         """
87         tg_instance = BuiltIn().get_library_instance(
88             'resources.libraries.python.TrafficGenerator')
89         return tg_instance.get_latency_int()
90
91
92 class TrafficGenerator(object):
93     """Traffic Generator."""
94
95     # use one instance of TrafficGenerator for all tests in test suite
96     ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
97
98     def __init__(self):
99         self._result = None
100         self._loss = None
101         self._sent = None
102         self._latency = None
103         self._received = None
104         self._node = None
105         # T-REX interface order mapping
106         self._ifaces_reordered = 0
107
108     @property
109     def node(self):
110         """Getter.
111
112         :returns: Traffic generator node.
113         :rtype: dict
114         """
115         return self._node
116
117     def get_loss(self):
118         """Return number of lost packets.
119
120         :returns: Number of lost packets.
121         :rtype: str
122         """
123         return self._loss
124
125     def get_sent(self):
126         """Return number of sent packets.
127
128         :returns: Number of sent packets.
129         :rtype: str
130         """
131         return self._sent
132
133     def get_received(self):
134         """Return number of received packets.
135
136         :returns: Number of received packets.
137         :rtype: str
138         """
139         return self._received
140
141     def get_latency_int(self):
142         """Return rounded min/avg/max latency.
143
144         :returns: Latency stats.
145         :rtype: list
146         """
147         return self._latency
148
149     def initialize_traffic_generator(self, tg_node, tg_if1, tg_if2,
150                                      tg_if1_adj_node, tg_if1_adj_if,
151                                      tg_if2_adj_node, tg_if2_adj_if,
152                                      test_type,
153                                      tg_if1_dst_mac=None, tg_if2_dst_mac=None):
154         """TG initialization.
155
156         :param tg_node: Traffic generator node.
157         :param tg_if1: TG - name of first interface.
158         :param tg_if2: TG - name of second interface.
159         :param tg_if1_adj_node: TG if1 adjecent node.
160         :param tg_if1_adj_if: TG if1 adjecent interface.
161         :param tg_if2_adj_node: TG if2 adjecent node.
162         :param tg_if2_adj_if: TG if2 adjecent interface.
163         :param test_type: 'L2' or 'L3' - src/dst MAC address.
164         :param tg_if1_dst_mac: Interface 1 destination MAC address.
165         :param tg_if2_dst_mac: Interface 2 destination MAC address.
166         :type tg_node: dict
167         :type tg_if1: str
168         :type tg_if2: str
169         :type tg_if1_adj_node: dict
170         :type tg_if1_adj_if: str
171         :type tg_if2_adj_node: dict
172         :type tg_if2_adj_if: str
173         :type test_type: str
174         :type tg_if1_dst_mac: str
175         :type tg_if2_dst_mac: str
176         :returns: nothing
177         :raises: RuntimeError in case of issue during initialization.
178         """
179
180         topo = Topology()
181
182         if tg_node['type'] != NodeType.TG:
183             raise RuntimeError('Node type is not a TG')
184         self._node = tg_node
185
186         if tg_node['subtype'] == NodeSubTypeTG.TREX:
187             trex_path = "/opt/trex-core-2.22"
188
189             ssh = SSH()
190             ssh.connect(tg_node)
191
192             (ret, stdout, stderr) = ssh.exec_command(
193                 "sudo -E sh -c '{}/resources/tools/t-rex/"
194                 "t-rex-installer.sh'".format(Constants.REMOTE_FW_DIR),
195                 timeout=1800)
196             if int(ret) != 0:
197                 logger.error('trex installation failed: {0}'.format(
198                     stdout + stderr))
199                 raise RuntimeError('Installation of TG failed')
200
201             if1_pci = topo.get_interface_pci_addr(tg_node, tg_if1)
202             if2_pci = topo.get_interface_pci_addr(tg_node, tg_if2)
203             if1_mac = topo.get_interface_mac(tg_node, tg_if1)
204             if2_mac = topo.get_interface_mac(tg_node, tg_if2)
205
206             if test_type == 'L2':
207                 if1_adj_mac = if2_mac
208                 if2_adj_mac = if1_mac
209             elif test_type == 'L3':
210                 if1_adj_mac = topo.get_interface_mac(tg_if1_adj_node,
211                                                      tg_if1_adj_if)
212                 if2_adj_mac = topo.get_interface_mac(tg_if2_adj_node,
213                                                      tg_if2_adj_if)
214             else:
215                 raise ValueError("test_type unknown")
216
217             if tg_if1_dst_mac is not None and tg_if2_dst_mac is not None:
218                 if1_adj_mac = tg_if1_dst_mac
219                 if2_adj_mac = tg_if2_dst_mac
220
221             if min(if1_pci, if2_pci) != if1_pci:
222                 if1_mac, if2_mac = if2_mac, if1_mac
223                 if1_pci, if2_pci = if2_pci, if1_pci
224                 if1_adj_mac, if2_adj_mac = if2_adj_mac, if1_adj_mac
225                 self._ifaces_reordered = 1
226
227             if1_mac_hex = "0x"+if1_mac.replace(":", ",0x")
228             if2_mac_hex = "0x"+if2_mac.replace(":", ",0x")
229             if1_adj_mac_hex = "0x"+if1_adj_mac.replace(":", ",0x")
230             if2_adj_mac_hex = "0x"+if2_adj_mac.replace(":", ",0x")
231
232             (ret, stdout, stderr) = ssh.exec_command(
233                 "sudo sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
234                 "- port_limit      : 2\n"
235                 "  version         : 2\n"
236                 "  interfaces      : [\"{}\",\"{}\"]\n"
237                 "  port_info       :\n"
238                 "          - dest_mac        :   [{}]\n"
239                 "            src_mac         :   [{}]\n"
240                 "          - dest_mac        :   [{}]\n"
241                 "            src_mac         :   [{}]\n"
242                 "EOF'"\
243                 .format(if1_pci, if2_pci,
244                         if1_adj_mac_hex, if1_mac_hex,
245                         if2_adj_mac_hex, if2_mac_hex))
246             if int(ret) != 0:
247                 logger.error("failed to create t-rex config: {}"\
248                 .format(stdout + stderr))
249                 raise RuntimeError('trex config generation error')
250
251             max_startup_retries = 3
252             while max_startup_retries > 0:
253                 # kill T-rex only if it is already running
254                 (ret, _, _) = ssh.exec_command(
255                     "sh -c 'pgrep t-rex && sudo pkill t-rex && sleep 3'")
256
257                 # configure T-rex
258                 (ret, stdout, stderr) = ssh.exec_command(
259                     "sh -c 'cd {0}/scripts/ && sudo ./trex-cfg'"\
260                     .format(trex_path))
261                 if int(ret) != 0:
262                     logger.error('trex-cfg failed: {0}'.format(stdout + stderr))
263                     raise RuntimeError('trex-cfg failed')
264
265                 # start T-rex
266                 (ret, _, _) = ssh.exec_command(
267                     "sh -c 'cd {0}/scripts/ && "
268                     "sudo nohup ./t-rex-64 -i -c 7 --iom 0 > /dev/null 2>&1 &'"
269                     "> /dev/null"\
270                     .format(trex_path))
271                 if int(ret) != 0:
272                     raise RuntimeError('t-rex-64 startup failed')
273
274                 # get T-rex server info
275                 (ret, _, _) = ssh.exec_command(
276                     "sh -c 'sleep 3; "
277                     "{0}/resources/tools/t-rex/t-rex-server-info.py'"\
278                     .format(Constants.REMOTE_FW_DIR),
279                     timeout=120)
280                 if int(ret) == 0:
281                     # If we get info T-rex is running
282                     return
283                 # try again
284                 max_startup_retries -= 1
285             # after max retries T-rex is still not responding to API
286             # critical error occured
287             raise RuntimeError('t-rex-64 startup failed')
288
289     @staticmethod
290     def teardown_traffic_generator(node):
291         """TG teardown.
292
293         :param node: Traffic generator node.
294         :type node: dict
295         :returns: nothing
296         :raises: RuntimeError if T-rex teardown failed.
297         :raises: RuntimeError if node type is not a TG.
298         """
299         if node['type'] != NodeType.TG:
300             raise RuntimeError('Node type is not a TG')
301         if node['subtype'] == NodeSubTypeTG.TREX:
302             ssh = SSH()
303             ssh.connect(node)
304             (ret, stdout, stderr) = ssh.exec_command(
305                 "sh -c 'sudo pkill t-rex && sleep 3'")
306             if int(ret) != 0:
307                 logger.error('pkill t-rex failed: {0}'.format(stdout + stderr))
308                 raise RuntimeError('pkill t-rex failed')
309
310     @staticmethod
311     def trex_stl_stop_remote_exec(node):
312         """Execute script on remote node over ssh to stop running traffic.
313
314         :param node: T-REX generator node.
315         :type node: dict
316         :returns: Nothing
317         :raises: RuntimeError if stop traffic script fails.
318         """
319         ssh = SSH()
320         ssh.connect(node)
321
322         (ret, stdout, stderr) = ssh.exec_command(
323             "sh -c '{}/resources/tools/t-rex/"
324             "t-rex-stateless-stop.py'".format(Constants.REMOTE_FW_DIR))
325         logger.trace(ret)
326         logger.trace(stdout)
327         logger.trace(stderr)
328
329         if int(ret) != 0:
330             raise RuntimeError('T-rex stateless runtime error')
331
332     def trex_stl_start_remote_exec(self, duration, rate, framesize,
333                                    traffic_type, async_call=False,
334                                    latency=True, warmup_time=5):
335         """Execute script on remote node over ssh to start traffic.
336
337         :param duration: Time expresed in seconds for how long to send traffic.
338         :param rate: Traffic rate expressed with units (pps, %)
339         :param framesize: L2 frame size to send (without padding and IPG).
340         :param traffic_type: Traffic profile.
341         :param async_call: If enabled then don't wait for all incomming trafic.
342         :param latency: With latency measurement.
343         :param warmup_time: Warmup time period.
344         :type duration: int
345         :type rate: str
346         :type framesize: int
347         :type traffic_type: str
348         :type async_call: bool
349         :type latency: bool
350         :type warmup_time: int
351         :returns: Nothing
352         :raises: NotImplementedError if traffic type is not supported.
353         :raises: RuntimeError in case of TG driver issue.
354         """
355         ssh = SSH()
356         ssh.connect(self._node)
357
358         _p0 = 1
359         _p1 = 2
360         _async = "--async" if async_call else ""
361         _latency = "--latency" if latency else ""
362
363         if self._ifaces_reordered != 0:
364             _p0, _p1 = _p1, _p0
365
366         if traffic_type in ["3-node-xconnect", "3-node-bridge"]:
367             (ret, stdout, stderr) = ssh.exec_command(
368                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
369                 "--duration={1} -r {2} -s {3} "
370                 "--p{4}_src_start_ip 10.10.10.1 "
371                 "--p{4}_src_end_ip 10.10.10.254 "
372                 "--p{4}_dst_start_ip 20.20.20.1 "
373                 "--p{5}_src_start_ip 20.20.20.1 "
374                 "--p{5}_src_end_ip 20.20.20.254 "
375                 "--p{5}_dst_start_ip 10.10.10.1 "
376                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
377                                                     duration, rate, framesize,
378                                                     _p0, _p1, _async, _latency,
379                                                     warmup_time),
380                 timeout=int(duration)+60)
381         elif traffic_type in ["3-node-IPv4"]:
382             (ret, stdout, stderr) = ssh.exec_command(
383                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
384                 "--duration={1} -r {2} -s {3} "
385                 "--p{4}_src_start_ip 10.10.10.2 "
386                 "--p{4}_src_end_ip 10.10.10.254 "
387                 "--p{4}_dst_start_ip 20.20.20.2 "
388                 "--p{5}_src_start_ip 20.20.20.2 "
389                 "--p{5}_src_end_ip 20.20.20.254 "
390                 "--p{5}_dst_start_ip 10.10.10.2 "
391                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
392                                                     duration, rate, framesize,
393                                                     _p0, _p1, _async, _latency,
394                                                     warmup_time),
395                 timeout=int(duration)+60)
396         elif traffic_type in ["3-node-IPv4-dst-1"]:
397             (ret, stdout, stderr) = ssh.exec_command(
398                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
399                 "--duration={1} -r {2} -s {3} "
400                 "--p{4}_src_start_ip 10.0.0.1 "
401                 "--p{4}_dst_start_ip 20.0.0.0 "
402                 "--p{4}_dst_end_ip 20.0.0.0 "
403                 "--p{5}_src_start_ip 20.0.0.1 "
404                 "--p{5}_dst_start_ip 10.0.0.0 "
405                 "--p{5}_dst_end_ip 10.0.0.0 "
406                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
407                                                     duration, rate, framesize,
408                                                     _p0, _p1, _async, _latency,
409                                                     warmup_time),
410                 timeout=int(duration)+60)
411         elif traffic_type in ["3-node-IPv4-dst-100"]:
412             (ret, stdout, stderr) = ssh.exec_command(
413                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
414                 "--duration={1} -r {2} -s {3} "
415                 "--p{4}_src_start_ip 10.0.0.1 "
416                 "--p{4}_dst_start_ip 20.0.0.0 "
417                 "--p{4}_dst_end_ip 20.0.0.99 "
418                 "--p{5}_src_start_ip 20.0.0.1 "
419                 "--p{5}_dst_start_ip 10.0.0.0 "
420                 "--p{5}_dst_end_ip 10.0.0.99 "
421                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
422                                                     duration, rate, framesize,
423                                                     _p0, _p1, _async, _latency,
424                                                     warmup_time),
425                 timeout=int(duration)+60)
426         elif traffic_type in ["3-node-IPv4-dst-1000"]:
427             (ret, stdout, stderr) = ssh.exec_command(
428                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
429                 "--duration={1} -r {2} -s {3} "
430                 "--p{4}_src_start_ip 10.0.0.1 "
431                 "--p{4}_dst_start_ip 20.0.0.0 "
432                 "--p{4}_dst_end_ip 20.0.3.231 "
433                 "--p{5}_src_start_ip 20.0.0.1 "
434                 "--p{5}_dst_start_ip 10.0.0.0 "
435                 "--p{5}_dst_end_ip 10.0.3.231 "
436                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
437                                                     duration, rate, framesize,
438                                                     _p0, _p1, _async, _latency,
439                                                     warmup_time),
440                 timeout=int(duration)+60)
441
442         elif traffic_type in ["3-node-IPv4-SNAT-1u-1p"]:
443             (ret, stdout, stderr) = ssh.exec_command(
444                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
445                 "--duration={1} -r {2} -s {3} "
446                 "--p{4}_src_start_ip 20.0.0.0 "
447                 "--p{4}_src_end_ip 20.0.0.0 "
448                 "--p{4}_dst_start_ip 12.0.0.2 "
449                 "--p{5}_src_start_ip 12.0.0.2 "
450                 "--p{5}_src_end_ip 12.0.0.2 "
451                 "--p{5}_dst_start_ip 200.0.0.0 "
452                 "--p{4}_src_start_udp_port 1024 "
453                 "--p{4}_src_end_udp_port 1024 "
454                 "--p{4}_dst_start_udp_port 1024 "
455                 "--p{5}_src_start_udp_port 1024 "
456                 "--p{5}_dst_start_udp_port 1028 "
457                 "--p{5}_dst_end_udp_port 1028 "
458                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
459                                                     duration, rate, framesize,
460                                                     _p0, _p1, _async, _latency,
461                                                     warmup_time),
462                 timeout=int(duration)+60)
463
464         elif traffic_type in ["3-node-IPv4-SNAT-1u-15p"]:
465             (ret, stdout, stderr) = ssh.exec_command(
466                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
467                 "--duration={1} -r {2} -s {3} "
468                 "--p{4}_src_start_ip 20.0.0.0 "
469                 "--p{4}_src_end_ip 20.0.0.0 "
470                 "--p{4}_dst_start_ip 12.0.0.2 "
471                 "--p{5}_src_start_ip 12.0.0.2 "
472                 "--p{5}_src_end_ip 12.0.0.2 "
473                 "--p{5}_dst_start_ip 200.0.0.0 "
474                 "--p{4}_src_start_udp_port 1024 "
475                 "--p{4}_src_end_udp_port 1038 "
476                 "--p{4}_dst_start_udp_port 1024 "
477                 "--p{5}_src_start_udp_port 1024 "
478                 "--p{5}_dst_start_udp_port 1024 "
479                 "--p{5}_dst_end_udp_port 1038 "
480                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
481                                                     duration, rate, framesize,
482                                                     _p0, _p1, _async, _latency,
483                                                     warmup_time),
484                 timeout=int(duration)+60)
485
486         elif traffic_type in ["3-node-IPv4-SNAT-10u-15p"]:
487             (ret, stdout, stderr) = ssh.exec_command(
488                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
489                 "--duration={1} -r {2} -s {3} "
490                 "--p{4}_src_start_ip 20.0.0.0 "
491                 "--p{4}_src_end_ip 20.0.0.9 "
492                 "--p{4}_dst_start_ip 12.0.0.2 "
493                 "--p{5}_src_start_ip 12.0.0.2 "
494                 "--p{5}_src_end_ip 12.0.0.2 "
495                 "--p{5}_dst_start_ip 200.0.0.0 "
496                 "--p{4}_src_start_udp_port 1024 "
497                 "--p{4}_src_end_udp_port 1038 "
498                 "--p{4}_dst_start_udp_port 1024 "
499                 "--p{5}_src_start_udp_port 1024 "
500                 "--p{5}_dst_start_udp_port 1024 "
501                 "--p{5}_dst_end_udp_port 1173 "
502                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
503                                                     duration, rate, framesize,
504                                                     _p0, _p1, _async, _latency,
505                                                     warmup_time),
506                 timeout=int(duration)+60)
507
508         elif traffic_type in ["3-node-IPv4-SNAT-100u-15p"]:
509             (ret, stdout, stderr) = ssh.exec_command(
510                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
511                 "--duration={1} -r {2} -s {3} "
512                 "--p{4}_src_start_ip 20.0.0.0 "
513                 "--p{4}_src_end_ip 20.0.0.99 "
514                 "--p{4}_dst_start_ip 12.0.0.2 "
515                 "--p{5}_src_start_ip 12.0.0.2 "
516                 "--p{5}_src_end_ip 12.0.0.2 "
517                 "--p{5}_dst_start_ip 200.0.0.0 "
518                 "--p{4}_src_start_udp_port 1024 "
519                 "--p{4}_src_end_udp_port 1038 "
520                 "--p{4}_dst_start_udp_port 1024 "
521                 "--p{5}_src_start_udp_port 1024 "
522                 "--p{5}_dst_start_udp_port 1024 "
523                 "--p{5}_dst_end_udp_port 2523 "
524                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
525                                                     duration, rate, framesize,
526                                                     _p0, _p1, _async, _latency,
527                                                     warmup_time),
528                 timeout=int(duration) + 60)
529
530         elif traffic_type in ["3-node-IPv4-SNAT-1000u-15p"]:
531             (ret, stdout, stderr) = ssh.exec_command(
532                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
533                 "--duration={1} -r {2} -s {3} "
534                 "--p{4}_src_start_ip 20.0.0.0 "
535                 "--p{4}_src_end_ip 20.0.3.231 "
536                 "--p{4}_dst_start_ip 12.0.0.2 "
537                 "--p{5}_src_start_ip 12.0.0.2 "
538                 "--p{5}_src_end_ip 12.0.0.2 "
539                 "--p{5}_dst_start_ip 200.0.0.0 "
540                 "--p{4}_src_start_udp_port 1024 "
541                 "--p{4}_src_end_udp_port 1038 "
542                 "--p{4}_dst_start_udp_port 1024 "
543                 "--p{5}_src_start_udp_port 1024 "
544                 "--p{5}_dst_start_udp_port 1024 "
545                 "--p{5}_dst_end_udp_port 16023 "
546                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
547                                                     duration, rate, framesize,
548                                                     _p0, _p1, _async, _latency,
549                                                     warmup_time),
550                 timeout=int(duration)+60)
551
552         elif traffic_type in ["3-node-IPv4-SNAT-2000u-15p"]:
553             (ret, stdout, stderr) = ssh.exec_command(
554                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
555                 "--duration={1} -r {2} -s {3} "
556                 "--p{4}_src_start_ip 20.0.0.0 "
557                 "--p{4}_src_end_ip 20.0.7.207 "
558                 "--p{4}_dst_start_ip 12.0.0.2 "
559                 "--p{5}_src_start_ip 12.0.0.2 "
560                 "--p{5}_src_end_ip 12.0.0.2 "
561                 "--p{5}_dst_start_ip 200.0.0.0 "
562                 "--p{4}_src_start_udp_port 1024 "
563                 "--p{4}_src_end_udp_port 1038 "
564                 "--p{4}_dst_start_udp_port 1024 "
565                 "--p{5}_src_start_udp_port 1024 "
566                 "--p{5}_dst_start_udp_port 1024 "
567                 "--p{5}_dst_end_udp_port 31022 "
568                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
569                                                     duration, rate, framesize,
570                                                     _p0, _p1, _async, _latency,
571                                                     warmup_time),
572                 timeout=int(duration)+60)
573
574         elif traffic_type in ["3-node-IPv4-SNAT-4000u-15p"]:
575             (ret, stdout, stderr) = ssh.exec_command(
576                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
577                 "--duration={1} -r {2} -s {3} "
578                 "--p{4}_src_start_ip 20.0.0.0 "
579                 "--p{4}_src_end_ip 20.0.15.159 "
580                 "--p{4}_dst_start_ip 12.0.0.2 "
581                 "--p{5}_src_start_ip 12.0.0.2 "
582                 "--p{5}_src_end_ip 12.0.0.2 "
583                 "--p{5}_dst_start_ip 200.0.0.0 "
584                 "--p{4}_src_start_udp_port 1024 "
585                 "--p{4}_src_end_udp_port 1038 "
586                 "--p{4}_dst_start_udp_port 1024 "
587                 "--p{5}_src_start_udp_port 1024 "
588                 "--p{5}_dst_start_udp_port 1024 "
589                 "--p{5}_dst_end_udp_port 61022 "
590                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
591                                                     duration, rate, framesize,
592                                                     _p0, _p1, _async, _latency,
593                                                     warmup_time),
594                 timeout=int(duration)+60)
595
596         elif traffic_type in ["3-node-IPv4-dst-10000"]:
597             (ret, stdout, stderr) = ssh.exec_command(
598                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
599                 "--duration={1} -r {2} -s {3} "
600                 "--p{4}_src_start_ip 10.0.0.1 "
601                 "--p{4}_dst_start_ip 20.0.0.0 "
602                 "--p{4}_dst_end_ip 20.0.39.15 "
603                 "--p{5}_src_start_ip 20.0.0.1 "
604                 "--p{5}_dst_start_ip 10.0.0.0 "
605                 "--p{5}_dst_end_ip 10.0.39.15 "
606                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
607                                                     duration, rate, framesize,
608                                                     _p0, _p1, _async, _latency,
609                                                     warmup_time),
610                 timeout=int(duration)+60)
611         elif traffic_type in ["3-node-IPv4-dst-100000"]:
612             (ret, stdout, stderr) = ssh.exec_command(
613                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
614                 "--duration={1} -r {2} -s {3} "
615                 "--p{4}_src_start_ip 10.0.0.1 "
616                 "--p{4}_dst_start_ip 20.0.0.0 "
617                 "--p{4}_dst_end_ip 20.1.134.159 "
618                 "--p{5}_src_start_ip 20.0.0.1 "
619                 "--p{5}_dst_start_ip 10.0.0.0 "
620                 "--p{5}_dst_end_ip 10.1.134.159 "
621                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
622                                                     duration, rate, framesize,
623                                                     _p0, _p1, _async, _latency,
624                                                     warmup_time),
625                 timeout=int(duration)+60)
626         elif traffic_type in ["3-node-IPv4-dst-1000000"]:
627             (ret, stdout, stderr) = ssh.exec_command(
628                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
629                 "--duration={1} -r {2} -s {3} "
630                 "--p{4}_src_start_ip 10.0.0.1 "
631                 "--p{4}_dst_start_ip 20.0.0.0 "
632                 "--p{4}_dst_end_ip 20.15.66.63 "
633                 "--p{5}_src_start_ip 20.0.0.1 "
634                 "--p{5}_dst_start_ip 10.0.0.0 "
635                 "--p{5}_dst_end_ip 10.15.66.63 "
636                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
637                                                     duration, rate, framesize,
638                                                     _p0, _p1, _async, _latency,
639                                                     warmup_time),
640                 timeout=int(duration)+60)
641         elif traffic_type in ["3-node-IPv6"]:
642             (ret, stdout, stderr) = ssh.exec_command(
643                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
644                 "--duration={1} -r {2} -s {3} -6 "
645                 "--p{4}_src_start_ip 2001:1::2 "
646                 "--p{4}_src_end_ip 2001:1::FE "
647                 "--p{4}_dst_start_ip 2001:2::2 "
648                 "--p{5}_src_start_ip 2001:2::2 "
649                 "--p{5}_src_end_ip 2001:2::FE "
650                 "--p{5}_dst_start_ip 2001:1::2 "
651                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
652                                                     duration, rate, framesize,
653                                                     _p0, _p1, _async, _latency,
654                                                     warmup_time),
655                 timeout=int(duration)+60)
656         elif traffic_type in ["3-node-IPv6-dst-10000"]:
657             (ret, stdout, stderr) = ssh.exec_command(
658                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
659                 "--duration={1} -r {2} -s {3} -6 "
660                 "--p{4}_src_start_ip 2001:1::1 "
661                 "--p{4}_dst_start_ip 2001:2::0 "
662                 "--p{4}_dst_end_ip 2001:2::270F "
663                 "--p{5}_src_start_ip 2001:2::1 "
664                 "--p{5}_dst_start_ip 2001:1::0 "
665                 "--p{5}_dst_end_ip 2001:1::270F "
666                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
667                                                     duration, rate, framesize,
668                                                     _p0, _p1, _async, _latency,
669                                                     warmup_time),
670                 timeout=int(duration)+60)
671         elif traffic_type in ["3-node-IPv6-dst-100000"]:
672             (ret, stdout, stderr) = ssh.exec_command(
673                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
674                 "--duration={1} -r {2} -s {3} -6 "
675                 "--p{4}_src_start_ip 2001:1::1 "
676                 "--p{4}_dst_start_ip 2001:2::0 "
677                 "--p{4}_dst_end_ip 2001:2::1:869F "
678                 "--p{5}_src_start_ip 2001:2::1 "
679                 "--p{5}_dst_start_ip 2001:1::0 "
680                 "--p{5}_dst_end_ip 2001:1::1:869F "
681                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
682                                                     duration, rate, framesize,
683                                                     _p0, _p1, _async, _latency,
684                                                     warmup_time),
685                 timeout=int(duration)+60)
686         elif traffic_type in ["3-node-IPv6-dst-1000000"]:
687             (ret, stdout, stderr) = ssh.exec_command(
688                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
689                 "--duration={1} -r {2} -s {3} -6 "
690                 "--p{4}_src_start_ip 2001:1::1 "
691                 "--p{4}_dst_start_ip 2001:2::0 "
692                 "--p{4}_dst_end_ip 2001:2::F:423F "
693                 "--p{5}_src_start_ip 2001:2::1 "
694                 "--p{5}_dst_start_ip 2001:1::0 "
695                 "--p{5}_dst_end_ip 2001:1::F:423F "
696                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
697                                                     duration, rate, framesize,
698                                                     _p0, _p1, _async, _latency,
699                                                     warmup_time),
700                 timeout=int(duration)+60)
701         elif traffic_type in ["2-node-bridge"]:
702             (ret, stdout, stderr) = ssh.exec_command(
703                 "sh -c '{0}/resources/tools/t-rex/t-rex-stateless.py "
704                 "--duration={1} -r {2} -s {3} "
705                 "--p{4}_src_start_ip 10.10.10.2 "
706                 "--p{4}_src_end_ip 10.10.10.254 "
707                 "--p{4}_dst_start_ip 20.20.20.2 "
708                 "--p{5}_src_start_ip 20.20.20.2 "
709                 "--p{5}_src_end_ip 20.20.20.254 "
710                 "--p{5}_dst_start_ip 10.10.10.2 "
711                 "{6} {7} --warmup_time={8}'".format(Constants.REMOTE_FW_DIR,
712                                                     duration, rate, framesize,
713                                                     _p0, _p1, _async, _latency,
714                                                     warmup_time),
715                 timeout = int(duration) + 60)
716         else:
717             raise NotImplementedError('Unsupported traffic type')
718
719         logger.trace(ret)
720         logger.trace(stdout)
721         logger.trace(stderr)
722
723         if int(ret) != 0:
724             raise RuntimeError('T-rex stateless runtime error')
725         elif async_call:
726             #no result
727             self._received = None
728             self._sent = None
729             self._loss = None
730             self._latency = None
731         else:
732             # last line from console output
733             line = stdout.splitlines()[-1]
734
735             self._result = line
736             logger.info('TrafficGen result: {0}'.format(self._result))
737
738             self._received = self._result.split(', ')[1].split('=')[1]
739             self._sent = self._result.split(', ')[2].split('=')[1]
740             self._loss = self._result.split(', ')[3].split('=')[1]
741
742             self._latency = []
743             self._latency.append(self._result.split(', ')[4].split('=')[1])
744             self._latency.append(self._result.split(', ')[5].split('=')[1])
745
746     def stop_traffic_on_tg(self):
747         """Stop all traffic on TG.
748
749         :returns: Nothing
750         :raises: RuntimeError if TG is not set.
751         """
752         if self._node is None:
753             raise RuntimeError("TG is not set")
754         if self._node['subtype'] == NodeSubTypeTG.TREX:
755             self.trex_stl_stop_remote_exec(self._node)
756
757     def send_traffic_on_tg(self, duration, rate, framesize,
758                            traffic_type, warmup_time=5, async_call=False,
759                            latency=True):
760         """Send traffic from all configured interfaces on TG.
761
762         :param duration: Duration of test traffic generation in seconds.
763         :param rate: Offered load per interface (e.g. 1%, 3gbps, 4mpps, ...).
764         :param framesize: Frame size (L2) in Bytes.
765         :param traffic_type: Traffic profile.
766         :param warmup_time: Warmup phase in seconds.
767         :param async_call: Async mode.
768         :param latency: With latency measurement.
769         :type duration: str
770         :type rate: str
771         :type framesize: str
772         :type traffic_type: str
773         :type warmup_time: int
774         :type async_call: bool
775         :type latency: bool
776         :returns: TG output.
777         :rtype: str
778         :raises: RuntimeError if TG is not set.
779         :raises: RuntimeError if node is not TG or subtype is not specified.
780         :raises: NotImplementedError if TG is not supported.
781         """
782
783         node = self._node
784         if node is None:
785             raise RuntimeError("TG is not set")
786
787         if node['type'] != NodeType.TG:
788             raise RuntimeError('Node type is not a TG')
789
790         if node['subtype'] is None:
791             raise RuntimeError('TG subtype not defined')
792         elif node['subtype'] == NodeSubTypeTG.TREX:
793             self.trex_stl_start_remote_exec(duration, rate, framesize,
794                                             traffic_type, async_call, latency,
795                                             warmup_time=warmup_time)
796         else:
797             raise NotImplementedError("TG subtype not supported")
798
799         return self._result
800
801     def no_traffic_loss_occurred(self):
802         """Fail if loss occurred in traffic run.
803
804         :returns: nothing
805         :raises: Exception if loss occured.
806         """
807         if self._loss is None:
808             raise Exception('The traffic generation has not been issued')
809         if self._loss != '0':
810             raise Exception('Traffic loss occurred: {0}'.format(self._loss))
811
812     def partial_traffic_loss_accepted(self, loss_acceptance,
813                                       loss_acceptance_type):
814         """Fail if loss is higher then accepted in traffic run.
815
816         :param loss_acceptance: Permitted drop ratio or frames count.
817         :param loss_acceptance_type: Type of permitted loss.
818         :type loss_acceptance: float
819         :type loss_acceptance_type: LossAcceptanceType
820         :returns: nothing
821         :raises: Exception if loss is above acceptance criteria.
822         """
823         if self._loss is None:
824             raise Exception('The traffic generation has not been issued')
825
826         if loss_acceptance_type == 'percentage':
827             loss = (float(self._loss) / float(self._sent)) * 100
828         elif loss_acceptance_type == 'frames':
829             loss = float(self._loss)
830         else:
831             raise Exception('Loss acceptance type not supported')
832
833         if loss > float(loss_acceptance):
834             raise Exception("Traffic loss {} above loss acceptance: {}".format(
835                 loss, loss_acceptance))