#!/usr/bin/env python3
"""Split a running server's resident memory by owner, from /proc/PID/smaps.

    rss_breakdown.py PID [--json]

PID is the root of a container's process tree (`podman inspect -f '{{.State.Pid}}' NAME`). Every process in
the tree is read, as `bench.py` does for its RSS figure, so the totals match the published numbers.

Owners (resident KB, from Rss of each mapping):
  binary     file-backed pages of the server executable (text, rodata, relro, data)
  db         SQLite files mapped by mmap (*.db, *.db-wal, *.db-shm)
  libs       other shared libraries and files
  anon       anonymous memory: mimalloc arenas, the glibc heap, thread stacks, everything malloc'd
  other      [vvar], [vdso], and the like
The thread count of each process is printed too (every thread's stack is inside anon).
"""
import json, os, re, sys

HDR = re.compile(r"^([0-9a-f]+)-([0-9a-f]+) (\S+) \S+ \S+ \S+\s*(.*)$")


def tree(root):
    kids = {}
    for d in os.listdir("/proc"):
        if d.isdigit():
            try:
                st = open(f"/proc/{d}/stat").read()
                kids.setdefault(int(st.rsplit(")", 1)[1].split()[1]), []).append(int(d))
            except Exception:
                pass
    out, todo = [], [root]
    while todo:
        p = todo.pop()
        out.append(p)
        todo += kids.get(p, [])
    return out


def owner(path, perms, size_kb):
    if path.endswith((".db", ".db-wal", ".db-shm")) or ".db" in os.path.basename(path):
        return "db"
    if path.endswith("leyr-server"):
        return "binary"
    if path.startswith("["):
        if path.startswith("[anon:"):
            return "anon" + path[5:-1]  # a named anonymous mapping, e.g. anon:mimalloc
        return "anon" if path in ("[heap]",) or path.startswith("[stack") else "other"
    if path:
        return "libs"
    return "anon"


def read(pid):
    res = {}
    cmd = open(f"/proc/{pid}/comm").read().strip()
    cur = None
    for ln in open(f"/proc/{pid}/smaps"):
        m = HDR.match(ln)
        if m:
            lo, hi, perms, path = int(m[1], 16), int(m[2], 16), m[3], m[4].strip()
            cur = {"path": path, "perms": perms, "size": (hi - lo) // 1024}
            continue
        k, _, v = ln.partition(":")
        if k in ("Rss", "Private_Dirty", "Anonymous") and cur is not None:
            cur[k] = int(v.split()[0])
        if k == "VmFlags" and cur is not None:
            o = owner(cur["path"], cur["perms"], cur["size"])
            r = res.setdefault(o, {"rss": 0, "anon": 0, "maps": 0})
            r["rss"] += cur.get("Rss", 0)
            r["anon"] += cur.get("Anonymous", 0)
            r["maps"] += 1
            cur = None
    threads = len(os.listdir(f"/proc/{pid}/task"))
    return cmd, res, threads


def snapshot(pid):
    """Owners in MB, summed over the process tree, plus the thread count: what bench.py stores."""
    total, thr_all = {}, 0
    for p in tree(pid):
        try:
            _, res, thr = read(p)
        except Exception:
            continue
        thr_all += thr
        for o, v in res.items():
            total[o] = total.get(o, 0) + v["rss"] / 1024
    return {"owners_mb": {o: round(v, 2) for o, v in total.items()}, "threads": thr_all}


def main():
    pid = int(sys.argv[1])
    total = {}
    procs = []
    for p in tree(pid):
        try:
            cmd, res, thr = read(p)
        except Exception:
            continue
        procs.append((p, cmd, thr, sum(v["rss"] for v in res.values())))
        for o, v in res.items():
            t = total.setdefault(o, {"rss": 0, "anon": 0, "maps": 0})
            for k in v:
                t[k] += v[k]
    if "--json" in sys.argv:
        print(json.dumps({"owners_kb": total, "procs": procs}))
        return
    grand = sum(v["rss"] for v in total.values())
    for o, v in sorted(total.items(), key=lambda kv: -kv[1]["rss"]):
        print(f"{o:8s} rss {v['rss']/1024:7.1f} MB  anon {v['anon']/1024:7.1f} MB  maps {v['maps']}")
    print(f"{'total':8s} rss {grand/1024:7.1f} MB")
    for p, cmd, thr, rss in procs:
        print(f"  pid {p} {cmd} threads {thr} rss {rss/1024:.1f} MB")


if __name__ == "__main__":
    main()
