152 lines
6.7 KiB
Python
152 lines
6.7 KiB
Python
"""Measure TCP flows across the dumbbell. Given; do not change it.
|
|
|
|
import measure
|
|
flow = measure.Flow(net, "h1", "h3", seconds=10, cc="reno")
|
|
flow.start() # iperf3 from h1 to h3, and cwnd sampling on h1
|
|
result = flow.finish() # waits for the transfer to end
|
|
|
|
`result` is a dict:
|
|
|
|
mbps average throughput the receiver got, Mbit/s
|
|
retransmits segments the sender sent again
|
|
rtt_ms the sender's smoothed RTT at the end, ms
|
|
intervals iperf3's report every `interval` seconds:
|
|
[{"t": seconds, "mbps": ..., "cwnd": bytes, "rtt_ms": ...}, ...]
|
|
cwnd the congestion window read from `ss -ti` every `sample` seconds:
|
|
[{"t": seconds, "cwnd": segments, "ssthresh": segments or None, "rtt_ms": ...}, ...]
|
|
|
|
Start two flows before finishing either one to make them compete.
|
|
|
|
The parsing functions at the bottom work on text, so selfcheck.py can test
|
|
them on any computer. References: iperf3 https://software.es.net/iperf/invoking.html,
|
|
ss https://man7.org/linux/man-pages/man8/ss.8.html
|
|
"""
|
|
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
|
|
class Flow:
|
|
PORTS = {"h3": 5201, "h4": 5202} # one iperf3 server port per receiver
|
|
|
|
def __init__(self, net, src, dst, seconds=10, cc="cubic", interval=0.5, sample=0.1):
|
|
self.net, self.src, self.dst = net, src, dst
|
|
self.seconds, self.cc, self.interval, self.sample = seconds, cc, interval, sample
|
|
self.port = self.PORTS[dst]
|
|
|
|
def start(self):
|
|
from topo import IP
|
|
sender, receiver = self.net.get(self.src), self.net.get(self.dst)
|
|
self.server = receiver.popen(["iperf3", "-s", "-1", "-p", str(self.port)],
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
time.sleep(0.5) # let the server start listening
|
|
# the sampler runs this file inside the sender's network namespace (see sample_main)
|
|
self.sampler = sender.popen([sys.executable, __file__, "_sample", IP[self.dst],
|
|
str(self.port), str(self.sample), str(self.seconds + 2)],
|
|
stdout=subprocess.PIPE, text=True)
|
|
self.client = sender.popen(["iperf3", "-c", IP[self.dst], "-p", str(self.port),
|
|
"-t", str(self.seconds), "-C", self.cc, "-i", str(self.interval), "-J"],
|
|
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
|
return self
|
|
|
|
def finish(self):
|
|
out, err = self.client.communicate(timeout=self.seconds + 30)
|
|
self.server.wait(timeout=10)
|
|
samples, _ = self.sampler.communicate(timeout=self.seconds + 30)
|
|
result = parse_iperf_json(out)
|
|
if result.get("error"):
|
|
raise RuntimeError(f"iperf3 {self.src}->{self.dst}: {result['error']} {err.strip()}")
|
|
result["cwnd"] = json.loads(samples)
|
|
return result
|
|
|
|
|
|
# ---------------------------------------------------------------- parsing (pure functions)
|
|
|
|
def parse_iperf_json(text):
|
|
"""The numbers this homework uses from `iperf3 -J` output."""
|
|
data = json.loads(text)
|
|
if "error" in data:
|
|
return {"error": data["error"]}
|
|
end = data["end"]
|
|
sent = end["streams"][0]["sender"]
|
|
intervals = []
|
|
for iv in data["intervals"]:
|
|
s = iv["streams"][0]
|
|
intervals.append({"t": round(s["end"], 3), "mbps": s["bits_per_second"] / 1e6,
|
|
"cwnd": s.get("snd_cwnd"), "rtt_ms": s.get("rtt", 0) / 1000})
|
|
return {"mbps": end["sum_received"]["bits_per_second"] / 1e6,
|
|
"retransmits": sent.get("retransmits", 0),
|
|
"rtt_ms": sent.get("mean_rtt", 0) / 1000,
|
|
"cc": end.get("sender_tcp_congestion"),
|
|
"intervals": intervals}
|
|
|
|
|
|
SS_FIELDS = {"cwnd": re.compile(r"\bcwnd:(\d+)"),
|
|
"ssthresh": re.compile(r"\bssthresh:(\d+)"),
|
|
"rtt": re.compile(r"\brtt:([\d.]+)/"),
|
|
"bytes_acked": re.compile(r"\bbytes_acked:(\d+)")}
|
|
|
|
|
|
def parse_ss(text, port):
|
|
"""Connections to `port` in `ss -tin` output: {local address: {cwnd, ssthresh, rtt_ms, bytes_acked}}.
|
|
|
|
`ss -tin` prints one line naming the connection and an indented line of
|
|
its TCP internals; the two are joined here.
|
|
"""
|
|
found, current = {}, None
|
|
for line in text.splitlines():
|
|
if not line.strip():
|
|
continue
|
|
if not line[0].isspace(): # a connection line
|
|
parts = line.split()
|
|
current = None
|
|
if len(parts) >= 5 and parts[4].endswith(f":{port}"):
|
|
current = parts[3]
|
|
found[current] = {}
|
|
elif current is not None: # its internals
|
|
info = {}
|
|
for name, rx in SS_FIELDS.items():
|
|
m = rx.search(line)
|
|
info[name] = float(m.group(1)) if m else None
|
|
found[current] = {"cwnd": info["cwnd"], "ssthresh": info["ssthresh"],
|
|
"rtt_ms": info["rtt"], "bytes_acked": info["bytes_acked"] or 0}
|
|
return found
|
|
|
|
|
|
def data_connection(conns, known=None):
|
|
"""The address of iperf3's data connection among `conns`, or None.
|
|
|
|
iperf3 opens a control connection beside the data one. The control one
|
|
moves a few hundred bytes; the data one is the first to pass 10 kB, and
|
|
once found it is followed by address so the control one never replaces it.
|
|
"""
|
|
if known in conns:
|
|
return known
|
|
busy = [a for a, c in conns.items() if c["bytes_acked"] > 10_000]
|
|
return max(busy, key=lambda a: conns[a]["bytes_acked"]) if busy else None
|
|
|
|
|
|
def sample_main(dst, port, every, seconds):
|
|
"""Runs inside the sender: read `ss -tin` every `every` seconds, print the samples as JSON."""
|
|
samples, t0, known = [], time.time(), None
|
|
while time.time() - t0 < seconds:
|
|
out = subprocess.run(["ss", "-tin", "dst", dst], capture_output=True, text=True).stdout
|
|
conns = parse_ss(out, port)
|
|
addr = data_connection(conns, known)
|
|
if addr is None and known is not None:
|
|
break # the data connection has closed
|
|
if addr is not None:
|
|
known, conn = addr, conns[addr]
|
|
if conn["cwnd"] is not None:
|
|
samples.append({"t": round(time.time() - t0, 2), "cwnd": int(conn["cwnd"]),
|
|
"ssthresh": int(conn["ssthresh"]) if conn["ssthresh"] else None,
|
|
"rtt_ms": conn["rtt_ms"]})
|
|
time.sleep(every)
|
|
print(json.dumps(samples))
|
|
|
|
|
|
if __name__ == "__main__" and len(sys.argv) == 6 and sys.argv[1] == "_sample":
|
|
sample_main(sys.argv[2], int(sys.argv[3]), float(sys.argv[4]), float(sys.argv[5]))
|