Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Disk writes of a running albedo daemon's process tree over a few minutes (macOS).
python3 test/manual/disk_writes.py --minutes 10 [--home ~/.albedo]
Reads each process's ri_diskio_byteswritten (proc_pid_rusage, RUSAGE_INFO_V2)every --interval seconds: the daemon from $ALBEDO_HOME/daemon.json and everydescendant (kernels, spares, bridges, run() jobs). A process that exits keepsits last sampled value, so a short-lived one can be missed between samples.Files under the home whose size or modification time changed are listed too,to say what was written; their size change is not the bytes written. Linux CImeasures the same thing from /proc/<pid>/io (robot-docs/perf.md)."""
from __future__ import annotations
import argparseimport ctypesimport jsonimport osfrom pathlib import Pathimport structimport subprocessimport sysimport time
RUSAGE_INFO_V2 = 2# rusage_info_v2: ri_diskio_byteswritten follows 18 uint64 fields and the uuid.DISKIO_WRITTEN = 152
def written(libproc, pid): """Bytes a live process has written to disk, or None once it is gone.""" buffer = ctypes.create_string_buffer(160) if libproc.proc_pid_rusage(pid, RUSAGE_INFO_V2, buffer) != 0: return None return struct.unpack_from("=Q", buffer.raw, DISKIO_WRITTEN)[0]
def tree(daemon): """The daemon and its descendants, as pid to command.""" rows = [ line.strip().split(None, 2) for line in subprocess.check_output( ["ps", "-axo", "pid=,ppid=,comm="], text=True ).splitlines() ] children: dict[int, list[int]] = {} commands = {} for pid, ppid, *command in rows: children.setdefault(int(ppid), []).append(int(pid)) commands[int(pid)] = command[0] if command else "" found, frontier = {}, [daemon] while frontier: pid = frontier.pop() if pid in commands and pid not in found: found[pid] = commands[pid] frontier.extend(children.get(pid, [])) return found
def files(home): """Size and modification time of every file under the home.""" result = {} for directory, _, names in os.walk(home): for name in names: path = Path(directory, name) try: info = path.lstat() except OSError: continue result[str(path.relative_to(home))] = (info.st_size, info.st_mtime_ns) return result
def size(value): for unit, scale in (("GB", 1e9), ("MB", 1e6), ("KB", 1e3)): if abs(value) >= scale: return f"{value / scale:.3g} {unit}" return f"{value:.0f} B"
def main(): parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--minutes", type=float, default=10) parser.add_argument("--interval", type=float, default=1) parser.add_argument( "--home", type=Path, default=Path(os.environ.get("ALBEDO_HOME", "~/.albedo")).expanduser(), ) args = parser.parse_args() if sys.platform != "darwin": parser.error("macOS only; Linux reads /proc/<pid>/io (perf)") libproc = ctypes.CDLL("/usr/lib/libproc.dylib") daemon = json.loads((args.home / "daemon.json").read_text())["pid"] if written(libproc, daemon) is None: parser.error(f"daemon {daemon} from {args.home / 'daemon.json'} is not running") start, last, names = {}, {}, {} before = files(args.home) deadline = time.monotonic() + args.minutes * 60 first = True while True: for pid, command in tree(daemon).items(): value = written(libproc, pid) if value is None: continue # A process first seen mid-run started after the window opened. start.setdefault(pid, value if first else 0) last[pid] = value names[pid] = command first = False if time.monotonic() >= deadline: break time.sleep(min(args.interval, max(0, deadline - time.monotonic()))) after = files(args.home) by_process = sorted(((last[pid] - start[pid], pid) for pid in last), reverse=True) total = sum(delta for delta, _ in by_process) print( f"{size(total)} written in {args.minutes:g} min " f"({size(total * 60 / args.minutes)} per hour) by daemon {daemon}" ) for delta, pid in by_process: if delta: print(f" {size(delta):>9} {pid:>7} {Path(names[pid]).name}") changed = sorted( path for path in after if before.get(path, (None, None))[1] != after[path][1] ) print(f"{len(changed)} files under {args.home} changed:") for path in changed: grown = after[path][0] - before.get(path, (0, 0))[0] print(f" {path} ({'+' if grown >= 0 else '-'}{size(abs(grown))})") for path in sorted(before.keys() - after.keys()): print(f" {path} (removed)")
if __name__ == "__main__": main()