congestion-control/mininet/selfcheck.py
2026-10-28 11:03:44 -06:00

161 lines
6.3 KiB
Python

"""Check your HW 10 work. Given; runs on any computer with Python 3, no container needed.
python3 selfcheck.py
It tests your summarize() and fairness_setup() on made-up numbers, then looks
at whichever of results.csv, fairness.csv, and cwnd.csv exist. A check whose
part is not written yet, or whose file is not there yet, says SKIP.
"""
import csv
import os
import sys
import measure
import run_experiment as rx
results = []
def check(title, fn):
try:
problem = fn()
except NotImplementedError as e:
problem = f"SKIP: {e} is not written yet"
except FileNotFoundError as e:
problem = f"SKIP: {os.path.basename(e.filename)} does not exist yet"
except Exception as e: # reported, then the next check runs
problem = f"{type(e).__name__}: {e}"
status = "PASS" if problem is None else ("SKIP" if problem.startswith("SKIP") else "FAIL")
results.append(status)
print(f"{status} {title}" + ("" if problem is None else f": {problem.removeprefix('SKIP: ')}"))
def rows(path):
with open(path, newline="") as f:
return list(csv.DictReader(f))
# ---------------------------------------------------------------- the given parsers
SS_SAMPLE = """State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
ESTAB 0 0 10.0.0.1:52000 10.0.0.3:5201
\t cubic wscale:10,10 rto:245 rtt:44.506/17.265 mss:1448 cwnd:10 bytes_acked:141 rcv_ssthresh:64088
ESTAB 0 506800 10.0.0.1:52012 10.0.0.3:5201
\t cubic wscale:10,10 rto:247 rtt:46.07/0.006 mss:1448 cwnd:60 ssthresh:59 bytes_acked:1911398
"""
def given_parsers():
conns = measure.parse_ss(SS_SAMPLE, 5201)
data = conns[measure.data_connection(conns)]
if (data["cwnd"], data["ssthresh"], data["rtt_ms"]) != (60, 59, 46.07):
return f"measure.py was changed: parse_ss read {data}"
return None
# ---------------------------------------------------------------- your functions
def summarize_made_up():
made_up = [{"cc": "reno", "loss": "1", "rep": "1", "mbps": "3.0"},
{"cc": "reno", "loss": "1", "rep": "2", "mbps": "4.0"},
{"cc": "reno", "loss": "1", "rep": "3", "mbps": "5.0"},
{"cc": "cubic", "loss": "0", "rep": "1", "mbps": "9.0"},
{"cc": "reno", "loss": "0", "rep": "1", "mbps": "8.0"}]
got = rx.summarize(made_up)
if not isinstance(got, list) or len(got) != 3:
return f"expected 3 conditions, got {got!r}"
order = [(g["loss"], g["cc"]) for g in got]
if order != [(0.0, "cubic"), (0.0, "reno"), (1.0, "reno")]:
return f"expected sorted by loss then algorithm, got {order}"
three = got[2]
want = {"n": 3, "mean": 4.0, "min": 3.0, "max": 5.0, "stdev": 1.0}
for key, value in want.items():
if abs(float(three[key]) - value) > 1e-9:
return f"reno at 1% loss: {key} should be {value}, got {three[key]}"
if float(got[0]["stdev"]) != 0.0:
return "a condition with one run should have stdev 0.0"
return None
def fairness_rtts():
delay, extra = rx.fairness_setup()
rtts = tuple(2 * delay + e for e in extra)
if rtts != tuple(rx.FAIR_RTTS):
return f"round trips would be {rtts} ms, not {rx.FAIR_RTTS}"
if min(extra) < 0 or delay <= 0:
return "delays cannot be negative, and the bottleneck needs some delay"
return None
# ---------------------------------------------------------------- your measurements
def results_file():
got = rows("results.csv")
for col in ("cc", "loss", "rep", "mbps", "retransmits", "rtt_ms"):
if col not in got[0]:
return f"results.csv has no column {col!r}"
runs = {}
for r in got:
runs.setdefault((r["cc"], float(r["loss"])), []).append(float(r["mbps"]))
if not 0 < float(r["mbps"]) <= rx.BW * 1.05:
return f"{r['cc']} at {r['loss']}% ran at {r['mbps']} Mbit/s on a {rx.BW} Mbit/s link"
missing = [(cc, loss) for cc in rx.ALGORITHMS for loss in rx.LOSSES if (cc, float(loss)) not in runs]
if missing:
return f"no runs for {missing}"
short = {k: len(v) for k, v in runs.items() if len(v) < rx.REPS}
if short:
return f"fewer than {rx.REPS} runs for {short}"
# one slow run is a result worth reporting; no fast run at all means the network was not set up as asked
idle = [k for k, v in runs.items() if k[1] == 0 and max(v) < 0.8 * rx.BW]
if idle:
return f"with no loss the link should fill, but no run of {idle} reached {0.8 * rx.BW} Mbit/s"
return None
def fairness_file():
got = rows("fairness.csv")
flows = {}
for r in got:
flows.setdefault(r["flow"], []).append(r)
if set(flows) != {"A", "B"}:
return f"expected flows A and B, got {sorted(flows)}"
if len(flows["A"]) < rx.REPS or len(flows["A"]) != len(flows["B"]):
return f"expected {rx.REPS} runs of both flows, got {len(flows['A'])} and {len(flows['B'])}"
rtts = (float(flows["A"][0]["rtt_ms"]), float(flows["B"][0]["rtt_ms"]))
if rtts != tuple(float(x) for x in rx.FAIR_RTTS):
return f"round trips recorded as {rtts}, expected {rx.FAIR_RTTS}"
for a, b in zip(flows["A"], flows["B"]):
total = float(a["mbps"]) + float(b["mbps"])
if total > rx.BW * 1.05:
return f"run {a['rep']}: the flows add up to {total:.2f} Mbit/s on a {rx.BW} Mbit/s link"
return None
def cwnd_file():
got = rows("cwnd.csv")
per = {}
for r in got:
per.setdefault(r["cc"], []).append(int(r["cwnd"]))
missing = [cc for cc in rx.ALGORITHMS if cc not in per]
if missing:
return f"no samples for {missing}"
few = {cc: len(v) for cc, v in per.items() if len(v) < 5 * rx.SECONDS}
if few:
return f"expected about 10 samples a second, got {few}"
return None
def main():
check("the given parsers are unchanged", given_parsers)
check("summarize() on made-up runs", summarize_made_up)
check("fairness_setup() gives the two round trips", fairness_rtts)
check("results.csv: every condition, enough runs, plausible numbers", results_file)
check("fairness.csv: both flows, every run", fairness_file)
check("cwnd.csv: a trace for each algorithm", cwnd_file)
print(f"\n{results.count('PASS')} passed, {results.count('FAIL')} failed, {results.count('SKIP')} skipped")
sys.exit(1 if "FAIL" in results else 0)
if __name__ == "__main__":
main()