Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions gateway/shutdown_forensics.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,12 +342,18 @@ def check_systemd_timing_alignment(drain_timeout: float) -> Optional[Dict[str, A

# Try to identify our unit name and ask systemctl for its config.
unit_name: Optional[str] = None
systemd_scope: Optional[str] = None
try:
# /proc/self/cgroup gives us "0::/user.slice/.../hermes-gateway.service"
with open("/proc/self/cgroup", encoding="utf-8") as fh:
for line in fh:
# systemd cgroup line ends with the unit name
if ".service" in line:
cgroup_path = line.strip().split(":", 2)[-1]
if cgroup_path.startswith("/system.slice/"):
systemd_scope = "system"
elif cgroup_path.startswith("/user.slice/"):
systemd_scope = "user"
parts = line.strip().split("/")
for p in reversed(parts):
if p.endswith(".service"):
Expand All @@ -360,11 +366,19 @@ def check_systemd_timing_alignment(drain_timeout: float) -> Optional[Dict[str, A
if not unit_name:
return None

# Query systemctl for TimeoutStopUSec. Use --user OR system depending
# on which manager actually owns the unit. Try user first since
# that's the common case for hermes.
# Query systemctl for TimeoutStopUSec. Use the manager identified by
# /proc/self/cgroup when possible: systemctl --user can return exit 0 plus
# a default TimeoutStopUSec for unknown units, so probing it first causes
# false stale-unit warnings for system-scope services (#61003).
timeout_us: Optional[int] = None
for flag in (["--user"], []):
if systemd_scope == "system":
scope_flags = ([],)
elif systemd_scope == "user":
scope_flags = (["--user"],)
else:
scope_flags = (["--user"], [])

for flag in scope_flags:
try:
result = subprocess.run(
["systemctl", *flag, "show", unit_name, "--property=TimeoutStopUSec"],
Expand Down
50 changes: 50 additions & 0 deletions tests/gateway/test_shutdown_forensics.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
import os
import signal
import subprocess
import sys
import time
from pathlib import Path
Expand Down Expand Up @@ -248,3 +249,52 @@ def test_returns_none_when_unit_undeterminable(self, monkeypatch):
# for whatever unit pytest IS in. Both are valid; we just ensure
# the function doesn't raise.
assert result is None or isinstance(result, dict)

def test_system_scope_cgroup_skips_phantom_user_unit(self, monkeypatch):
"""A system-scope unit must not trust systemctl --user's default row.

systemctl --user show can return success plus TimeoutStopUSec=90s even
for an unknown user unit. If /proc/self/cgroup says this process is in
/system.slice, the check should query the system manager directly.
"""
monkeypatch.setenv("INVOCATION_ID", "abc")

cgroup = "0::/system.slice/hermes-gateway-duke.service\n"
real_open = open

def fake_open(path, *args, **kwargs):
if path == "/proc/self/cgroup":
from io import StringIO

return StringIO(cgroup)
return real_open(path, *args, **kwargs)

calls = []

def fake_run(cmd, **_kwargs):
calls.append(cmd)
if "--user" in cmd:
return subprocess.CompletedProcess(
cmd, 0, stdout="TimeoutStopUSec=1min 30s\n", stderr=""
)
return subprocess.CompletedProcess(
cmd, 0, stdout="TimeoutStopUSec=4min\n", stderr=""
)

monkeypatch.setattr("builtins.open", fake_open)
monkeypatch.setattr(sf.subprocess, "run", fake_run)

result = sf.check_systemd_timing_alignment(180.0)

assert result is not None
assert result["unit"] == "hermes-gateway-duke.service"
assert result["timeout_stop_sec"] == 240.0
assert result["mismatch"] is False
assert calls == [
[
"systemctl",
"show",
"hermes-gateway-duke.service",
"--property=TimeoutStopUSec",
]
]