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

236 lines
10 KiB
Python

#!/usr/bin/env python3
"""Run the experiments: Project 3's fixed window and TCP Reno over a simulated bottleneck. Given.
python3 run.py fixed Project 3's fixed windows, 1 to 64, on a Project 3 path and on the bottleneck: fixed.csv
python3 run.py fixed --p3 ../p3/gbn.py the same, with your own Project 3 Go-Back-N sender
python3 run.py trace one Reno flow: every cwnd change, saved to trace.csv
python3 run.py rwnd a slow receiver: which window limits the sender? saved to rwnd.csv
python3 run.py queue the same flow with queues of 2 to 40 packets, three runs each: queue.csv
python3 run.py fair two Reno flows, 20 ms and 100 ms round trips, one queue: fair.csv
python3 run.py mix a fixed window of 32 and a Reno flow sharing one queue: mix.csv
python3 run.py all all six
python3 run.py trace --cc other.py --out results/ another controller, files elsewhere
The bottleneck path: 200 packets a second (1000-byte packets, 1.6 Mbit/s), a
10-packet queue unless the run varies it, and 20 ms each way. The Project 3
path in `fixed` is Project 3's experiment again: 10 ms each way, 5 percent of
packets lost at random, and no queue to fill. Everything runs on this computer;
no network, root or container. `--cc FILE` runs a Reno class from another file.
Reference: https://docs.python.org/3/library/csv.html
"""
import argparse
import csv
import importlib.util
import os
import statistics
import sys
import threading
import time
import bottleneck
from receiver import Receiver
from sender import Sender
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = HERE # where the CSV files go; --out changes it
RATE = 200 # packets a second through the bottleneck
DELAY = 0.020 # seconds each way
PACKETS = 600
def load(path, name):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def load_controller(path):
return load(path, "controller").Reno
def transfer(neck, controller, packets=PACKETS, delay=DELAY, buffer=64, drain=None, start=None, loss=0.0, seed=0):
"""One flow through `neck`. Returns (stats, trace, intact)."""
a, b = neck.link(delay=delay, loss=loss, seed=seed)
data = bytes((i * 7 + 3) % 251 for i in range(packets * 1000))
out = {}
def receive():
out["data"] = Receiver(b, buffer=buffer, drain=drain).receive()
r = threading.Thread(target=receive, daemon=True)
r.start()
if start is not None:
start.wait()
sender = Sender(a, "B", controller())
stats = sender.send(data)
r.join(5)
return stats, sender.trace, out.get("data") == data
def save(name, rows):
path = os.path.join(OUT, name)
with open(path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
print(f"wrote {len(rows)} rows to {name}")
def goodput(stats, packets=PACKETS):
return round(packets * 1000 * 8 / 1e6 / stats["seconds"], 3)
def fixed_once(neck, size, delay, loss, p3_sender, packets):
"""One fixed-window transfer: the given sender with FixedWindow, or your own Project 3 sender."""
if p3_sender is None:
import congestion
stats, _, intact = transfer(neck, lambda: congestion.FixedWindow(size), packets=packets,
delay=delay, loss=loss, seed=size)
return stats, intact
a, b = neck.link(delay=delay, loss=loss, seed=size)
data = bytes((i * 7 + 3) % 251 for i in range(packets * 1000))
out = {}
r = threading.Thread(target=lambda: out.update(data=Receiver(b).receive()), daemon=True)
r.start()
start = time.monotonic()
stats = dict(p3_sender.Sender(a, "B", window=size, timeout=0.25).send(data) or {})
stats["seconds"] = round(time.monotonic() - start, 3)
r.join(5)
return stats, out.get("data") == data
def run_fixed(controller, p3_path=None):
p3_sender = load(p3_path, "your_gbn") if p3_path else None
rows = []
for path in ("project3", "bottleneck"):
for size in (1, 2, 4, 8, 16, 24, 32, 64):
if path == "project3": # Project 3's experiment: random loss, no queue to fill
neck, delay, loss = bottleneck.Bottleneck(rate=100_000, queue=100_000), 0.010, 0.05
else:
neck, delay, loss = bottleneck.Bottleneck(rate=RATE, queue=10), DELAY, 0.0
stats, intact = fixed_once(neck, size, delay, loss, p3_sender, 300)
rows.append({"path": path, "window": size, "sender": "yours" if p3_sender else "given",
"intact": intact, "mbps": goodput(stats, 300), "seconds": stats["seconds"],
"transmissions": stats.get("transmissions"), "retransmissions": stats.get("retransmissions"),
"queue_drops": neck.dropped, "peak_queue": neck.peak})
print(rows[-1])
save("fixed.csv", rows)
def run_mix(controller):
import congestion
rows = []
for run in (1, 2, 3):
neck = bottleneck.Bottleneck(rate=RATE, queue=10)
go = threading.Event()
results = {}
def flow(name, make):
results[name] = transfer(neck, make, packets=800, start=go)
threads = [threading.Thread(target=flow, args=("fixed", lambda: congestion.FixedWindow(32))),
threading.Thread(target=flow, args=("reno", controller))]
for t in threads:
t.start()
time.sleep(0.2)
go.set()
for t in threads:
t.join()
both = min(results[n][0]["seconds"] for n in results)
for name in ("fixed", "reno"):
stats, trace, intact = results[name]
shared = [row for row in trace if row["t_ms"] <= both * 1000]
delivered = max(row["base"] for row in shared)
rows.append({"run": run, "flow": name, "intact": intact, "shared_seconds": round(both, 3),
"packets_while_shared": delivered, "mbps_while_shared": round(delivered * 8000 / 1e6 / both, 3),
"retransmissions": stats["retransmissions"], "timeouts": stats["timeouts"],
"mean_cwnd_while_shared": round(statistics.mean(row["cwnd"] for row in shared), 2)})
print(rows[-1])
save("mix.csv", rows)
def run_trace(controller):
neck = bottleneck.Bottleneck(rate=RATE, queue=10)
stats, trace, intact = transfer(neck, controller)
save("trace.csv", trace)
print(f"intact {intact} goodput {goodput(stats)} Mbit/s {stats} queue drops {neck.dropped}")
def run_rwnd(controller):
neck = bottleneck.Bottleneck(rate=RATE, queue=10)
stats, trace, intact = transfer(neck, controller, packets=300, buffer=6, drain=100)
save("rwnd.csv", trace)
print(f"intact {intact} goodput {goodput(stats, 300)} Mbit/s {stats} queue drops {neck.dropped}")
def run_queue(controller):
rows = []
for queue in (2, 5, 10, 20, 40):
for run in (1, 2, 3):
neck = bottleneck.Bottleneck(rate=RATE, queue=queue)
stats, trace, intact = transfer(neck, controller)
peak = max(row["cwnd"] for row in trace)
rows.append({"queue": queue, "run": run, "intact": intact, "mbps": goodput(stats),
"retransmissions": stats["retransmissions"], "fast_retransmits": stats["fast_retransmits"],
"timeouts": stats["timeouts"], "peak_cwnd": peak, "peak_queue": neck.peak,
"queue_drops": neck.dropped})
print(rows[-1])
save("queue.csv", rows)
def run_fair(controller):
rows = []
for run in (1, 2, 3):
neck = bottleneck.Bottleneck(rate=RATE, queue=10)
go = threading.Event()
results = {}
def flow(name, delay):
results[name] = transfer(neck, controller, packets=800, delay=delay, start=go)
threads = [threading.Thread(target=flow, args=("A", 0.010)), threading.Thread(target=flow, args=("B", 0.050))]
for t in threads:
t.start()
time.sleep(0.2)
go.set()
for t in threads:
t.join()
both = min(results[n][0]["seconds"] for n in ("A", "B")) # while both flows were sending
for name, rtt in (("A", 20), ("B", 100)):
stats, trace, intact = results[name]
shared = [row for row in trace if row["t_ms"] <= both * 1000]
delivered = max(row["base"] for row in shared)
mean_cwnd = statistics.mean(row["cwnd"] for row in shared)
rows.append({"run": run, "flow": name, "rtt_ms": rtt, "intact": intact,
"shared_seconds": round(both, 3), "packets_while_shared": delivered,
"mbps_while_shared": round(delivered * 8000 / 1e6 / both, 3),
"seconds_alone": round(stats["seconds"] - both, 3),
"retransmissions": stats["retransmissions"], "mean_cwnd_while_shared": round(mean_cwnd, 2)})
print(rows[-1])
save("fair.csv", rows)
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("what", choices=("fixed", "trace", "rwnd", "queue", "fair", "mix", "all"))
parser.add_argument("--p3", help="fixed only: your Project 3 gbn.py, run in place of the given sender")
parser.add_argument("--cc", default=os.path.join(HERE, "congestion.py"), help="the controller file to run")
parser.add_argument("--out", default=HERE, help="the folder the CSV files are written to")
args = parser.parse_args()
global OUT
OUT = args.out
controller = load_controller(args.cc)
runs = {"fixed": lambda c: run_fixed(c, args.p3), "trace": run_trace, "rwnd": run_rwnd,
"queue": run_queue, "fair": run_fair, "mix": run_mix}
try:
for name in (runs if args.what == "all" else [args.what]):
runs[name](controller)
except NotImplementedError as exc:
sys.exit(f"{exc} is not written yet in {args.p3 or args.cc}; without --p3 the given sender runs")
if __name__ == "__main__":
main()