import subprocess as s,time,json,pathlib,sys
host,mode=sys.argv[1:3]
root=pathlib.Path(__file__).parent
tag=host+"-"+mode+"-"+str(time.time_ns())
jobs=[]
for p in range(5200,5210):
 f=root/(tag+"-"+str(p)+".json")
 args=["timeout","55","iperf3","-c",host,"-p",str(p)]
 args += ["-P","8","-t","30","-J"]
 args += ["-R"] if mode=="rx" else []
 jobs.append((p,f,s.Popen(args,stdout=f.open("w"),stderr=s.STDOUT)))
def counters():
 base=pathlib.Path("/sys/class/net")
 names=("enp33s0f0","enp33s0f1")
 return [int((base/n/"statistics"/(mode+"_bytes")).read_text()) for n in names]
a=counters(); t=time.monotonic(); samples=[]
for i in range(20):
 time.sleep(2)
 b=counters(); u=time.monotonic()
 v=[(y-x)*8/(u-t)/1e9 for x,y in zip(a,b)]
 if 1<i<13: samples.append(v)
 print("PORTS",*[round(z,2) for z in v],"TOTAL",round(sum(v),2),flush=True)
 a=b; t=u
for p,f,proc in jobs:
 proc.wait(timeout=20)
 try: d=json.JSONDecoder().raw_decode(f.read_text())[0]
 except Exception as e: print(p,str(e)); continue
 e=d.get("end",{})
 rate=e.get("sum_received",{}).get("bits_per_second",0)/1e9
 print("IPERF",p,round(rate,2),d.get("error",""),flush=True)
 print("CPU",p,e.get("cpu_utilization_percent",{}))
if samples:
 avg=[sum(x[j] for x in samples)/len(samples) for j in (0,1)]
 print("AVERAGE",mode,*[round(x,2) for x in avg],"TOTAL",round(sum(avg),2))
 print("PEAK",round(max(sum(x) for x in samples),2))
