File size: 5,588 Bytes
3cfcb19 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | #!/usr/bin/env python3
"""Relay heartbeat test (local, no external network).
Boots a relay with HEARTBEAT_WINDOW_SECONDS=2 and verifies:
1. a healthy stub worker (GET /health -> 200) receives a heartbeat within a window;
/desktop/status reports last_heartbeat_ok_at and zero failures
2. an unreachable worker accumulates heartbeat_failures (observational only)
3. a pull-mode (pull://) worker is NEVER pinged — pull workers check in by polling
4. heartbeat never changes push eligibility (status stays idle for a healthy worker)
"""
import json
import os
import shutil
import signal
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
PORT = 8798
BASE = f"http://127.0.0.1:{PORT}/dataset_verification"
PERSIST_DIR = "/tmp/relay_heartbeat_test"
STUB_OK_PORT = 8821
STUB_PULL_PORT = 8822
ENV = dict(os.environ, PERSIST_DIR=PERSIST_DIR,
RUNNER_API_KEY="runner-key", AGENT_API_KEY="agent-key",
PUSH_URL_HOST_SUFFIX="*", RETENTION_SECONDS="10800",
HEARTBEAT_WINDOW_SECONDS="2", HEARTBEAT_TIMEOUT_SECONDS="1.0")
SPACE_DIR = os.path.join(os.path.dirname(__file__), "..")
def req(method, path, body=None, key="agent-key", timeout=15):
data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode()
r = urllib.request.Request(BASE + path, data=data, method=method)
if key:
r.add_header("Authorization", f"Bearer {key}")
if not isinstance(body, bytes):
r.add_header("Content-Type", "application/json")
with urllib.request.urlopen(r, timeout=timeout) as resp:
return json.loads(resp.read().decode() or "{}")
class Stub(BaseHTTPRequestHandler):
hits = 0
def log_message(self, *a):
pass
def do_GET(self):
if self.path.rstrip("/") == "/health":
type(self).hits += 1
body = b'{"ok": true}'
self.send_response(200)
else:
body = b'{"detail": "not found"}'
self.send_response(404)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def start_stub(port):
server = ThreadingHTTPServer(("127.0.0.1", port), Stub)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
def main():
shutil.rmtree(PERSIST_DIR, ignore_errors=True)
Stub.hits = 0
ok = []
proc = subprocess.Popen([sys.executable, "-m", "uvicorn", "main:app",
"--host", "127.0.0.1", "--port", str(PORT)],
cwd=SPACE_DIR, env=ENV,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for _ in range(60):
try:
urllib.request.urlopen(f"{BASE}/health", timeout=1)
break
except Exception:
time.sleep(0.5)
else:
proc.kill()
raise RuntimeError("boot failed")
print("1. booted (heartbeat window=2s)")
stub_ok = start_stub(STUB_OK_PORT)
stub_pull = start_stub(STUB_PULL_PORT)
env_desc = {"platform": "linux", "os_version": "ubuntu",
"runtimes": ["python-3.12"], "max_concurrent_jobs": 1}
req("POST", "/worker/register",
{"worker_id": 71, "url": f"http://127.0.0.1:{STUB_OK_PORT}",
"environment": env_desc}, key="runner-key")
req("POST", "/worker/register",
{"worker_id": 72, "url": "http://127.0.0.1:9",
"environment": env_desc}, key="runner-key")
req("POST", "/worker/register",
{"worker_id": 73, "url": "pull://73/deadbeefcafe",
"environment": env_desc}, key="runner-key")
ok.append("3 workers registered (healthy / unreachable / pull-mode)")
deadline = time.time() + 25
s71 = s72 = s73 = None
while time.time() < deadline:
status = req("GET", "/desktop/status")
by_id = {w["worker_id"]: w for w in status["workers"]}
s71, s72, s73 = by_id.get(71, {}), by_id.get(72, {}), by_id.get(73, {})
if (s71.get("last_heartbeat_ok_at") and int(s72.get("heartbeat_failures", 0)) >= 1):
break
time.sleep(0.5)
assert s71 and s71.get("last_heartbeat_ok_at"), f"healthy worker never got a heartbeat: {s71}"
assert int(s71.get("heartbeat_failures", 0)) == 0
assert s71.get("status") == "idle", s71 # observational: never disturbs eligibility
ok.append("healthy worker heartbeated; status still idle")
assert s72 and int(s72.get("heartbeat_failures", 0)) >= 1, f"unreachable worker never failed: {s72}"
ok.append("unreachable worker accumulated heartbeat_failures (no eligibility change)")
assert s73 and s73.get("last_heartbeat_at") is None, f"pull-mode worker was pinged: {s73}"
ok.append("pull-mode worker never pinged")
assert Stub.hits >= 1, "healthy stub never saw the ping land"
stub_ok.shutdown()
stub_pull.shutdown()
print("PASS:", " | ".join(ok))
return 0
finally:
proc.send_signal(signal.SIGTERM)
try:
proc.wait(timeout=10)
except Exception:
proc.kill()
if __name__ == "__main__":
sys.exit(main())
|