Record Linux trial memory from outside the workload cgroup
This commit is contained in:
@ -45,6 +45,24 @@ env GAMEID=umu-default \
|
||||
Logs are in the prefix, under
|
||||
`drive_c/users/steamuser/AppData/Local/victory/logs`.
|
||||
|
||||
### Recording memory during a systemd user service
|
||||
|
||||
While the service is active, run the sampler from a separate terminal outside
|
||||
its cgroup. Substitute the unit name used for the trial.
|
||||
|
||||
```sh
|
||||
unit=example-trial.service
|
||||
group=$(systemctl --user show --property=ControlGroup --value "$unit")
|
||||
test -n "$group" && python3 scripts/linux_cgroup_sample.py "/sys/fs/cgroup$group" --seconds 90 > host.csv
|
||||
```
|
||||
|
||||
The sampler flushes a CSV row each second with host available memory, host and
|
||||
service memory pressure, service memory, swap, task counts and controller
|
||||
events. It reads procfs and cgroup v2 independently of Wine and GPU tools.
|
||||
Missing controller values have an empty field and a reason in `errors`. A
|
||||
directory descriptor pins the original service instance through removal. UTC
|
||||
and monotonic timestamps support comparison with the journal on the same boot.
|
||||
|
||||
## Shader compiler crash with proton-cachyos
|
||||
|
||||
| Proton | vkd3d-proton | What happened |
|
||||
|
||||
87
scripts/linux_cgroup_sample.py
Normal file
87
scripts/linux_cgroup_sample.py
Normal file
@ -0,0 +1,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()
|
||||
62
tests/linux/test_cgroup_sample.py
Normal file
62
tests/linux/test_cgroup_sample.py
Normal file
@ -0,0 +1,62 @@
|
||||
import csv
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))
|
||||
from linux_cgroup_sample import CGROUP_FILES, HostRecorder
|
||||
|
||||
|
||||
class HostRecorderTests(unittest.TestCase):
|
||||
def test_partial_controller_read_does_not_drop_host_row(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
group = Path(tmp)
|
||||
(group / "memory.events").write_text("high 42\noom 0\n")
|
||||
fd = os.open(group, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
stream = io.StringIO()
|
||||
recorder = HostRecorder(stream)
|
||||
recorder.record(None)
|
||||
recorder.record(fd)
|
||||
rows = list(csv.DictReader(io.StringIO(stream.getvalue())))
|
||||
finally:
|
||||
os.close(fd)
|
||||
self.assertEqual(rows[0]["errors"], "awaiting cgroup")
|
||||
self.assertGreater(int(rows[1]["host_available_bytes"]), 0)
|
||||
self.assertEqual(rows[1]["memory_events"], "high 42|oom 0")
|
||||
self.assertEqual(rows[1]["service_bytes"], "")
|
||||
self.assertIn("memory.current:", rows[1]["errors"])
|
||||
|
||||
def test_final_row_cannot_read_replacement_group(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
group = Path(tmp) / "unit"
|
||||
group.mkdir()
|
||||
fd = os.open(group, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
stream = io.StringIO()
|
||||
recorder = HostRecorder(stream)
|
||||
for name in CGROUP_FILES.values():
|
||||
(group / name).write_text("0\n")
|
||||
recorder.record(fd)
|
||||
for item in group.iterdir():
|
||||
item.unlink()
|
||||
group.rmdir()
|
||||
group.mkdir()
|
||||
(group / "memory.current").write_text("123\n")
|
||||
recorder.record(fd, "final")
|
||||
before, after = csv.DictReader(io.StringIO(stream.getvalue()))
|
||||
finally:
|
||||
os.close(fd)
|
||||
self.assertEqual(before["errors"], "")
|
||||
self.assertEqual(before["service_bytes"], "0")
|
||||
self.assertEqual(after["phase"], "final")
|
||||
self.assertEqual(after["service_bytes"], "")
|
||||
self.assertEqual(after["errors"], "cgroup removed")
|
||||
self.assertGreater(int(after["monotonic_ns"]), int(before["monotonic_ns"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user