1# SPDX-License-Identifier: GPL-2.0 2 3import time 4 5from lib.py import ksft_pr, cmd, ip, rand_port, wait_port_listen, bkg 6 7class GenerateTraffic: 8 def __init__(self, env, port=None): 9 env.require_cmd("iperf3", remote=True) 10 11 self.env = env 12 13 if port is None: 14 port = rand_port() 15 self._iperf_server = cmd(f"iperf3 -s -1 -p {port}", background=True) 16 wait_port_listen(port) 17 time.sleep(0.1) 18 self._iperf_client = cmd(f"iperf3 -c {env.addr} -P 16 -p {port} -t 86400", 19 background=True, host=env.remote) 20 21 # Wait for traffic to ramp up 22 if not self._wait_pkts(pps=1000): 23 self.stop(verbose=True) 24 raise Exception("iperf3 traffic did not ramp up") 25 26 def run_remote_test(self, env: object, port=None, command=None): 27 if port is None: 28 port = rand_port() 29 try: 30 server_cmd = f"iperf3 -s 1 -p {port} --one-off" 31 with bkg(server_cmd, host=env.remote): 32 #iperf3 opens TCP connection as default in server 33 #-u to be specified in client command for UDP 34 wait_port_listen(port, host=env.remote) 35 except Exception as e: 36 raise Exception(f"Unexpected error occurred while running server command: {e}") 37 try: 38 client_cmd = f"iperf3 -c {env.remote_addr} -p {port} {command}" 39 proc = cmd(client_cmd) 40 return proc 41 except Exception as e: 42 raise Exception(f"Unexpected error occurred while running client command: {e}") 43 44 def _wait_pkts(self, pkt_cnt=None, pps=None): 45 """ 46 Wait until we've seen pkt_cnt or until traffic ramps up to pps. 47 Only one of pkt_cnt or pss can be specified. 48 """ 49 pkt_start = ip("-s link show dev " + self.env.ifname, json=True)[0]["stats64"]["rx"]["packets"] 50 for _ in range(50): 51 time.sleep(0.1) 52 pkt_now = ip("-s link show dev " + self.env.ifname, json=True)[0]["stats64"]["rx"]["packets"] 53 if pps: 54 if pkt_now - pkt_start > pps / 10: 55 return True 56 pkt_start = pkt_now 57 elif pkt_cnt: 58 if pkt_now - pkt_start > pkt_cnt: 59 return True 60 return False 61 62 def wait_pkts_and_stop(self, pkt_cnt): 63 failed = not self._wait_pkts(pkt_cnt=pkt_cnt) 64 self.stop(verbose=failed) 65 66 def stop(self, verbose=None): 67 self._iperf_client.process(terminate=True) 68 if verbose: 69 ksft_pr(">> Client:") 70 ksft_pr(self._iperf_client.stdout) 71 ksft_pr(self._iperf_client.stderr) 72 self._iperf_server.process(terminate=True) 73 if verbose: 74 ksft_pr(">> Server:") 75 ksft_pr(self._iperf_server.stdout) 76 ksft_pr(self._iperf_server.stderr) 77