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

115 lines
4.5 KiB
Python

"""A simulated path with a bottleneck: a slow link and a drop-tail queue. Given; do not change it.
Project 3's channel.py lost packets at random. Real congestion is different: a
router's outgoing link can send only so many packets a second, packets that
arrive faster wait in its queue, and when the queue is full the newest one is
dropped. This file builds that path for one or more flows:
neck = Bottleneck(rate=200, queue=10) # 200 packets a second, 10 waiting at most
a, b = neck.link(delay=0.020) # 20 ms each way, so 40 ms round trip
c, d = neck.link(delay=0.050) # a second flow through the same queue
Each link gives two endpoints that behave like the UDP sockets of Project 3:
sendto(), recvfrom() and settimeout(). Data from the first endpoint (the
sender) goes through the bottleneck; the reply direction (ACKs) only waits its
delay. Every flow made from one Bottleneck shares its queue, so flows compete
the way they do at a real router.
Reference: Peterson and Davie, section 6.2, queuing disciplines (FIFO with tail drop)
"""
import heapq
import itertools
import random
import socket
import threading
import time
class _Endpoint:
def __init__(self, name, link):
self.name = name
self._link = link
self._queue = [] # (arrival time, order, bytes, from)
self._timeout = None
def settimeout(self, seconds):
self._timeout = seconds
def sendto(self, data, addr):
self._link.carry(self, bytes(data))
return len(data)
def recvfrom(self, bufsize):
neck = self._link.neck
deadline = None if self._timeout is None else time.monotonic() + self._timeout
with neck.cond:
while True:
now = time.monotonic()
if self._queue and self._queue[0][0] <= now:
_, _, data, sender = heapq.heappop(self._queue)
return data[:bufsize], sender
if deadline is not None and now >= deadline:
raise socket.timeout("timed out")
waits = [t for t in (deadline, self._queue[0][0] if self._queue else None) if t is not None]
neck.cond.wait(None if not waits else max(0.0, min(waits) - now))
class _Link:
def __init__(self, neck, delay, loss, seed):
self.neck = neck
self.delay = delay
self.loss = loss
self.rng = random.Random(seed)
self.a = _Endpoint("A", self)
self.b = _Endpoint("B", self)
def carry(self, source, data):
neck = self.neck
with neck.cond:
now = time.monotonic()
if source is self.a: # data: through the bottleneck queue
arrive = neck.enqueue(now)
if arrive is None or self.rng.random() < self.loss:
neck.cond.notify_all()
return
arrive += self.delay
dest = self.b
else: # ACKs: delay only
arrive = now + self.delay
dest = self.a
heapq.heappush(dest._queue, (arrive, next(neck.order), data, source.name))
neck.cond.notify_all()
class Bottleneck:
"""A link that sends `rate` packets a second behind a FIFO queue holding at most `queue` packets."""
def __init__(self, rate=200, queue=10):
self.rate = rate
self.limit = queue
self.cond = threading.Condition()
self.order = itertools.count()
self._departures = [] # when each packet now queued finishes sending
self.sent = self.dropped = 0
self.peak = 0
def enqueue(self, now):
"""When this packet leaves the bottleneck, or None if the full queue drops it."""
while self._departures and self._departures[0] <= now:
heapq.heappop(self._departures)
waiting = len(self._departures)
if waiting > self.limit: # one in service plus `limit` waiting
self.dropped += 1
return None
last = max(self._departures) if self._departures else now
leave = max(now, last) + 1.0 / self.rate
heapq.heappush(self._departures, leave)
self.sent += 1
self.peak = max(self.peak, waiting)
return leave
def link(self, delay=0.020, loss=0.0, seed=0):
"""Two endpoints for one flow through this bottleneck, `delay` seconds each way."""
made = _Link(self, delay, loss, seed)
return made.a, made.b