Upgrade to T-rex v2.34
[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 = False
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.34"
188
189             ssh = SSH()
190             ssh.connect(tg_node)
191
192             (ret, _, _) = ssh.exec_command(
193                 "sudo -E sh -c '{}/resources/tools/trex/"
194                 "trex_installer.sh'".format(Constants.REMOTE_FW_DIR),
195                 timeout=1800)
196             if int(ret) != 0:
197                 raise RuntimeError('TRex installation failed.')
198
199             if1_pci = topo.get_interface_pci_addr(tg_node, tg_if1)
200             if2_pci = topo.get_interface_pci_addr(tg_node, tg_if2)
201             if1_mac = topo.get_interface_mac(tg_node, tg_if1)
202             if2_mac = topo.get_interface_mac(tg_node, tg_if2)
203
204             if test_type == 'L2':
205                 if1_adj_mac = if2_mac
206                 if2_adj_mac = if1_mac
207             elif test_type == 'L3':
208                 if1_adj_mac = topo.get_interface_mac(tg_if1_adj_node,
209                                                      tg_if1_adj_if)
210                 if2_adj_mac = topo.get_interface_mac(tg_if2_adj_node,
211                                                      tg_if2_adj_if)
212             else:
213                 raise ValueError("test_type unknown")
214
215             if tg_if1_dst_mac is not None and tg_if2_dst_mac is not None:
216                 if1_adj_mac = tg_if1_dst_mac
217                 if2_adj_mac = tg_if2_dst_mac
218
219             if min(if1_pci, if2_pci) != if1_pci:
220                 if1_mac, if2_mac = if2_mac, if1_mac
221                 if1_pci, if2_pci = if2_pci, if1_pci
222                 if1_adj_mac, if2_adj_mac = if2_adj_mac, if1_adj_mac
223                 self._ifaces_reordered = True
224
225             if1_mac_hex = "0x"+if1_mac.replace(":", ",0x")
226             if2_mac_hex = "0x"+if2_mac.replace(":", ",0x")
227             if1_adj_mac_hex = "0x"+if1_adj_mac.replace(":", ",0x")
228             if2_adj_mac_hex = "0x"+if2_adj_mac.replace(":", ",0x")
229
230             (ret, _, _) = ssh.exec_command(
231                 "sudo sh -c 'cat << EOF > /etc/trex_cfg.yaml\n"
232                 "- port_limit      : 2\n"
233                 "  version         : 2\n"
234                 "  interfaces      : [\"{}\",\"{}\"]\n"
235                 "  port_info       :\n"
236                 "          - dest_mac        :   [{}]\n"
237                 "            src_mac         :   [{}]\n"
238                 "          - dest_mac        :   [{}]\n"
239                 "            src_mac         :   [{}]\n"
240                 "EOF'"\
241                 .format(if1_pci, if2_pci,
242                         if1_adj_mac_hex, if1_mac_hex,
243                         if2_adj_mac_hex, if2_mac_hex))
244             if int(ret) != 0:
245                 raise RuntimeError('trex config generation error')
246
247             max_startup_retries = 3
248             while max_startup_retries > 0:
249                 # kill T-rex only if it is already running
250                 (ret, _, _) = ssh.exec_command(
251                     "sh -c 'pgrep t-rex && sudo pkill t-rex && sleep 3'")
252
253                 # configure T-rex
254                 (ret, _, _) = ssh.exec_command(
255                     "sh -c 'cd {0}/scripts/ && sudo ./trex-cfg'"\
256                     .format(trex_path))
257                 if int(ret) != 0:
258                     raise RuntimeError('trex-cfg failed')
259
260                 # start T-rex
261                 (ret, _, _) = ssh.exec_command(
262                     "sh -c 'cd {0}/scripts/ && "
263                     "sudo nohup ./t-rex-64 -i -c 7 --iom 0 > /tmp/trex.log "
264                     "2>&1 &' > /dev/null"\
265                     .format(trex_path))
266                 if int(ret) != 0:
267                     ssh.exec_command("sh -c 'cat /tmp/trex.log'")
268                     raise RuntimeError('t-rex-64 startup failed')
269
270                 # get T-rex server info
271                 (ret, _, _) = ssh.exec_command(
272                     "sh -c 'sleep 3; "
273                     "{0}/resources/tools/trex/trex_server_info.py'"\
274                     .format(Constants.REMOTE_FW_DIR),
275                     timeout=120)
276                 if int(ret) == 0:
277                     # If we get info T-rex is running
278                     return
279                 # try again
280                 max_startup_retries -= 1
281             # after max retries T-rex is still not responding to API
282             # critical error occurred
283             raise RuntimeError('t-rex-64 startup failed')
284
285     @staticmethod
286     def teardown_traffic_generator(node):
287         """TG teardown.
288
289         :param node: Traffic generator node.
290         :type node: dict
291         :returns: nothing
292         :raises: RuntimeError if T-rex teardown failed.
293         :raises: RuntimeError if node type is not a TG.
294         """
295         if node['type'] != NodeType.TG:
296             raise RuntimeError('Node type is not a TG')
297         if node['subtype'] == NodeSubTypeTG.TREX:
298             ssh = SSH()
299             ssh.connect(node)
300             (ret, _, _) = ssh.exec_command(
301                 "sh -c 'sudo pkill t-rex && sleep 3'")
302             if int(ret) != 0:
303                 raise RuntimeError('pkill t-rex failed')
304
305     @staticmethod
306     def trex_stl_stop_remote_exec(node):
307         """Execute script on remote node over ssh to stop running traffic.
308
309         :param node: T-REX generator node.
310         :type node: dict
311         :returns: Nothing
312         :raises: RuntimeError if stop traffic script fails.
313         """
314         ssh = SSH()
315         ssh.connect(node)
316
317         (ret, _, _) = ssh.exec_command(
318             "sh -c '{}/resources/tools/trex/"
319             "trex_stateless_stop.py'".format(Constants.REMOTE_FW_DIR))
320
321         if int(ret) != 0:
322             raise RuntimeError('T-rex stateless runtime error')
323
324     def trex_stl_start_remote_exec(self, duration, rate, framesize,
325                                    traffic_type, async_call=False,
326                                    latency=True, warmup_time=5):
327         """Execute script on remote node over ssh to start traffic.
328
329         :param duration: Time expresed in seconds for how long to send traffic.
330         :param rate: Traffic rate expressed with units (pps, %)
331         :param framesize: L2 frame size to send (without padding and IPG).
332         :param traffic_type: Traffic profile.
333         :param async_call: If enabled then don't wait for all incomming trafic.
334         :param latency: With latency measurement.
335         :param warmup_time: Warmup time period.
336         :type duration: int
337         :type rate: str
338         :type framesize: str
339         :type traffic_type: str
340         :type async_call: bool
341         :type latency: bool
342         :type warmup_time: int
343         :returns: Nothing
344         :raises: RuntimeError in case of TG driver issue.
345         """
346         ssh = SSH()
347         ssh.connect(self._node)
348
349         _async = "--async" if async_call else ""
350         _latency = "--latency" if latency else ""
351         _p0, _p1 = (2, 1) if self._ifaces_reordered else (1, 2)
352
353         profile_path = ("{0}/resources/traffic_profiles/trex/"
354                         "{1}.py".format(Constants.REMOTE_FW_DIR,
355                                         traffic_type))
356         (ret, stdout, _) = ssh.exec_command(
357             "sh -c "
358             "'{0}/resources/tools/trex/trex_stateless_profile.py "
359             "--profile {1} "
360             "--duration {2} "
361             "--frame_size {3} "
362             "--rate {4} "
363             "--warmup_time {5} "
364             "--port_0 {6} "
365             "--port_1 {7} "
366             "{8} "   # --async
367             "{9}'".  # --latency
368             format(Constants.REMOTE_FW_DIR, profile_path, duration, framesize,
369                    rate, warmup_time, _p0 - 1, _p1 - 1, _async, _latency),
370             timeout=int(duration) + 60)
371
372         if int(ret) != 0:
373             raise RuntimeError('T-rex stateless runtime error')
374         elif async_call:
375             #no result
376             self._received = None
377             self._sent = None
378             self._loss = None
379             self._latency = None
380         else:
381             # last line from console output
382             line = stdout.splitlines()[-1]
383
384             self._result = line
385             logger.info('TrafficGen result: {0}'.format(self._result))
386
387             self._received = self._result.split(', ')[1].split('=')[1]
388             self._sent = self._result.split(', ')[2].split('=')[1]
389             self._loss = self._result.split(', ')[3].split('=')[1]
390
391             self._latency = []
392             self._latency.append(self._result.split(', ')[4].split('=')[1])
393             self._latency.append(self._result.split(', ')[5].split('=')[1])
394
395     def stop_traffic_on_tg(self):
396         """Stop all traffic on TG.
397
398         :returns: Nothing
399         :raises: RuntimeError if TG is not set.
400         """
401         if self._node is None:
402             raise RuntimeError("TG is not set")
403         if self._node['subtype'] == NodeSubTypeTG.TREX:
404             self.trex_stl_stop_remote_exec(self._node)
405
406     def send_traffic_on_tg(self, duration, rate, framesize,
407                            traffic_type, warmup_time=5, async_call=False,
408                            latency=True):
409         """Send traffic from all configured interfaces on TG.
410
411         :param duration: Duration of test traffic generation in seconds.
412         :param rate: Offered load per interface (e.g. 1%, 3gbps, 4mpps, ...).
413         :param framesize: Frame size (L2) in Bytes.
414         :param traffic_type: Traffic profile.
415         :param warmup_time: Warmup phase in seconds.
416         :param async_call: Async mode.
417         :param latency: With latency measurement.
418         :type duration: str
419         :type rate: str
420         :type framesize: str
421         :type traffic_type: str
422         :type warmup_time: int
423         :type async_call: bool
424         :type latency: bool
425         :returns: TG output.
426         :rtype: str
427         :raises: RuntimeError if TG is not set.
428         :raises: RuntimeError if node is not TG or subtype is not specified.
429         :raises: NotImplementedError if TG is not supported.
430         """
431
432         node = self._node
433         if node is None:
434             raise RuntimeError("TG is not set")
435
436         if node['type'] != NodeType.TG:
437             raise RuntimeError('Node type is not a TG')
438
439         if node['subtype'] is None:
440             raise RuntimeError('TG subtype not defined')
441         elif node['subtype'] == NodeSubTypeTG.TREX:
442             self.trex_stl_start_remote_exec(int(duration), rate, framesize,
443                                             traffic_type, async_call, latency,
444                                             warmup_time=warmup_time)
445         else:
446             raise NotImplementedError("TG subtype not supported")
447
448         return self._result
449
450     def no_traffic_loss_occurred(self):
451         """Fail if loss occurred in traffic run.
452
453         :returns: nothing
454         :raises: Exception if loss occured.
455         """
456         if self._loss is None:
457             raise Exception('The traffic generation has not been issued')
458         if self._loss != '0':
459             raise Exception('Traffic loss occurred: {0}'.format(self._loss))
460
461     def partial_traffic_loss_accepted(self, loss_acceptance,
462                                       loss_acceptance_type):
463         """Fail if loss is higher then accepted in traffic run.
464
465         :param loss_acceptance: Permitted drop ratio or frames count.
466         :param loss_acceptance_type: Type of permitted loss.
467         :type loss_acceptance: float
468         :type loss_acceptance_type: LossAcceptanceType
469         :returns: nothing
470         :raises: Exception if loss is above acceptance criteria.
471         """
472         if self._loss is None:
473             raise Exception('The traffic generation has not been issued')
474
475         if loss_acceptance_type == 'percentage':
476             loss = (float(self._loss) / float(self._sent)) * 100
477         elif loss_acceptance_type == 'frames':
478             loss = float(self._loss)
479         else:
480             raise Exception('Loss acceptance type not supported')
481
482         if loss > float(loss_acceptance):
483             raise Exception("Traffic loss {} above loss acceptance: {}".format(
484                 loss, loss_acceptance))

©2016 FD.io a Linux Foundation Collaborative Project. All Rights Reserved.
Linux Foundation is a registered trademark of The Linux Foundation. Linux is a registered trademark of Linus Torvalds.
Please see our privacy policy and terms of use.