blob: 50c8c39df28986c8cd31641002497782348b7e5b [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,
Yi Tsengdda7e322021-09-20 14:21:20 -0700152 os.path.join(pathToTrexConfig, self.trex_config),
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200153 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
Daniele Morof811f9f2021-09-21 19:07:52 +0200233 def startAndWaitTraffic(self, duration=10, ports=[]):
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200234 """
235 Start generating traffic and wait traffic to be send
Daniele Morof811f9f2021-09-21 19:07:52 +0200236
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200237 :param duration: Traffic generation duration
Daniele Morof811f9f2021-09-21 19:07:52 +0200238 :param ports: Ports IDs to monitor while traffic is active
239 :return: port statistics collected while traffic is active
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200240 """
241 if not self.trex_client:
242 main.log.error(
243 "Cannot start traffic, first connect the TRex client")
244 return False
245 main.log.info("Start sending traffic for %d seconds" % duration)
246 self.trex_client.start(list(self.all_sender_port), mult="1",
247 duration=duration)
248 main.log.info("Waiting until all traffic is sent..")
Daniele Morof811f9f2021-09-21 19:07:52 +0200249 result = self.__monitor_port_stats(ports)
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200250 self.trex_client.wait_on_traffic(ports=list(self.all_sender_port),
251 rx_delay_ms=100)
252 main.log.info("...traffic sent!")
253 # Reset sender port so we can run other tests with the same TRex client
254 self.all_sender_port = set()
255 main.log.info("Getting stats")
256 self.stats = self.trex_client.get_stats()
Daniele Morof811f9f2021-09-21 19:07:52 +0200257 return result
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200258
259 def getFlowStats(self, flow_id):
260 if self.stats is None:
261 main.log.error("No stats saved!")
262 return None
263 return TrexClientDriver.__get_flow_stats(flow_id, self.stats)
264
265 def logFlowStats(self, flow_id):
266 main.log.info("Statistics for flow {}: {}".format(
267 flow_id,
268 TrexClientDriver.__get_readable_flow_stats(
269 self.getFlowStats(flow_id))))
270
271 def getLatencyStats(self, flow_id):
272 if self.stats is None:
273 main.log.error("No stats saved!")
274 return None
275 return TrexClientDriver.__get_latency_stats(flow_id, self.stats)
276
277 def logLatencyStats(self, flow_id):
278 main.log.info("Latency statistics for flow {}: {}".format(
279 flow_id,
280 TrexClientDriver.__get_readable_latency_stats(
281 self.getLatencyStats(flow_id))))
282
283 def getPortStats(self, port_id):
284 if self.stats is None:
285 main.log.error("No stats saved!")
286 return None
287 return TrexClientDriver.__get_port_stats(port_id, self.stats)
288
289 def logPortStats(self, port_id):
290 if self.stats is None:
291 main.log.error("No stats saved!")
292 return None
293 main.log.info("Statistics for port {}: {}".format(
294 port_id, TrexClientDriver.__get_readable_port_stats(
295 self.stats.get(port_id))))
296
297 # From ptf/test/common/ptf_runner.py
298 def __set_up_trex_server(self, trex_daemon_client, trex_address,
299 trex_config,
300 force_restart):
301 try:
302 main.log.info("Pushing Trex config %s to the server" % trex_config)
303 if not trex_daemon_client.push_files(trex_config):
304 main.log.error("Unable to push %s to Trex server" % trex_config)
305 return False
306
307 if force_restart:
308 main.log.info("Restarting TRex")
309 trex_daemon_client.kill_all_trexes()
310 time.sleep(1)
311
312 if not trex_daemon_client.is_idle():
313 main.log.info("The Trex server process is running")
314 main.log.warn(
315 "A Trex server process is still running, "
316 + "use --force-restart to kill it if necessary."
317 )
318 return False
319
320 trex_config_file_on_server = TREX_FILES_DIR + os.path.basename(
321 trex_config)
322 trex_daemon_client.start_stateless(cfg=trex_config_file_on_server)
323 except ConnectionRefusedError:
324 main.log.error(
Daniele Morof811f9f2021-09-21 19:07:52 +0200325 "Unable to connect to server %s.\n" +
326 "Did you start the Trex daemon?" % trex_address)
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200327 return False
328
329 return True
330
331 def __create_latency_stats_stream(self, pkt, pg_id,
332 name=None,
333 l1_bps=None,
334 percentage=None,
335 isg=0):
336 assert (percentage is None and l1_bps is not None) or (
337 percentage is not None and l1_bps is None)
338 return STLStream(
339 name=name,
340 packet=STLPktBuilder(pkt=pkt),
341 mode=STLTXCont(bps_L1=l1_bps, percentage=percentage),
342 isg=isg,
343 flow_stats=STLFlowLatencyStats(pg_id=pg_id)
344 )
345
346 def __create_background_stream(self, pkt, name=None, percentage=None,
347 l1_bps=None):
348 assert (percentage is None and l1_bps is not None) or (
349 percentage is not None and l1_bps is None)
350 return STLStream(
351 name=name,
352 packet=STLPktBuilder(pkt=pkt),
353 mode=STLTXCont(bps_L1=l1_bps, percentage=percentage)
354 )
355
356 # Multiplier for data rates
357 K = 1000
358 M = 1000 * K
359 G = 1000 * M
360
Daniele Morof811f9f2021-09-21 19:07:52 +0200361 def __monitor_port_stats(self, ports, time_interval=1):
362 """
363 List some port stats continuously while traffic is active
364
365 :param ports: List of ports ids to monitor
366 :param time_interval: Interval between read
367 :return: Statistics read while traffic is active
368 """
369
370 results = {
371 port_id: {"rx_bps": [], "tx_bps": [], "rx_pps": [], "tx_pps": []}
372 for port_id in ports
373 }
374 results["duration"] = []
375
376 prev = {
377 port_id: {
378 "opackets": 0,
379 "ipackets": 0,
380 "obytes": 0,
381 "ibytes": 0,
382 "time": time.time(),
383 }
384 for port_id in ports
385 }
386
387 s_time = time.time()
388 while self.trex_client.is_traffic_active():
389 stats = self.trex_client.get_stats(ports=ports)
390 if not stats:
391 break
392
393 main.log.debug(
394 "\nTRAFFIC RUNNING {:.2f} SEC".format(time.time() - s_time))
395 main.log.debug(
396 "{:^4} | {:<10} | {:<10} | {:<10} | {:<10} |".format(
397 "Port", "RX bps", "TX bps", "RX pps", "TX pps"
398 )
399 )
400 main.log.debug(
401 "----------------------------------------------------------")
402
403 for port in ports:
404 opackets = stats[port]["opackets"]
405 ipackets = stats[port]["ipackets"]
406 obytes = stats[port]["obytes"]
407 ibytes = stats[port]["ibytes"]
408 time_diff = time.time() - prev[port]["time"]
409
410 rx_bps = 8 * (ibytes - prev[port]["ibytes"]) / time_diff
411 tx_bps = 8 * (obytes - prev[port]["obytes"]) / time_diff
412 rx_pps = ipackets - prev[port]["ipackets"] / time_diff
413 tx_pps = opackets - prev[port]["opackets"] / time_diff
414
415 main.log.debug(
416 "{:^4} | {:<10} | {:<10} | {:<10} | {:<10} |".format(
417 port,
418 TrexClientDriver.__to_readable(rx_bps, "bps"),
419 TrexClientDriver.__to_readable(tx_bps, "bps"),
420 TrexClientDriver.__to_readable(rx_pps, "pps"),
421 TrexClientDriver.__to_readable(tx_pps, "pps"),
422 )
423 )
424
425 results["duration"].append(time.time() - s_time)
426 results[port]["rx_bps"].append(rx_bps)
427 results[port]["tx_bps"].append(tx_bps)
428 results[port]["rx_pps"].append(rx_pps)
429 results[port]["tx_pps"].append(tx_pps)
430
431 prev[port]["opackets"] = opackets
432 prev[port]["ipackets"] = ipackets
433 prev[port]["obytes"] = obytes
434 prev[port]["ibytes"] = ibytes
435 prev[port]["time"] = time.time()
436
437 time.sleep(time_interval)
438 main.log.debug("")
439
440 return results
441
Daniele Moro4a5a91f2021-09-07 17:24:39 +0200442 @staticmethod
443 def __to_readable(src, unit="bps"):
444 """
445 Convert number to human readable string.
446 For example: 1,000,000 bps to 1Mbps. 1,000 bytes to 1KB
447
448 :parameters:
449 src : int
450 the original data
451 unit : str
452 the unit ('bps', 'pps', or 'bytes')
453 :returns:
454 A human readable string
455 """
456 if src < 1000:
457 return "{:.1f} {}".format(src, unit)
458 elif src < 1000000:
459 return "{:.1f} K{}".format(src / 1000, unit)
460 elif src < 1000000000:
461 return "{:.1f} M{}".format(src / 1000000, unit)
462 else:
463 return "{:.1f} G{}".format(src / 1000000000, unit)
464
465 @staticmethod
466 def __get_readable_port_stats(port_stats):
467 opackets = port_stats.get("opackets", 0)
468 ipackets = port_stats.get("ipackets", 0)
469 obytes = port_stats.get("obytes", 0)
470 ibytes = port_stats.get("ibytes", 0)
471 oerrors = port_stats.get("oerrors", 0)
472 ierrors = port_stats.get("ierrors", 0)
473 tx_bps = port_stats.get("tx_bps", 0)
474 tx_pps = port_stats.get("tx_pps", 0)
475 tx_bps_L1 = port_stats.get("tx_bps_L1", 0)
476 tx_util = port_stats.get("tx_util", 0)
477 rx_bps = port_stats.get("rx_bps", 0)
478 rx_pps = port_stats.get("rx_pps", 0)
479 rx_bps_L1 = port_stats.get("rx_bps_L1", 0)
480 rx_util = port_stats.get("rx_util", 0)
481 return """
482 Output packets: {}
483 Input packets: {}
484 Output bytes: {} ({})
485 Input bytes: {} ({})
486 Output errors: {}
487 Input errors: {}
488 TX bps: {} ({})
489 TX pps: {} ({})
490 L1 TX bps: {} ({})
491 TX util: {}
492 RX bps: {} ({})
493 RX pps: {} ({})
494 L1 RX bps: {} ({})
495 RX util: {}""".format(
496 opackets,
497 ipackets,
498 obytes,
499 TrexClientDriver.__to_readable(obytes, "Bytes"),
500 ibytes,
501 TrexClientDriver.__to_readable(ibytes, "Bytes"),
502 oerrors,
503 ierrors,
504 tx_bps,
505 TrexClientDriver.__to_readable(tx_bps),
506 tx_pps,
507 TrexClientDriver.__to_readable(tx_pps, "pps"),
508 tx_bps_L1,
509 TrexClientDriver.__to_readable(tx_bps_L1),
510 tx_util,
511 rx_bps,
512 TrexClientDriver.__to_readable(rx_bps),
513 rx_pps,
514 TrexClientDriver.__to_readable(rx_pps, "pps"),
515 rx_bps_L1,
516 TrexClientDriver.__to_readable(rx_bps_L1),
517 rx_util,
518 )
519
520 @staticmethod
521 def __get_port_stats(port, stats):
522 """
523 :param port: int
524 :param stats:
525 :return:
526 """
527 port_stats = stats.get(port)
528 return PortStats(
529 tx_packets=port_stats.get("opackets", 0),
530 rx_packets=port_stats.get("ipackets", 0),
531 tx_bytes=port_stats.get("obytes", 0),
532 rx_bytes=port_stats.get("ibytes", 0),
533 tx_errors=port_stats.get("oerrors", 0),
534 rx_errors=port_stats.get("ierrors", 0),
535 tx_bps=port_stats.get("tx_bps", 0),
536 tx_pps=port_stats.get("tx_pps", 0),
537 tx_bps_L1=port_stats.get("tx_bps_L1", 0),
538 tx_util=port_stats.get("tx_util", 0),
539 rx_bps=port_stats.get("rx_bps", 0),
540 rx_pps=port_stats.get("rx_pps", 0),
541 rx_bps_L1=port_stats.get("rx_bps_L1", 0),
542 rx_util=port_stats.get("rx_util", 0),
543 )
544
545 @staticmethod
546 def __get_latency_stats(pg_id, stats):
547 """
548 :param pg_id: int
549 :param stats:
550 :return:
551 """
552
553 lat_stats = stats["latency"].get(pg_id)
554 lat = lat_stats["latency"]
555 # Estimate latency percentiles from the histogram.
556 l = list(lat["histogram"].keys())
557 l.sort()
558 all_latencies = []
559 for sample in l:
560 range_start = sample
561 if range_start == 0:
562 range_end = 10
563 else:
564 range_end = range_start + pow(10, (len(str(range_start)) - 1))
565 val = lat["histogram"][sample]
566 # Assume whole the bucket experienced the range_end latency.
567 all_latencies += [range_end] * val
568 q = [50, 75, 90, 99, 99.9, 99.99, 99.999]
569 percentiles = np.percentile(all_latencies, q)
570
571 ret = LatencyStats(
572 pg_id=pg_id,
573 jitter=lat["jitter"],
574 average=lat["average"],
575 total_max=lat["total_max"],
576 total_min=lat["total_min"],
577 last_max=lat["last_max"],
578 histogram=lat["histogram"],
579 dropped=lat_stats["err_cntrs"]["dropped"],
580 out_of_order=lat_stats["err_cntrs"]["out_of_order"],
581 duplicate=lat_stats["err_cntrs"]["dup"],
582 seq_too_high=lat_stats["err_cntrs"]["seq_too_high"],
583 seq_too_low=lat_stats["err_cntrs"]["seq_too_low"],
584 percentile_50=percentiles[0],
585 percentile_75=percentiles[1],
586 percentile_90=percentiles[2],
587 percentile_99=percentiles[3],
588 percentile_99_9=percentiles[4],
589 percentile_99_99=percentiles[5],
590 percentile_99_999=percentiles[6],
591 )
592 return ret
593
594 @staticmethod
595 def __get_readable_latency_stats(stats):
596 """
597 :param stats: LatencyStats
598 :return:
599 """
600 histogram = ""
601 # need to listify in order to be able to sort them.
602 l = list(stats.histogram.keys())
603 l.sort()
604 for sample in l:
605 range_start = sample
606 if range_start == 0:
607 range_end = 10
608 else:
609 range_end = range_start + pow(10, (len(str(range_start)) - 1))
610 val = stats.histogram[sample]
611 histogram = (
612 histogram
613 + "\n Packets with latency between {0:>5} us and {1:>5} us: {2:>10}".format(
614 range_start, range_end, val
615 )
616 )
617
618 return """
619 Latency info for pg_id {}
620 Dropped packets: {}
621 Out-of-order packets: {}
622 Sequence too high packets: {}
623 Sequence too low packets: {}
624 Maximum latency: {} us
625 Minimum latency: {} us
626 Maximum latency in last sampling period: {} us
627 Average latency: {} us
628 50th percentile latency: {} us
629 75th percentile latency: {} us
630 90th percentile latency: {} us
631 99th percentile latency: {} us
632 99.9th percentile latency: {} us
633 99.99th percentile latency: {} us
634 99.999th percentile latency: {} us
635 Jitter: {} us
636 Latency distribution histogram: {}
637 """.format(stats.pg_id, stats.dropped, stats.out_of_order,
638 stats.seq_too_high, stats.seq_too_low, stats.total_max,
639 stats.total_min, stats.last_max, stats.average,
640 stats.percentile_50, stats.percentile_75,
641 stats.percentile_90,
642 stats.percentile_99, stats.percentile_99_9,
643 stats.percentile_99_99,
644 stats.percentile_99_999, stats.jitter, histogram)
645
646 @staticmethod
647 def __get_flow_stats(pg_id, stats):
648 """
649 :param pg_id: int
650 :param stats:
651 :return:
652 """
653 FlowStats = collections.namedtuple(
654 "FlowStats",
655 ["pg_id", "tx_packets", "rx_packets", "tx_bytes", "rx_bytes", ],
656 )
657 flow_stats = stats["flow_stats"].get(pg_id)
658 ret = FlowStats(
659 pg_id=pg_id,
660 tx_packets=flow_stats["tx_pkts"]["total"],
661 rx_packets=flow_stats["rx_pkts"]["total"],
662 tx_bytes=flow_stats["tx_bytes"]["total"],
663 rx_bytes=flow_stats["rx_bytes"]["total"],
664 )
665 return ret
666
667 @staticmethod
668 def __get_readable_flow_stats(stats):
669 """
670 :param stats: FlowStats
671 :return:
672 """
673 return """Flow info for pg_id {}
674 TX packets: {}
675 RX packets: {}
676 TX bytes: {}
677 RX bytes: {}""".format(stats.pg_id, stats.tx_packets,
678 stats.rx_packets, stats.tx_bytes,
679 stats.rx_bytes)