Files

109 lines
3.9 KiB
Python
Executable File

#!/usr/bin/env python3
"""latency - measure latency to several hosts and rank them.
Usage: latency [-p PORT] [-n COUNT] host [host ...] [--selftest]
Times a TCP connect to each host (default port 80) COUNT times and ranks
the hosts fastest-first, with min/avg/max and a verdict per host. TCP
connect time is used instead of ICMP so it works without raw-socket
privileges and measures what an application actually feels. Unreachable
hosts are ranked last with the error shown, not dropped.
"""
import argparse
import socket
import sys
import time
def measure(host, port, count=3, timeout=3.0):
times = []
err = None
for _ in range(count):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
t0 = time.monotonic()
try:
s.connect((host, port))
times.append((time.monotonic() - t0) * 1000.0)
except OSError as e:
err = str(e)
finally:
s.close()
return times, err
def verdict(avg_ms):
if avg_ms is None:
return "UNREACHABLE"
if avg_ms < 20:
return "excellent"
if avg_ms < 80:
return "good"
if avg_ms < 200:
return "slow"
return "very slow"
def rank(hosts, port, count):
results = []
for host in hosts:
try:
ip = socket.gethostbyname(host)
except socket.gaierror as e:
results.append((host, None, None, None, f"DNS: {e}"))
continue
times, err = measure(ip, port, count)
if times:
results.append((host, min(times), sum(times) / len(times), max(times), None))
else:
results.append((host, None, None, None, err or "connect failed"))
results.sort(key=lambda r: (r[2] is None, r[2] if r[2] is not None else 0))
return results
def selftest():
# Localhost TCP connect must be fast; use a throwaway listener so the
# test does not depend on any service actually running.
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 0))
port = srv.getsockname()[1]
srv.listen(1)
try:
results = rank(["127.0.0.1", "nonexistent.invalid"], port, 2)
print(f"{'HOST':<22} {'MIN':>7} {'AVG':>7} {'MAX':>7} VERDICT")
for host, mn, avg, mx, err in results:
if err:
print(f"{host:<22} {'-':>7} {'-':>7} {'-':>7} {err}")
else:
print(f"{host:<22} {mn:7.1f} {avg:7.1f} {mx:7.1f} {verdict(avg)}")
assert results[0][0] == "127.0.0.1" and results[0][2] is not None, "localhost should rank first"
assert results[0][2] < 100, f"localhost avg {results[0][2]:.1f} ms implausibly slow"
print("selftest: localhost ranked first, unreachable host ranked last — OK")
return 0
finally:
srv.close()
def main():
ap = argparse.ArgumentParser(description="latency - measure latency to several hosts and rank them")
ap.add_argument("hosts", nargs="*", help="hosts to measure")
ap.add_argument("-p", "--port", type=int, default=80, help="TCP port to connect to (default 80)")
ap.add_argument("-n", "--count", type=int, default=3, help="connects per host (default 3)")
ap.add_argument("--selftest", action="store_true", help="rank localhost vs an unresolvable host")
args = ap.parse_args()
if args.selftest:
return selftest()
if not args.hosts:
ap.error("at least one host is required (or use --selftest)")
results = rank(args.hosts, args.port, args.count)
print(f"{'HOST':<28} {'MIN':>7} {'AVG':>7} {'MAX':>7} VERDICT")
for host, mn, avg, mx, err in results:
if err:
print(f"{host:<28} {'-':>7} {'-':>7} {'-':>7} {err}")
else:
print(f"{host:<28} {mn:7.1f} {avg:7.1f} {mx:7.1f} {verdict(avg)}")
return 0
if __name__ == "__main__":
sys.exit(main())