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