142 lines
5.1 KiB
Python
142 lines
5.1 KiB
Python
"""极简入口分流器(perf-harness-demo 横向扩展实验用)。
|
|
|
|
扮演真实架构里入口 Nginx 的角色:把请求**轮询**转发给后端 N 个 mock 实例。
|
|
横向扩展实验里,后端实例数是唯一变量 —— 分流策略与负载参数保持不变。
|
|
|
|
用法:
|
|
python3 target/dispatcher.py --port 18100 --backends 18101,18102,18103,18104
|
|
|
|
零第三方依赖;每线程到每个后端保持一条 keep-alive 连接(http.client)。
|
|
只监听 127.0.0.1,只做本机压测,绝不对外。
|
|
"""
|
|
|
|
import argparse
|
|
import http.client
|
|
import itertools
|
|
import json
|
|
import sys
|
|
import threading
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
|
|
class BackendPool:
|
|
"""轮询选后端 + 每线程 keep-alive 连接复用(断连自动重建重试一次)。"""
|
|
|
|
def __init__(self, ports, host="127.0.0.1", timeout=30.0):
|
|
self.backends = [(host, p) for p in ports]
|
|
self.timeout = timeout
|
|
self._rr = itertools.count()
|
|
self._local = threading.local()
|
|
|
|
def pick(self):
|
|
# itertools.count.__next__ 在 GIL 下原子,多线程轮询无需加锁
|
|
return self.backends[next(self._rr) % len(self.backends)]
|
|
|
|
def _conn(self, backend):
|
|
conns = getattr(self._local, "conns", None)
|
|
if conns is None:
|
|
conns = self._local.conns = {}
|
|
conn = conns.get(backend)
|
|
if conn is None:
|
|
conn = http.client.HTTPConnection(backend[0], backend[1],
|
|
timeout=self.timeout)
|
|
conns[backend] = conn
|
|
return conn
|
|
|
|
def _drop(self, backend):
|
|
conns = getattr(self._local, "conns", None)
|
|
if conns and backend in conns:
|
|
try:
|
|
conns.pop(backend).close()
|
|
except OSError:
|
|
pass
|
|
|
|
def forward(self, method, path, body, headers):
|
|
backend = self.pick()
|
|
for attempt in range(2):
|
|
conn = self._conn(backend)
|
|
try:
|
|
conn.request(method, path, body=body, headers=headers)
|
|
resp = conn.getresponse()
|
|
data = resp.read()
|
|
return resp.status, data
|
|
except (http.client.HTTPException, OSError):
|
|
# keep-alive 连接可能已被后端关闭:丢弃重建,重试一次
|
|
self._drop(backend)
|
|
if attempt == 1:
|
|
raise
|
|
raise RuntimeError("unreachable")
|
|
|
|
|
|
def make_handler(pool):
|
|
class Handler(BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def log_message(self, *args): # 静默
|
|
pass
|
|
|
|
def handle_error(self, request, client_address):
|
|
# 对端先断连(压测收尾)是常态,不刷 traceback(会带本机绝对路径)
|
|
err = sys.exc_info()[1]
|
|
if isinstance(err, (BrokenPipeError, ConnectionResetError)):
|
|
return
|
|
super().handle_error(request, client_address)
|
|
|
|
def _write(self, status, data):
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def _proxy(self):
|
|
length = int(self.headers.get("Content-Length") or 0)
|
|
body = self.rfile.read(length) if length else None
|
|
headers = {"Content-Type": self.headers.get(
|
|
"Content-Type", "application/json")}
|
|
try:
|
|
status, data = pool.forward(self.command, self.path,
|
|
body, headers)
|
|
except (http.client.HTTPException, OSError) as e:
|
|
payload = json.dumps(
|
|
{"code": 502, "msg": f"backend error: {e}",
|
|
"data": None}).encode()
|
|
self._write(502, payload)
|
|
return
|
|
self._write(status, data)
|
|
|
|
def do_GET(self):
|
|
if self.path.startswith("/health"):
|
|
# 就绪探针本地应答,不转发(探的是分流器自己)
|
|
self._write(200, json.dumps(
|
|
{"code": 0, "msg": "ok",
|
|
"data": {"status": "up",
|
|
"backends": len(pool.backends)}}).encode())
|
|
else:
|
|
self._proxy()
|
|
|
|
do_POST = _proxy
|
|
do_DELETE = _proxy
|
|
|
|
return Handler
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="本机轮询分流器(横向扩展实验用)")
|
|
ap.add_argument("--port", type=int, default=18100)
|
|
ap.add_argument("--backends", required=True,
|
|
help="逗号分隔的后端端口,如 18101,18102")
|
|
args = ap.parse_args()
|
|
ports = [int(p) for p in args.backends.split(",") if p.strip()]
|
|
if not ports:
|
|
ap.error("--backends 至少一个端口")
|
|
pool = BackendPool(ports)
|
|
srv = ThreadingHTTPServer(("127.0.0.1", args.port), make_handler(pool))
|
|
print(f"[dispatcher] listening on http://127.0.0.1:{args.port} "
|
|
f"backends={ports}")
|
|
srv.serve_forever()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|