#!/usr/bin/env python3 """Measurement helper for the CRaC post. Standard library only. crac_tool.py bench ROUNDS interleaved rounds of every configuration, prints a table crac_tool.py once LABEL start one configuration, print time to first 200 and first POST crac_tool.py traffic PORT N send N valid POST /orders and GET /orders/{id} requests (warm-up) "Ready" = milliseconds from the moment the process is spawned until the first HTTP 200 from GET /ping (polled every 2 ms from a raw socket, so the poll itself costs almost nothing). """ import json, os, signal, socket, statistics, subprocess, sys, time ENV = {k: v for k, v in os.environ.items() if k not in ("JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS")} W = os.environ.get("WORK", "/tmp/crac-work") PORT = int(os.environ.get("PORT", "18771")) JDK_PLAIN, JDK_CRAC = os.environ["JDK_PLAIN"], os.environ["JDK_CRAC"] APP = f"{W}/app/crac-demo-1.0.0.jar" CONFIGS = { "plain-temurin": [f"{JDK_PLAIN}/bin/java", "-jar", APP, f"--server.port={PORT}"], "plain-zulu-crac": [f"{JDK_CRAC}/bin/java", "-jar", APP, f"--server.port={PORT}"], "aot-ctx-only": [f"{JDK_PLAIN}/bin/java", f"-XX:AOTCache={W}/ctx.aot", "-jar", APP, f"--server.port={PORT}"], "aot-traffic": [f"{JDK_PLAIN}/bin/java", f"-XX:AOTCache={W}/traffic.aot", "-jar", APP, f"--server.port={PORT}"], "crac-on-refresh": [f"{JDK_CRAC}/bin/java", f"-XX:CRaCRestoreFrom={W}/cp-refresh"], "crac-warm": [f"{JDK_CRAC}/bin/java", f"-XX:CRaCRestoreFrom={W}/cp-warm"], "native": [f"{W}/native/crac-demo", f"--server.port={PORT}"], } def http(method, path, body=None, timeout=5.0): s = socket.create_connection(("127.0.0.1", PORT), timeout=timeout) try: data = json.dumps(body).encode() if body is not None else b"" hdr = f"{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n" if body is not None: hdr += f"Content-Type: application/json\r\nContent-Length: {len(data)}\r\n" s.sendall(hdr.encode() + b"\r\n" + data) buf = b"" while True: c = s.recv(65536) if not c: break buf += c return int(buf.split(b" ", 2)[1]), buf.split(b"\r\n\r\n", 1)[1].decode() finally: s.close() def port_free(): s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # TIME_WAIT sockets from the last run must not count as busy try: s.bind(("127.0.0.1", PORT)); return True except OSError: return False finally: s.close() def session_rss_mb(sid): best = 0 for pid in os.listdir("/proc"): if not pid.isdigit(): continue try: if os.getsid(int(pid)) != sid: continue for line in open(f"/proc/{pid}/status"): if line.startswith("VmRSS:"): best = max(best, int(line.split()[1]) // 1024) except (OSError, ProcessLookupError): pass return best def run(label, log=None): assert port_free(), "port busy" t0 = time.perf_counter() p = subprocess.Popen(CONFIGS[label], env=ENV, cwd=W, start_new_session=True, stdout=open(log or os.devnull, "w"), stderr=subprocess.STDOUT) ready = None while time.perf_counter() - t0 < 60: try: st, _ = http("GET", "/ping", timeout=1) if st == 200: ready = (time.perf_counter() - t0) * 1000; break except OSError: time.sleep(0.002) if ready is None: kill(p); raise RuntimeError(label + ": not ready") t1 = time.perf_counter() st, _ = http("POST", "/orders", {"customer": "ada", "sku": "X-1", "quantity": 2}) first_post = (time.perf_counter() - t1) * 1000 assert st == 201, st times = [] for i in range(50): t = time.perf_counter(); http("GET", "/orders/1"); times.append((time.perf_counter() - t) * 1000) rss = session_rss_mb(p.pid) kill(p) return dict(ready=ready, first_post=first_post, next50=statistics.median(times), rss=rss) def kill(p): try: os.killpg(p.pid, signal.SIGKILL) except ProcessLookupError: pass try: p.wait(5) except Exception: pass for _ in range(500): if port_free(): return time.sleep(0.01) def bench(rounds): res = {k: [] for k in CONFIGS} for r in range(rounds): for k in CONFIGS: res[k].append(run(k)); time.sleep(0.3) print(f"round {r+1}/{rounds} done", file=sys.stderr) print(f"{'configuration':<18}{'ready ms (median [min..max])':<34}{'1st POST ms':>12}{'next 50 ms':>12}{'RSS MB':>8}") for k, rs in res.items(): rd = [x["ready"] for x in rs] print(f"{k:<18}{statistics.median(rd):>8.0f} [{min(rd):.0f}..{max(rd):.0f}]".ljust(52) + f"{statistics.median(x['first_post'] for x in rs):>12.1f}" + f"{statistics.median(x['next50'] for x in rs):>12.2f}" + f"{statistics.median(x['rss'] for x in rs):>8.0f}") print("raw ready ms per round:") for k, rs in res.items(): print(f" {k}: " + " ".join(f"{x['ready']:.0f}" for x in rs)) def traffic(n): for i in range(n): st, body = http("POST", "/orders", {"customer": f"c{i%7}", "sku": f"S-{i%13}", "quantity": 1 + i % 5}) assert st == 201, (st, body) http("GET", f"/orders/{i+1}") http("POST", "/orders", {"customer": "", "sku": "X", "quantity": 0}) # a 400, so the validation error path is warm http("GET", "/orders/999999") # a 404 http("GET", "/actuator/health") if __name__ == "__main__": cmd = sys.argv[1] if cmd == "bench": bench(int(sys.argv[2])) elif cmd == "once": print(json.dumps(run(sys.argv[2], f"{W}/once-{sys.argv[2]}.log"))) elif cmd == "traffic": PORT = int(sys.argv[2]); traffic(int(sys.argv[3]))