diff options
| author | ghptc <pittacgh@gmail.com> | 2026-11-28 11:35:18 -0300 |
|---|---|---|
| committer | ghptc <pittacgh@gmail.com> | 2026-11-28 16:51:45 -0300 |
| commit | 0822119d1b63d5bdff458e15f8ea835059844349 (patch) | |
| tree | 48da56c5622e66c56524bb3f206c8d3338904db9 /scripts/linux_cgroup_sample.py | |
| parent | 923e38cc8c92cd1c42090076382138538f2bb487 (diff) | |
Record Linux trial memory from outside the workload cgroup
Diffstat (limited to 'scripts/linux_cgroup_sample.py')
| -rw-r--r-- | scripts/linux_cgroup_sample.py | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/scripts/linux_cgroup_sample.py b/scripts/linux_cgroup_sample.py new file mode 100644 index 00000000..3316ae4d --- /dev/null +++ b/scripts/linux_cgroup_sample.py | |||
| @@ -0,0 +1,87 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Record host and cgroup v2 memory from a process outside the measured unit. | ||
| 3 | |||
| 4 | python3 scripts/linux_cgroup_sample.py /sys/fs/cgroup/.../trial.service --seconds 90 > host.csv | ||
| 5 | """ | ||
| 6 | import argparse | ||
| 7 | import csv | ||
| 8 | import datetime as dt | ||
| 9 | import os | ||
| 10 | from pathlib import Path | ||
| 11 | import sys | ||
| 12 | import time | ||
| 13 | |||
| 14 | |||
| 15 | CGROUP_FILES = { | ||
| 16 | "service_bytes": "memory.current", | ||
| 17 | "peak_bytes": "memory.peak", | ||
| 18 | "swap_bytes": "memory.swap.current", | ||
| 19 | "memory_events": "memory.events", | ||
| 20 | "memory_psi": "memory.pressure", | ||
| 21 | "tasks": "pids.current", | ||
| 22 | "pids_events": "pids.events", | ||
| 23 | } | ||
| 24 | FIELDS = ("utc", "monotonic_ns", "phase", "host_available_bytes", "host_psi", *CGROUP_FILES, "errors") | ||
| 25 | |||
| 26 | |||
| 27 | class HostRecorder: | ||
| 28 | def __init__(self, stream): | ||
| 29 | self.stream = stream | ||
| 30 | self.writer = csv.DictWriter(stream, FIELDS) | ||
| 31 | self.writer.writeheader() | ||
| 32 | stream.flush() | ||
| 33 | |||
| 34 | def record(self, group_fd, phase="sample"): | ||
| 35 | """group_fd pins one cgroup instance, even if systemd reuses its name.""" | ||
| 36 | row = {"utc": dt.datetime.now(dt.timezone.utc).isoformat(), | ||
| 37 | "monotonic_ns": time.monotonic_ns(), "phase": phase} | ||
| 38 | errors = [] | ||
| 39 | try: | ||
| 40 | meminfo = Path("/proc/meminfo").read_text().splitlines() | ||
| 41 | available = next(line for line in meminfo if line.startswith("MemAvailable:")) | ||
| 42 | row["host_available_bytes"] = int(available.split()[1]) * 1024 | ||
| 43 | except (OSError, StopIteration, ValueError, IndexError) as exc: | ||
| 44 | errors.append(f"MemAvailable: {type(exc).__name__}") | ||
| 45 | try: | ||
| 46 | row["host_psi"] = "|".join(Path("/proc/pressure/memory").read_text().splitlines()) | ||
| 47 | except OSError as exc: | ||
| 48 | errors.append(f"host PSI: {exc.strerror}") | ||
| 49 | if group_fd is None: | ||
| 50 | errors.append("awaiting cgroup") | ||
| 51 | elif os.fstat(group_fd).st_nlink == 0: | ||
| 52 | errors.append("cgroup removed") | ||
| 53 | else: | ||
| 54 | for key, name in CGROUP_FILES.items(): | ||
| 55 | try: | ||
| 56 | with os.fdopen(os.open(name, os.O_RDONLY, dir_fd=group_fd)) as item: | ||
| 57 | row[key] = "|".join(item.read().splitlines()) | ||
| 58 | except OSError as exc: | ||
| 59 | errors.append(f"{name}: {exc.strerror}") | ||
| 60 | row["errors"] = "|".join(errors) | ||
| 61 | self.writer.writerow(row) | ||
| 62 | self.stream.flush() | ||
| 63 | |||
| 64 | |||
| 65 | def main(): | ||
| 66 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 67 | parser.add_argument("cgroup", type=Path) | ||
| 68 | parser.add_argument("--seconds", type=int, default=90) | ||
| 69 | args = parser.parse_args() | ||
| 70 | if args.seconds < 1: | ||
| 71 | parser.error("--seconds must be positive") | ||
| 72 | fd = os.open(args.cgroup, os.O_RDONLY | os.O_DIRECTORY) | ||
| 73 | try: | ||
| 74 | recorder = HostRecorder(sys.stdout) | ||
| 75 | deadline = time.monotonic() + args.seconds | ||
| 76 | while time.monotonic() < deadline: | ||
| 77 | recorder.record(fd) | ||
| 78 | if os.fstat(fd).st_nlink == 0: | ||
| 79 | break | ||
| 80 | time.sleep(min(1, max(0, deadline - time.monotonic()))) | ||
| 81 | recorder.record(fd, "final") | ||
| 82 | finally: | ||
| 83 | os.close(fd) | ||
| 84 | |||
| 85 | |||
| 86 | if __name__ == "__main__": | ||
| 87 | main() | ||