upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts/linux_cgroup_sample.py
blob: 3316ae4d00dd2d2449a67b1d49d73c245af3db6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/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()