#!/usr/bin/env python3 """Record host and cgroup v2 memory from a process outside the measured unit. python3 scripts/linux_cgroup_sample.py /sys/fs/cgroup/.../trial.service --seconds 90 > host.csv """ import argparse import csv import datetime as dt import os from pathlib import Path import sys import time CGROUP_FILES = { "service_bytes": "memory.current", "peak_bytes": "memory.peak", "swap_bytes": "memory.swap.current", "memory_events": "memory.events", "memory_psi": "memory.pressure", "tasks": "pids.current", "pids_events": "pids.events", } FIELDS = ("utc", "monotonic_ns", "phase", "host_available_bytes", "host_psi", *CGROUP_FILES, "errors") class HostRecorder: def __init__(self, stream): self.stream = stream self.writer = csv.DictWriter(stream, FIELDS) self.writer.writeheader() stream.flush() def record(self, group_fd, phase="sample"): """group_fd pins one cgroup instance, even if systemd reuses its name.""" row = {"utc": dt.datetime.now(dt.timezone.utc).isoformat(), "monotonic_ns": time.monotonic_ns(), "phase": phase} errors = [] try: meminfo = Path("/proc/meminfo").read_text().splitlines() available = next(line for line in meminfo if line.startswith("MemAvailable:")) row["host_available_bytes"] = int(available.split()[1]) * 1024 except (OSError, StopIteration, ValueError, IndexError) as exc: errors.append(f"MemAvailable: {type(exc).__name__}") try: row["host_psi"] = "|".join(Path("/proc/pressure/memory").read_text().splitlines()) except OSError as exc: errors.append(f"host PSI: {exc.strerror}") if group_fd is None: errors.append("awaiting cgroup") elif os.fstat(group_fd).st_nlink == 0: errors.append("cgroup removed") else: for key, name in CGROUP_FILES.items(): try: with os.fdopen(os.open(name, os.O_RDONLY, dir_fd=group_fd)) as item: row[key] = "|".join(item.read().splitlines()) except OSError as exc: errors.append(f"{name}: {exc.strerror}") row["errors"] = "|".join(errors) self.writer.writerow(row) self.stream.flush() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("cgroup", type=Path) parser.add_argument("--seconds", type=int, default=90) args = parser.parse_args() if args.seconds < 1: parser.error("--seconds must be positive") fd = os.open(args.cgroup, os.O_RDONLY | os.O_DIRECTORY) try: recorder = HostRecorder(sys.stdout) deadline = time.monotonic() + args.seconds while time.monotonic() < deadline: recorder.record(fd) if os.fstat(fd).st_nlink == 0: break time.sleep(min(1, max(0, deadline - time.monotonic()))) recorder.record(fd, "final") finally: os.close(fd) if __name__ == "__main__": main()