#!/usr/bin/env python3
"""xbench: reproducible execution-client micro-benchmarks (xone.sh/benchmarks).

Standard library only. Linux only (reads /proc). Every run prints the host,
load average and exact command line so a reader can judge the conditions.

  xbench.py local  --client xone=/path/xone --client geth=/path/geth --client reth=/path/reth
  xbench.py rpc    --url http://127.0.0.1:8545 [--n 2000]
  xbench.py disk   --datadir DIR --url http://127.0.0.1:8545 [--minutes 60]

local: binary size, `version` wall time, cold start of a dev-chain node to first
       eth_blockNumber answer, idle RSS 30 s after start, and RPC p50/p99
       (eth_blockNumber, eth_call to the identity precompile) on that dev node.
rpc:   p50/p99/mean of eth_blockNumber and eth_call against any node (use a
       synced node for the numbers that matter).
disk:  samples datadir size and head block, reports bytes per 100k blocks.
"""
import argparse, http.client, json, os, platform, shutil, signal, socket
import statistics, subprocess, sys, tempfile, time, urllib.parse

# Dev-chain start command per client (#3028). Fields: {bin} {dd} {http} {p2p} {auth}. Each entry
# is one argv element, so a path with a space stays one argument.
TEMPLATES = {
    "xone": ["{bin}", "--dev", "--datadir", "{dd}", "--http", "--http.addr", "127.0.0.1",
             "--http.port", "{http}", "--port", "{p2p}", "--authrpc.port", "{auth}", "--nodiscover",
             "--maxpeers", "0", "--ipcdisable",
             # xone rate-limits RPC by default (geth/reth do not); lift it for a like-for-like run
             "--rpc.bucket.burst", "100000000", "--rpc.bucket.rate", "100000000"],
    "geth": ["{bin}", "--dev", "--datadir", "{dd}", "--http", "--http.addr", "127.0.0.1",
             "--http.port", "{http}", "--port", "{p2p}", "--authrpc.port", "{auth}", "--nodiscover",
             "--maxpeers", "0", "--ipcdisable"],
    "reth": ["{bin}", "node", "--dev", "--datadir", "{dd}", "--http", "--http.addr", "127.0.0.1",
             "--http.port", "{http}", "--port", "{p2p}", "--discovery.port", "{p2p}",
             "--authrpc.port", "{auth}", "--disable-discovery", "--ipcdisable"],
    # Nethermind has no --dev flag. `spaceneth` is its bundled single-node dev preset (dev wallet,
    # no sync, no discovery, in-memory database); the flags were checked with `nethermind --help`
    # of 2.2.2. The preset is found next to the binary (configs/spaceneth.json, chainspec/).
    "nethermind": ["{bin}", "-c", "spaceneth", "-dd", "{dd}", "--JsonRpc.Enabled", "true",
                   "--JsonRpc.Host", "127.0.0.1", "--JsonRpc.Port", "{http}",
                   "--JsonRpc.EngineHost", "127.0.0.1", "--JsonRpc.EnginePort", "{auth}",
                   "--Network.P2PPort", "{p2p}", "--Network.DiscoveryPort", "{p2p}",
                   "--Network.MaxActivePeers", "0", "--Init.DiscoveryEnabled", "false",
                   "--Init.WebSocketsEnabled", "false"],
}
VERSION_ARGS = {"xone": ["version"], "geth": ["version"], "reth": ["--version"],
                "nethermind": ["--version"]}
START_TIMEOUT_S = 60
LOG_TAIL_LINES = 20


def kind_of(name):
    """The template a client name uses: `xone-before` and `xone` both use `xone`."""
    if name in TEMPLATES:
        return name
    base = name.split("-", 1)[0]
    return base if base in TEMPLATES else None


def render(kind, binpath, dd, ports):
    return [a.format(bin=binpath, dd=dd, **ports) for a in TEMPLATES[kind]]


def log_tail(path, n=LOG_TAIL_LINES):
    try:
        with open(path, errors="replace") as f:
            return [l.rstrip("\n") for l in f.readlines()[-n:]]
    except OSError:
        return []


CALL = {"to": "0x0000000000000000000000000000000000000004", "data": "0x68656c6c6f"}


def free_port():
    s = socket.socket(); s.bind(("127.0.0.1", 0)); p = s.getsockname()[1]; s.close(); return p


class Rpc:
    def __init__(self, url):
        u = urllib.parse.urlparse(url)
        self.host, self.port, self.path = u.hostname, u.port or 80, u.path or "/"
        self.conn = None

    def call(self, method, params, timeout=5):
        if self.conn is None:
            self.conn = http.client.HTTPConnection(self.host, self.port, timeout=timeout)
        body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
        try:
            self.conn.request("POST", self.path, body, {"Content-Type": "application/json"})
            r = json.loads(self.conn.getresponse().read())
        except Exception:
            self.conn.close(); self.conn = None; raise
        if "error" in r:
            raise RuntimeError(r["error"])
        return r["result"]


def pct(xs, p):
    xs = sorted(xs); k = (len(xs) - 1) * p / 100; f = int(k)
    return xs[f] + (xs[min(f + 1, len(xs) - 1)] - xs[f]) * (k - f)


def latency(rpc, method, params, n):
    for _ in range(min(50, n)):
        rpc.call(method, params)  # warm-up
    ts = []
    for _ in range(n):
        t = time.perf_counter(); rpc.call(method, params); ts.append((time.perf_counter() - t) * 1000)
    return {"method": method, "n": n, "p50_ms": round(pct(ts, 50), 3),
            "p99_ms": round(pct(ts, 99), 3), "mean_ms": round(statistics.mean(ts), 3)}


def rss_kb(pid, key="VmRSS"):
    tot = 0
    pids = [pid]
    try:
        kids = open(f"/proc/{pid}/task/{pid}/children").read().split()
        pids += [int(k) for k in kids]
    except OSError:
        pass
    for p in pids:
        try:
            for line in open(f"/proc/{p}/status"):
                if line.startswith(key + ":"):
                    tot += int(line.split()[1])
        except OSError:
            pass
    return tot


def host_info():
    try:
        cpu = next(l.split(":", 1)[1].strip() for l in open("/proc/cpuinfo") if l.startswith("model name"))
    except Exception:
        cpu = platform.processor()
    mem = next(int(l.split()[1]) for l in open("/proc/meminfo") if l.startswith("MemTotal"))
    return {"date_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "kernel": platform.release(),
            "cpu": cpu, "cores": os.cpu_count(), "mem_gb": round(mem / 1048576, 1),
            "loadavg": open("/proc/loadavg").read().split()[:3]}


def bench_local(name, binpath, idle_s, n, trials):
    out = {"client": name, "binary": os.path.realpath(binpath),
           "binary_bytes": os.path.getsize(os.path.realpath(binpath))}
    kind = kind_of(name)
    vargs = VERSION_ARGS.get(kind, ["--version"])
    ts = []
    for _ in range(5):
        t = time.perf_counter()
        r = subprocess.run([binpath] + vargs, capture_output=True, text=True)
        ts.append((time.perf_counter() - t) * 1000)
    lines = (r.stdout or r.stderr or "").strip().splitlines()
    out["version"] = next((l.strip() for l in lines if any(c.isdigit() for c in l)), lines[0] if lines else "")
    out["version_ms_median"] = round(statistics.median(ts), 1)
    if kind is None:
        out["error"] = f"no start template for {name!r} (known: {', '.join(TEMPLATES)})"
        return out
    runs = []
    for i in range(trials):
        dd = tempfile.mkdtemp(prefix=f"xbench-{name}-")
        ports = dict(http=free_port(), p2p=free_port(), auth=free_port())
        cmd = render(kind, binpath, dd, ports)
        log = open(os.path.join(dd, "..", os.path.basename(dd) + ".log"), "w")
        t0 = time.perf_counter()
        p = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
        rpc = Rpc(f"http://127.0.0.1:{ports['http']}")
        ready = None
        while time.perf_counter() - t0 < START_TIMEOUT_S:
            if p.poll() is not None:
                break
            try:
                rpc.call("eth_blockNumber", [], timeout=1); ready = time.perf_counter() - t0; break
            except Exception:
                time.sleep(0.02)
        run = {"trial": i + 1, "cmd": " ".join(cmd)}
        try:
            if ready is None:
                run["error"] = (f"no RPC answer within {START_TIMEOUT_S} s (exit={p.poll()})")
            else:
                run["start_to_rpc_s"] = round(ready, 3)
                time.sleep(max(0, idle_s - (time.perf_counter() - t0)))
                run["idle_rss_mb"] = round(rss_kb(p.pid) / 1024, 1)
                run["peak_rss_mb"] = round(rss_kb(p.pid, "VmHWM") / 1024, 1)
                run["rpc"] = [latency(rpc, "eth_blockNumber", [], n),
                              latency(rpc, "eth_call", [CALL, "latest"], n)]
                run["datadir_bytes"] = sum(os.path.getsize(os.path.join(a, f))
                                           for a, _, fs in os.walk(dd) for f in fs
                                           if os.path.isfile(os.path.join(a, f)))
        except Exception as e:
            run["error"] = f"{type(e).__name__}: {e}"
        finally:
            try:
                os.killpg(p.pid, signal.SIGTERM); p.wait(20)
            except Exception:
                try:
                    os.killpg(p.pid, signal.SIGKILL)
                except Exception:
                    pass
        log.close()
        if "error" in run:
            run["log_tail"] = log_tail(log.name)
        os.remove(log.name)  # the tail is in the result
        shutil.rmtree(dd, ignore_errors=True)
        runs.append(run)
    out["runs"] = runs
    ok = [r for r in runs if "error" not in r]
    if ok:
        med = lambda k: round(statistics.median(r[k] for r in ok), 3)
        out["median"] = {"trials_ok": len(ok), "start_to_rpc_s": med("start_to_rpc_s"), "idle_rss_mb": med("idle_rss_mb"),
                         "blockNumber_p50_ms": round(statistics.median(r["rpc"][0]["p50_ms"] for r in ok), 3),
                         "blockNumber_p99_ms": round(statistics.median(r["rpc"][0]["p99_ms"] for r in ok), 3),
                         "call_p50_ms": round(statistics.median(r["rpc"][1]["p50_ms"] for r in ok), 3),
                         "call_p99_ms": round(statistics.median(r["rpc"][1]["p99_ms"] for r in ok), 3)}
    else:
        # never a null median without the reason (#3028)
        out["error"] = runs[-1]["error"] if runs else "no trials run"
    return out


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    a = sub.add_parser("local"); a.add_argument("--client", action="append", required=True,
                                                help="name=/path/to/binary; the name, or its part before the first -, picks the "
                                                     "template (xone, geth, reth, nethermind)")
    a.add_argument("--idle", type=int, default=30); a.add_argument("--n", type=int, default=1000)
    a.add_argument("--trials", type=int, default=3); a.add_argument("--out")
    b = sub.add_parser("rpc"); b.add_argument("--url", required=True); b.add_argument("--n", type=int, default=2000)
    b.add_argument("--out")
    c = sub.add_parser("disk"); c.add_argument("--datadir", required=True); c.add_argument("--url", required=True)
    c.add_argument("--minutes", type=float, default=60); c.add_argument("--every", type=int, default=60)
    c.add_argument("--out")
    args = ap.parse_args()
    res = {"tool": "xbench 1.1", "host": host_info(), "argv": sys.argv[1:]}
    if args.cmd == "local":
        res["results"] = []
        for spec in args.client:
            name, path = spec.split("=", 1)
            print(f"[xbench] {name} ...", file=sys.stderr)
            res["results"].append(bench_local(name, path, args.idle, args.n, args.trials))
    elif args.cmd == "rpc":
        rpc = Rpc(args.url)
        res["head"] = int(rpc.call("eth_blockNumber", []), 16)
        res["results"] = [latency(rpc, "eth_blockNumber", [], args.n),
                          latency(rpc, "eth_call", [CALL, "latest"], args.n)]
    elif args.cmd == "disk":
        rpc = Rpc(args.url); samples = []
        end = time.time() + args.minutes * 60
        while True:
            size = int(subprocess.run(["du", "-sb", args.datadir], capture_output=True, text=True).stdout.split()[0])
            samples.append({"t": int(time.time()), "head": int(rpc.call("eth_blockNumber", []), 16), "bytes": size})
            print(json.dumps(samples[-1]), file=sys.stderr)
            if time.time() >= end:
                break
            time.sleep(args.every)
        d_blocks = samples[-1]["head"] - samples[0]["head"]; d_bytes = samples[-1]["bytes"] - samples[0]["bytes"]
        res["samples"] = samples
        res["blocks"] = d_blocks; res["bytes"] = d_bytes
        res["bytes_per_100k_blocks"] = round(d_bytes / d_blocks * 100000) if d_blocks else None
    js = json.dumps(res, indent=2)
    if getattr(args, "out", None):
        open(args.out, "w").write(js + "\n")
    print(js)


if __name__ == "__main__":
    main()
