blob: 030e42b566630397ca75868c25f3aa3e0c32dbe9 [file] [log] [blame]
Daniele Moro4a5a91f2021-09-07 17:24:39 +02001"""
2Copyright 2021 Open Networking Foundation (ONF)
3
4Please refer questions to either the onos test mailing list at <onos-test@onosproject.org>,
5the System Testing Plans and Results wiki page at <https://wiki.onosproject.org/x/voMg>,
6or the System Testing Guide page at <https://wiki.onosproject.org/x/WYQg>
7
8"""
9import time
10import os
Daniele Moro732055a2021-09-28 15:28:46 +020011import sys
12import importlib
Daniele Moro4a5a91f2021-09-07 17:24:39 +020013import collections
14import numpy as np
15
16from drivers.common.api.controllerdriver import Controller
Daniele Moro4a5a91f2021-09-07 17:24:39 +020017
18from socket import error as ConnectionRefusedError
19from distutils.util import strtobool
20
21TREX_FILES_DIR = "/tmp/trex_files/"
22
23LatencyStats = collections.namedtuple(
24 "LatencyStats",
25 [
26 "pg_id",
27 "jitter",
28 "average",
29 "total_max",
30 "total_min",
31 "last_max",
32 "histogram",
33 "dropped",
34 "out_of_order",
35 "duplicate",
36 "seq_too_high",
37 "seq_too_low",
38 "percentile_50",
39 "percentile_75",
40 "percentile_90",
41 "percentile_99",
42 "percentile_99_9",
43 "percentile_99_99",
44 "percentile_99_999",
45 ],
46)
47
48PortStats = collections.namedtuple(
49 "PortStats",
50 [
51 "tx_packets",
52 "rx_packets",
53 "tx_bytes",
54 "rx_bytes",
55 "tx_errors",
56 "rx_errors",
57 "tx_bps",
58 "tx_pps",
59 "tx_bps_L1",
60 "tx_util",
61 "rx_bps",
62 "rx_pps",
63 "rx_bps_L1",
64 "rx_util",
65 ],
66)
67
68FlowStats = collections.namedtuple(
69 "FlowStats",
70 [
71 "pg_id",
72 "tx_packets",
73 "rx_packets",
74 "tx_bytes",
75 "rx_bytes",
76 ],
77)
78
79
80class TrexClientDriver(Controller):
81 """
82 Implements a Trex Client Driver
83 """
84
85 def __init__(self):
86 self.trex_address = "localhost"
87 self.trex_config = None # Relative path in dependencies of the test using this driver
88 self.force_restart = True
89 self.sofware_mode = False
90 self.setup_successful = False
91 self.stats = None
92 self.trex_client = None
93 self.trex_daemon_client = None
Daniele Moro732055a2021-09-28 15:28:46 +020094 self.trex_library_python_path = None
Daniele Moro4a5a91f2021-09-07 17:24:39 +020095 super(TrexClientDriver, self).__init__()
96
97 def connect(self, **connectargs):
Daniele Moro732055a2021-09-28 15:28:46 +020098 global STLClient, STLStreamDstMAC_PKT, CTRexClient, STLPktBuilder, \
99 STLFlowLatencyStats, STLStream, STLTXCont
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200100 try:
101 for key in connectargs:
102 vars(self)[key] = connectargs[key]
103 for key in self.options:
104 if key == "trex_address":
105 self.trex_address = self.options[key]
106 elif key == "trex_config":
107 self.trex_config = self.options[key]
108 elif key == "force_restart":
109 self.force_restart = bool(strtobool(self.options[key]))
110 elif key == "software_mode":
111 self.software_mode = bool(strtobool(self.options[key]))
Daniele Moro732055a2021-09-28 15:28:46 +0200112 elif key == "trex_library_python_path":
113 self.trex_library_python_path = self.options[key]
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200114 self.name = self.options["name"]
Daniele Moro732055a2021-09-28 15:28:46 +0200115 if self.trex_library_python_path is not None:
116 sys.path.append(self.trex_library_python_path)
117 # Import after appending the TRex library Python path
118 STLClient = getattr(importlib.import_module("trex.stl.api"), "STLClient")
119 STLStreamDstMAC_PKT = getattr(importlib.import_module("trex.stl.api"), "STLStreamDstMAC_PKT")
120 CTRexClient = getattr(importlib.import_module("trex_stf_lib.trex_client"), "CTRexClient")
121 STLFlowLatencyStats = getattr(importlib.import_module("trex_stl_lib.api"), "STLFlowLatencyStats")
122 STLPktBuilder = getattr(importlib.import_module("trex_stl_lib.api"), "STLPktBuilder")
123 STLStream = getattr(importlib.import_module("trex_stl_lib.api"), "STLStream")
124 STLTXCont = getattr(importlib.import_module("trex_stl_lib.api"), "STLTXCont")
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200125 except Exception as inst:
126 main.log.error("Uncaught exception: " + str(inst))
127 main.cleanAndExit()
128 return super(TrexClientDriver, self).connect()
129
130 def disconnect(self):
131 """
132 Called when Test is complete
133 """
134 self.disconnectTrexClient()
135 self.stopTrexServer()
136 return main.TRUE
137
138 def setupTrex(self, pathToTrexConfig):
139 """
140 Setup TRex server passing the TRex configuration.
141 :return: True if setup successful, False otherwise
142 """
143 main.log.debug(self.name + ": Setting up TRex server")
144 if self.software_mode:
145 trex_args = "--software --no-hw-flow-stat"
146 else:
147 trex_args = None
148 self.trex_daemon_client = CTRexClient(self.trex_address,
149 trex_args=trex_args)
150 success = self.__set_up_trex_server(
151 self.trex_daemon_client, self.trex_address,
152 pathToTrexConfig + self.trex_config,
153 self.force_restart
154 )
155 if not success:
156 main.log.error("Failed to set up TRex daemon!")
157 return False
158 self.setup_successful = True
159 return True
160
161 def connectTrexClient(self):
162 if not self.setup_successful:
163 main.log.error("Cannot connect TRex Client, first setup TRex")
164 return False
165 main.log.info("Connecting TRex Client")
166 self.trex_client = STLClient(server=self.trex_address)
167 self.trex_client.connect()
168 self.trex_client.acquire()
169 self.trex_client.reset() # Resets configs from all ports
170 self.trex_client.clear_stats() # Clear status from all ports
171 # Put all ports to promiscuous mode, otherwise they will drop all
172 # incoming packets if the destination mac is not the port mac address.
173 self.trex_client.set_port_attr(self.trex_client.get_all_ports(),
174 promiscuous=True)
175 # Reset the used sender ports
176 self.all_sender_port = set()
177 self.stats = None
178 return True
179
180 def disconnectTrexClient(self):
181 # Teardown TREX Client
182 if self.trex_client is not None:
183 main.log.info("Tearing down STLClient...")
184 self.trex_client.stop()
185 self.trex_client.release()
186 self.trex_client.disconnect()
187 self.trex_client = None
188 # Do not reset stats
189
190 def stopTrexServer(self):
191 if self.trex_daemon_client is not None:
192 self.trex_daemon_client.stop_trex()
193 self.trex_daemon_client = None
194
195 def addStream(self, pkt, trex_port, l1_bps=None, percentage=None,
196 delay=0, flow_id=None, flow_stats=False):
197 """
198 :param pkt: Scapy packet, TRex will send copy of this packet
199 :param trex_port: Port number to send packet from, must match a port in the TRex config file
200 :param l1_bps: L1 Throughput generated by TRex (mutually exclusive with percentage)
201 :param percentage: Percentage usage of the selected port bandwidth (mutually exlusive with l1_bps)
202 :param flow_id: Flow ID, required when saving latency statistics
203 :param flow_stats: True to measure flow statistics (latency and packet), False otherwise, might require software mode
204 :return: True if the stream is create, false otherwise
205 """
206 if (percentage is None and l1_bps is None) or (
207 percentage is not None and l1_bps is not None):
208 main.log.error(
209 "Either percentage or l1_bps must be provided when creating a stream")
210 return False
211 main.log.debug("Creating flow stream")
212 main.log.debug(
213 "port: %d, l1_bps: %s, percentage: %s, delay: %d, flow_id:%s, flow_stats: %s" % (
214 trex_port, str(l1_bps), str(percentage), delay, str(flow_id),
215 str(flow_stats)))
216 main.log.debug(pkt.summary())
217 if flow_stats:
218 traffic_stream = self.__create_latency_stats_stream(
219 pkt,
220 pg_id=flow_id,
221 isg=delay,
222 percentage=percentage,
223 l1_bps=l1_bps)
224 else:
225 traffic_stream = self.__create_background_stream(
226 pkt,
227 percentage=percentage,
228 l1_bps=l1_bps)
229 self.trex_client.add_streams(traffic_stream, ports=trex_port)
230 self.all_sender_port.add(trex_port)
231 return True
232
233 def startAndWaitTraffic(self, duration=10):
234 """
235 Start generating traffic and wait traffic to be send
236 :param duration: Traffic generation duration
237 :return:
238 """
239 if not self.trex_client:
240 main.log.error(
241 "Cannot start traffic, first connect the TRex client")
242 return False
243 main.log.info("Start sending traffic for %d seconds" % duration)
244 self.trex_client.start(list(self.all_sender_port), mult="1",
245 duration=duration)
246 main.log.info("Waiting until all traffic is sent..")
247 self.trex_client.wait_on_traffic(ports=list(self.all_sender_port),
248 rx_delay_ms=100)
249 main.log.info("...traffic sent!")
250 # Reset sender port so we can run other tests with the same TRex client
251 self.all_sender_port = set()
252 main.log.info("Getting stats")
253 self.stats = self.trex_client.get_stats()
254 main.log.info("GOT stats")
255
256 def getFlowStats(self, flow_id):
257 if self.stats is None:
258 main.log.error("No stats saved!")
259 return None
260 return TrexClientDriver.__get_flow_stats(flow_id, self.stats)
261
262 def logFlowStats(self, flow_id):
263 main.log.info("Statistics for flow {}: {}".format(
264 flow_id,
265 TrexClientDriver.__get_readable_flow_stats(
266 self.getFlowStats(flow_id))))
267
268 def getLatencyStats(self, flow_id):
269 if self.stats is None:
270 main.log.error("No stats saved!")
271 return None
272 return TrexClientDriver.__get_latency_stats(flow_id, self.stats)
273
274 def logLatencyStats(self, flow_id):
275 main.log.info("Latency statistics for flow {}: {}".format(
276 flow_id,
277 TrexClientDriver.__get_readable_latency_stats(
278 self.getLatencyStats(flow_id))))
279
280 def getPortStats(self, port_id):
281 if self.stats is None:
282 main.log.error("No stats saved!")
283 return None
284 return TrexClientDriver.__get_port_stats(port_id, self.stats)
285
286 def logPortStats(self, port_id):
287 if self.stats is None:
288 main.log.error("No stats saved!")
289 return None
290 main.log.info("Statistics for port {}: {}".format(
291 port_id, TrexClientDriver.__get_readable_port_stats(
292 self.stats.get(port_id))))
293
294 # From ptf/test/common/ptf_runner.py
295 def __set_up_trex_server(self, trex_daemon_client, trex_address,
296 trex_config,
297 force_restart):
298 try:
299 main.log.info("Pushing Trex config %s to the server" % trex_config)
300 if not trex_daemon_client.push_files(trex_config):
301 main.log.error("Unable to push %s to Trex server" % trex_config)
302 return False
303
304 if force_restart:
305 main.log.info("Restarting TRex")
306 trex_daemon_client.kill_all_trexes()
307 time.sleep(1)
308
309 if not trex_daemon_client.is_idle():
310 main.log.info("The Trex server process is running")
311 main.log.warn(
312 "A Trex server process is still running, "
313 + "use --force-restart to kill it if necessary."
314 )
315 return False
316
317 trex_config_file_on_server = TREX_FILES_DIR + os.path.basename(
318 trex_config)
319 trex_daemon_client.start_stateless(cfg=trex_config_file_on_server)
320 except ConnectionRefusedError:
321 main.log.error(
322 "Unable to connect to server %s.\n" + "Did you start the Trex daemon?" % trex_address)
323 return False
324
325 return True
326
327 def __create_latency_stats_stream(self, pkt, pg_id,
328 name=None,
329 l1_bps=None,
330 percentage=None,
331 isg=0):
332 assert (percentage is None and l1_bps is not None) or (
333 percentage is not None and l1_bps is None)
334 return STLStream(
335 name=name,
336 packet=STLPktBuilder(pkt=pkt),
337 mode=STLTXCont(bps_L1=l1_bps, percentage=percentage),
338 isg=isg,
339 flow_stats=STLFlowLatencyStats(pg_id=pg_id)
340 )
341
342 def __create_background_stream(self, pkt, name=None, percentage=None,
343 l1_bps=None):
344 assert (percentage is None and l1_bps is not None) or (
345 percentage is not None and l1_bps is None)
346 return STLStream(
347 name=name,
348 packet=STLPktBuilder(pkt=pkt),
349 mode=STLTXCont(bps_L1=l1_bps, percentage=percentage)
350 )
351
352 # Multiplier for data rates
353 K = 1000
354 M = 1000 * K
355 G = 1000 * M
356
357 @staticmethod
358 def __to_readable(src, unit="bps"):
359 """
360 Convert number to human readable string.
361 For example: 1,000,000 bps to 1Mbps. 1,000 bytes to 1KB
362
363 :parameters:
364 src : int
365 the original data
366 unit : str
367 the unit ('bps', 'pps', or 'bytes')
368 :returns:
369 A human readable string
370 """
371 if src < 1000:
372 return "{:.1f} {}".format(src, unit)
373 elif src < 1000000:
374 return "{:.1f} K{}".format(src / 1000, unit)
375 elif src < 1000000000:
376 return "{:.1f} M{}".format(src / 1000000, unit)
377 else:
378 return "{:.1f} G{}".format(src / 1000000000, unit)
379
380 @staticmethod
381 def __get_readable_port_stats(port_stats):
382 opackets = port_stats.get("opackets", 0)
383 ipackets = port_stats.get("ipackets", 0)
384 obytes = port_stats.get("obytes", 0)
385 ibytes = port_stats.get("ibytes", 0)
386 oerrors = port_stats.get("oerrors", 0)
387 ierrors = port_stats.get("ierrors", 0)
388 tx_bps = port_stats.get("tx_bps", 0)
389 tx_pps = port_stats.get("tx_pps", 0)
390 tx_bps_L1 = port_stats.get("tx_bps_L1", 0)
391 tx_util = port_stats.get("tx_util", 0)
392 rx_bps = port_stats.get("rx_bps", 0)
393 rx_pps = port_stats.get("rx_pps", 0)
394 rx_bps_L1 = port_stats.get("rx_bps_L1", 0)
395 rx_util = port_stats.get("rx_util", 0)
396 return """
397 Output packets: {}
398 Input packets: {}
399 Output bytes: {} ({})
400 Input bytes: {} ({})
401 Output errors: {}
402 Input errors: {}
403 TX bps: {} ({})
404 TX pps: {} ({})
405 L1 TX bps: {} ({})
406 TX util: {}
407 RX bps: {} ({})
408 RX pps: {} ({})
409 L1 RX bps: {} ({})
410 RX util: {}""".format(
411 opackets,
412 ipackets,
413 obytes,
414 TrexClientDriver.__to_readable(obytes, "Bytes"),
415 ibytes,
416 TrexClientDriver.__to_readable(ibytes, "Bytes"),
417 oerrors,
418 ierrors,
419 tx_bps,
420 TrexClientDriver.__to_readable(tx_bps),
421 tx_pps,
422 TrexClientDriver.__to_readable(tx_pps, "pps"),
423 tx_bps_L1,
424 TrexClientDriver.__to_readable(tx_bps_L1),
425 tx_util,
426 rx_bps,
427 TrexClientDriver.__to_readable(rx_bps),
428 rx_pps,
429 TrexClientDriver.__to_readable(rx_pps, "pps"),
430 rx_bps_L1,
431 TrexClientDriver.__to_readable(rx_bps_L1),
432 rx_util,
433 )
434
435 @staticmethod
436 def __get_port_stats(port, stats):
437 """
438 :param port: int
439 :param stats:
440 :return:
441 """
442 port_stats = stats.get(port)
443 return PortStats(
444 tx_packets=port_stats.get("opackets", 0),
445 rx_packets=port_stats.get("ipackets", 0),
446 tx_bytes=port_stats.get("obytes", 0),
447 rx_bytes=port_stats.get("ibytes", 0),
448 tx_errors=port_stats.get("oerrors", 0),
449 rx_errors=port_stats.get("ierrors", 0),
450 tx_bps=port_stats.get("tx_bps", 0),
451 tx_pps=port_stats.get("tx_pps", 0),
452 tx_bps_L1=port_stats.get("tx_bps_L1", 0),
453 tx_util=port_stats.get("tx_util", 0),
454 rx_bps=port_stats.get("rx_bps", 0),
455 rx_pps=port_stats.get("rx_pps", 0),
456 rx_bps_L1=port_stats.get("rx_bps_L1", 0),
457 rx_util=port_stats.get("rx_util", 0),
458 )
459
460 @staticmethod
461 def __get_latency_stats(pg_id, stats):
462 """
463 :param pg_id: int
464 :param stats:
465 :return:
466 """
467
468 lat_stats = stats["latency"].get(pg_id)
469 lat = lat_stats["latency"]
470 # Estimate latency percentiles from the histogram.
471 l = list(lat["histogram"].keys())
472 l.sort()
473 all_latencies = []
474 for sample in l:
475 range_start = sample
476 if range_start == 0:
477 range_end = 10
478 else:
479 range_end = range_start + pow(10, (len(str(range_start)) - 1))
480 val = lat["histogram"][sample]
481 # Assume whole the bucket experienced the range_end latency.
482 all_latencies += [range_end] * val
483 q = [50, 75, 90, 99, 99.9, 99.99, 99.999]
484 percentiles = np.percentile(all_latencies, q)
485
486 ret = LatencyStats(
487 pg_id=pg_id,
488 jitter=lat["jitter"],
489 average=lat["average"],
490 total_max=lat["total_max"],
491 total_min=lat["total_min"],
492 last_max=lat["last_max"],
493 histogram=lat["histogram"],
494 dropped=lat_stats["err_cntrs"]["dropped"],
495 out_of_order=lat_stats["err_cntrs"]["out_of_order"],
496 duplicate=lat_stats["err_cntrs"]["dup"],
497 seq_too_high=lat_stats["err_cntrs"]["seq_too_high"],
498 seq_too_low=lat_stats["err_cntrs"]["seq_too_low"],
499 percentile_50=percentiles[0],
500 percentile_75=percentiles[1],
501 percentile_90=percentiles[2],
502 percentile_99=percentiles[3],
503 percentile_99_9=percentiles[4],
504 percentile_99_99=percentiles[5],
505 percentile_99_999=percentiles[6],
506 )
507 return ret
508
509 @staticmethod
510 def __get_readable_latency_stats(stats):
511 """
512 :param stats: LatencyStats
513 :return:
514 """
515 histogram = ""
516 # need to listify in order to be able to sort them.
517 l = list(stats.histogram.keys())
518 l.sort()
519 for sample in l:
520 range_start = sample
521 if range_start == 0:
522 range_end = 10
523 else:
524 range_end = range_start + pow(10, (len(str(range_start)) - 1))
525 val = stats.histogram[sample]
526 histogram = (
527 histogram
528 + "\n Packets with latency between {0:>5} us and {1:>5} us: {2:>10}".format(
529 range_start, range_end, val
530 )
531 )
532
533 return """
534 Latency info for pg_id {}
535 Dropped packets: {}
536 Out-of-order packets: {}
537 Sequence too high packets: {}
538 Sequence too low packets: {}
539 Maximum latency: {} us
540 Minimum latency: {} us
541 Maximum latency in last sampling period: {} us
542 Average latency: {} us
543 50th percentile latency: {} us
544 75th percentile latency: {} us
545 90th percentile latency: {} us
546 99th percentile latency: {} us
547 99.9th percentile latency: {} us
548 99.99th percentile latency: {} us
549 99.999th percentile latency: {} us
550 Jitter: {} us
551 Latency distribution histogram: {}
552 """.format(stats.pg_id, stats.dropped, stats.out_of_order,
553 stats.seq_too_high, stats.seq_too_low, stats.total_max,
554 stats.total_min, stats.last_max, stats.average,
555 stats.percentile_50, stats.percentile_75,
556 stats.percentile_90,
557 stats.percentile_99, stats.percentile_99_9,
558 stats.percentile_99_99,
559 stats.percentile_99_999, stats.jitter, histogram)
560
561 @staticmethod
562 def __get_flow_stats(pg_id, stats):
563 """
564 :param pg_id: int
565 :param stats:
566 :return:
567 """
568 FlowStats = collections.namedtuple(
569 "FlowStats",
570 ["pg_id", "tx_packets", "rx_packets", "tx_bytes", "rx_bytes", ],
571 )
572 flow_stats = stats["flow_stats"].get(pg_id)
573 ret = FlowStats(
574 pg_id=pg_id,
575 tx_packets=flow_stats["tx_pkts"]["total"],
576 rx_packets=flow_stats["rx_pkts"]["total"],
577 tx_bytes=flow_stats["tx_bytes"]["total"],
578 rx_bytes=flow_stats["rx_bytes"]["total"],
579 )
580 return ret
581
582 @staticmethod
583 def __get_readable_flow_stats(stats):
584 """
585 :param stats: FlowStats
586 :return:
587 """
588 return """Flow info for pg_id {}
589 TX packets: {}
590 RX packets: {}
591 TX bytes: {}
592 RX bytes: {}""".format(stats.pg_id, stats.tx_packets,
593 stats.rx_packets, stats.tx_bytes,
594 stats.rx_bytes)