#!/bin/sh set -eu # Both virtual peers live inside disposable network namespaces. exec timeout 45s unshare --user --map-root-user --net python3 - <<'PY' import json import re import socket import statistics import subprocess import sys from concurrent.futures import ThreadPoolExecutor import time def run(*args): return subprocess.run(args, check=True, capture_output=True, text=True, timeout=5).stdout def probe(): output = run("ping", "-n", "-i", "0.15", "-W", "1", "-c", "6", "192.0.2.2") times = [float(value) for value in re.findall(r"time[=<]([\d.]+)", output)] return {"replies": len(times), "medianMs": round(statistics.median(times), 3), "minMs": min(times), "maxMs": max(times)} def upload(): with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client: deadline = time.monotonic() + 3 while time.monotonic() < deadline: client.sendto(bytes(900), ("192.0.2.2", 12345)) time.sleep(0.006) peer_code = """ import socket import subprocess print("namespace ready", flush=True) input() subprocess.run(["ip", "addr", "add", "192.0.2.2/30", "dev", "lab-peer"], check=True) subprocess.run(["ip", "link", "set", "lab-peer", "up"], check=True) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server: server.bind(("192.0.2.2", 12345)) print("sink ready", flush=True) while True: server.recvfrom(1024) """ peer = subprocess.Popen(["unshare", "--net", sys.executable, "-c", peer_code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) try: assert peer.stdout.readline().strip() == "namespace ready" run("ip", "link", "add", "lab-client", "type", "veth", "peer", "name", "lab-peer") run("ip", "link", "set", "lab-peer", "netns", str(peer.pid)) run("ip", "addr", "add", "192.0.2.1/30", "dev", "lab-client") run("ip", "link", "set", "lab-client", "up") run("tc", "qdisc", "add", "dev", "lab-client", "root", "netem", "rate", "1mbit", "limit", "20") peer.stdin.write("\n") peer.stdin.flush() assert peer.stdout.readline().strip() == "sink ready" results = [] for _ in range(3): idle = probe() with ThreadPoolExecutor(max_workers=1) as executor: load = executor.submit(upload) time.sleep(0.5) busy = probe() assert not load.done(), "Upload ended before the probe window" load.result() time.sleep(0.35) results.append({"idle": idle, "upload": busy, "recovery": probe()}) print(json.dumps(results, indent=2)) assert all(item["upload"]["medianMs"] > item["idle"]["medianMs"] + 20 and item["recovery"]["medianMs"] < item["upload"]["medianMs"] - 20 for item in results) finally: peer.terminate() peer.wait(timeout=3) PY