mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
Add enhanced one-session diagnostic bundles
This commit is contained in:
1 parent
b563b8d1eb
commit
5614bd5d5a
32 files changed
+3100
-141
No files matched your search
@@ -0,0 +1,234 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "tools/linuxfs/overlay/usr/local/bin/droiddeck-diagnostic-inventory"
|
||||
MODULE = runpy.run_path(str(SCRIPT), run_name="droiddeck_diagnostic_inventory")
|
||||
|
||||
|
||||
def write_process(root, pid, ppid, start, comm, cmdline, maps=None):
|
||||
process = root / str(pid)
|
||||
process.mkdir(parents=True)
|
||||
children = process / "task" / str(pid) / "children"
|
||||
children.parent.mkdir(parents=True)
|
||||
children.write_text("")
|
||||
fields = ["S", str(ppid)] + ["0"] * 17 + [str(start)]
|
||||
(process / "stat").write_text(f"{pid} ({comm}) " + " ".join(fields) + "\n")
|
||||
(process / "comm").write_text(comm + "\n")
|
||||
(process / "cmdline").write_bytes(cmdline.replace(" ", "\0").encode() + b"\0")
|
||||
if maps is not None:
|
||||
(process / "maps").write_text("".join(
|
||||
f"1000-2000 r-xp 00000000 00:00 0 {path}\n" for path in maps
|
||||
))
|
||||
parent_children = root / str(ppid) / "task" / str(ppid) / "children"
|
||||
if parent_children.is_file():
|
||||
existing = parent_children.read_text().split()
|
||||
if str(pid) not in existing:
|
||||
parent_children.write_text(" ".join(existing + [str(pid)]) + "\n")
|
||||
return process
|
||||
|
||||
|
||||
def rows(text):
|
||||
prefix = MODULE["PREFIX"]
|
||||
return [json.loads(line.removeprefix(prefix)) for line in text.splitlines() if line.startswith(prefix)]
|
||||
|
||||
|
||||
class DiagnosticInventoryTest(unittest.TestCase):
|
||||
def test_default_off_produces_no_output(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = io.StringIO()
|
||||
result = MODULE["main"](
|
||||
["--once", "--root-pid", "100", "--proc-root", directory], {}, output,
|
||||
)
|
||||
self.assertEqual(result, 0)
|
||||
self.assertEqual(output.getvalue(), "")
|
||||
|
||||
def test_once_scopes_processes_and_reports_only_safe_graphics_identity(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
proc = Path(directory)
|
||||
write_process(proc, 100, 1, 10, "droiddeck-session", "/usr/local/bin/droiddeck-session steam", [
|
||||
"/usr/lib/libvulkan.so.1",
|
||||
])
|
||||
write_process(proc, 101, 100, 11, "steam", "/secret/account/steam -login private-token", [
|
||||
"/data/user/0/com.droiddeck.launcher/files/components/system-vulkan/abc/libVkLayer_hybris_compat.so",
|
||||
"/data/user/0/com.droiddeck.launcher/files/components/system-vulkan/abc/libvulkan-private-account.so",
|
||||
"/data/user/0/com.droiddeck.launcher/files/components/system-vulkan/abc/libdrm_accountSecret.so",
|
||||
"/data/user/0/com.droiddeck.launcher/files/components/system-vulkan/abc/libxcb-sessionSecret.so",
|
||||
"/data/user/0/com.droiddeck.launcher/files/components/system-vulkan/abc/libvkd3d-userSecret.so",
|
||||
"/data/user/0/com.droiddeck.launcher/files/components/system-vulkan/abc/libdrm_amdgpu.so.1.0.0",
|
||||
"/home/private-user/not-graphics-secret.so",
|
||||
"/home/private-user/libvulkan-private-user.so",
|
||||
])
|
||||
write_process(proc, 102, 101, 12, "steamwebhelper", "steamwebhelper --user-data-dir=/secret/profile", [
|
||||
"/vendor/lib64/hw/vulkan.samsung.so",
|
||||
"/tmp/libvulkan-secret with spaces.so",
|
||||
])
|
||||
write_process(proc, 103, 101, 13, "private-game-title", "private-game-title --token=child-secret", [])
|
||||
write_process(proc, 200, 1, 20, "unrelated", "unrelated --password=hunter2", [
|
||||
"/vendor/lib64/hw/vulkan.unrelated.so",
|
||||
])
|
||||
output = io.StringIO()
|
||||
MODULE["main"](
|
||||
["--once", "--root-pid", "100", "--proc-root", directory],
|
||||
{"DROIDDECK_ENHANCED_DIAGNOSTICS": "1"}, output,
|
||||
)
|
||||
payloads = rows(output.getvalue())
|
||||
self.assertEqual(payloads[0]["event"], "provider")
|
||||
snapshot = payloads[1]
|
||||
self.assertEqual(snapshot["alive"], 4)
|
||||
self.assertEqual(snapshot["roles"], {
|
||||
"game-or-helper": 1, "session": 1, "steam-client": 1, "steam-webhelper": 1,
|
||||
})
|
||||
self.assertEqual(snapshot["providerStatus"], "available")
|
||||
self.assertEqual(snapshot["scopeMethod"], "children")
|
||||
self.assertFalse(snapshot["scopeIncomplete"])
|
||||
libraries = {(item["name"], item["origin"]) for item in snapshot["libraries"]}
|
||||
self.assertIn(("libvulkan.so.1", "guest-runtime"), libraries)
|
||||
self.assertIn(("libVkLayer_hybris_compat.so", "droiddeck-component"), libraries)
|
||||
self.assertIn(("libdrm_amdgpu.so.1.0.0", "droiddeck-component"), libraries)
|
||||
self.assertIn(("vulkan.samsung.so", "android-vendor"), libraries)
|
||||
self.assertTrue(any(name.startswith("sha256:") and origin == "other" for name, origin in libraries))
|
||||
self.assertGreaterEqual(sum(name.startswith("sha256:") and origin == "droiddeck-component"
|
||||
for name, origin in libraries), 4)
|
||||
text = output.getvalue()
|
||||
for secret in ("private-token", "private-user", "child-secret", "private-game-title", "hunter2",
|
||||
"accountSecret", "sessionSecret", "userSecret", "unrelated", "/vendor/", "/data/user/"):
|
||||
self.assertNotIn(secret, text)
|
||||
|
||||
def test_missing_maps_and_proc_are_explicit(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
proc = Path(directory)
|
||||
write_process(proc, 100, 1, 10, "droiddeck-session", "droiddeck-session")
|
||||
collector = MODULE["Collector"](proc, 100)
|
||||
snapshot, _ = collector.scan()
|
||||
self.assertEqual(snapshot["maps"]["unavailable"], 1)
|
||||
self.assertEqual(snapshot["providerStatus"], "available")
|
||||
missing = MODULE["Collector"](proc / "missing", 100)
|
||||
snapshot, _ = missing.scan()
|
||||
self.assertEqual(snapshot["providerStatus"], "proc-unavailable")
|
||||
|
||||
def test_children_fallback_is_explicitly_incomplete(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
proc = Path(directory)
|
||||
process = write_process(proc, 100, 1, 10, "droiddeck-session", "droiddeck-session", [])
|
||||
write_process(proc, 101, 100, 11, "steam", "steam", [])
|
||||
(process / "task" / "100" / "children").unlink()
|
||||
collector = MODULE["Collector"](proc, 100)
|
||||
snapshot, _ = collector.scan()
|
||||
self.assertEqual(snapshot["alive"], 2)
|
||||
self.assertEqual(snapshot["scopeMethod"], "children+scan-fallback")
|
||||
self.assertTrue(snapshot["scopeIncomplete"])
|
||||
|
||||
def test_pid_reuse_is_an_exit_and_a_new_process(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
proc = Path(directory)
|
||||
write_process(proc, 99, 1, 9, "droiddeck-session", "droiddeck-session", [])
|
||||
process = write_process(proc, 100, 99, 10, "steam", "steam", [])
|
||||
collector = MODULE["Collector"](proc, 99)
|
||||
first, _ = collector.scan()
|
||||
first_token = next(row["token"] for row in first["started"] if row["role"] == "steam-client")
|
||||
fields = ["S", "99"] + ["0"] * 17 + ["20"]
|
||||
(process / "stat").write_text("100 (steam) " + " ".join(fields) + "\n")
|
||||
second, changed = collector.scan()
|
||||
self.assertTrue(changed)
|
||||
self.assertEqual(next(row["token"] for row in second["exited"] if row["role"] == "steam-client"), first_token)
|
||||
self.assertNotEqual(
|
||||
next(row["token"] for row in second["started"] if row["role"] == "steam-client"), first_token,
|
||||
)
|
||||
|
||||
def test_exec_role_change_is_reported_without_pid_reuse(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
proc = Path(directory)
|
||||
process = write_process(proc, 100, 1, 10, "droiddeck-session", "droiddeck-session", [])
|
||||
collector = MODULE["Collector"](proc, 100)
|
||||
collector.scan()
|
||||
(process / "comm").write_text("gamescope\n")
|
||||
(process / "cmdline").write_bytes(b"gamescope\0--backend\0wayland\0")
|
||||
snapshot, changed = collector.scan()
|
||||
self.assertTrue(changed)
|
||||
self.assertEqual(snapshot["roles"], {"gamescope": 1})
|
||||
|
||||
def test_process_scope_is_bounded(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
proc = Path(directory)
|
||||
write_process(proc, 100, 1, 10, "droiddeck-session", "droiddeck-session", [])
|
||||
for pid in range(101, 370):
|
||||
write_process(proc, pid, 100, pid, "helper", "helper", [])
|
||||
collector = MODULE["Collector"](proc, 100)
|
||||
snapshot, _ = collector.scan()
|
||||
self.assertLessEqual(snapshot["alive"], MODULE["MAX_PROCESSES"])
|
||||
self.assertTrue(snapshot["scopeCapped"])
|
||||
|
||||
def test_reused_root_pid_is_not_adopted(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
proc = Path(directory)
|
||||
process = write_process(proc, 100, 1, 10, "droiddeck-session", "droiddeck-session", [])
|
||||
collector = MODULE["Collector"](proc, 100)
|
||||
collector.scan()
|
||||
fields = ["S", "1"] + ["0"] * 17 + ["20"]
|
||||
(process / "stat").write_text("100 (unrelated-app) " + " ".join(fields) + "\n")
|
||||
snapshot, _ = collector.scan()
|
||||
self.assertEqual(snapshot["providerStatus"], "root-reused")
|
||||
self.assertEqual(snapshot["alive"], 0)
|
||||
self.assertNotIn("unrelated-app", json.dumps(snapshot))
|
||||
|
||||
def test_reparented_child_is_rejected_after_process_reads(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
proc = Path(directory)
|
||||
write_process(proc, 100, 1, 10, "droiddeck-session", "droiddeck-session", [])
|
||||
child = write_process(proc, 101, 100, 11, "steam", "steam", [])
|
||||
globals_ = MODULE["Collector"].scan.__globals__
|
||||
original = globals_["process_stat"]
|
||||
calls = 0
|
||||
|
||||
def racing(path):
|
||||
nonlocal calls
|
||||
if path == child / "stat":
|
||||
calls += 1
|
||||
if calls == 3:
|
||||
fields = ["S", "1"] + ["0"] * 17 + ["11"]
|
||||
path.write_text("101 (steam) " + " ".join(fields) + "\n")
|
||||
return original(path)
|
||||
|
||||
globals_["process_stat"] = racing
|
||||
try:
|
||||
collector = MODULE["Collector"](proc, 100)
|
||||
snapshot, _ = collector.scan()
|
||||
finally:
|
||||
globals_["process_stat"] = original
|
||||
self.assertEqual(snapshot["roles"], {"session": 1})
|
||||
self.assertEqual(snapshot["alive"], 1)
|
||||
|
||||
def test_watch_is_bounded_and_emits_heartbeats_without_process_changes(self):
|
||||
globals_ = MODULE["main"].__globals__
|
||||
original = globals_["HEARTBEAT_MS"]
|
||||
globals_["HEARTBEAT_MS"] = 40
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
proc = Path(directory)
|
||||
write_process(proc, 100, 1, 10, "droiddeck-session", "droiddeck-session", [])
|
||||
output = io.StringIO()
|
||||
MODULE["main"](
|
||||
["--watch", "--root-pid", "100", "--proc-root", directory,
|
||||
"--interval-ms", "250", "--duration-ms", "520", "--max-records", "4"],
|
||||
{"DROIDDECK_ENHANCED_DIAGNOSTICS": "1"}, output,
|
||||
)
|
||||
payloads = rows(output.getvalue())
|
||||
self.assertEqual(payloads[0]["event"], "provider")
|
||||
self.assertEqual(payloads[1]["event"], "snapshot")
|
||||
self.assertEqual(payloads[2]["event"], "heartbeat")
|
||||
self.assertNotIn("libraries", payloads[2])
|
||||
self.assertTrue(payloads[2]["librariesUnchanged"])
|
||||
self.assertLessEqual(len(payloads), 4)
|
||||
finally:
|
||||
globals_["HEARTBEAT_MS"] = original
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,50 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
|
||||
|
||||
class DiagnosticSessionIntegrationTest(unittest.TestCase):
|
||||
def run_inventory(self, enabled, inside=False, installed=True):
|
||||
source = SESSION.read_text()
|
||||
match = re.search(r'^start_diagnostic_inventory\(\) \{\n.*?^\}\n', source, re.M | re.S)
|
||||
self.assertIsNotNone(match)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
marker = root / 'called'
|
||||
if installed:
|
||||
helper = root / 'droiddeck-diagnostic-inventory'
|
||||
helper.write_text('#!/bin/bash\nprintf "%s\\n" "$@" > "$MARKER"\n')
|
||||
helper.chmod(0o755)
|
||||
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
|
||||
MARKER=str(marker), DROIDDECK_ENHANCED_DIAGNOSTICS='1' if enabled else '0')
|
||||
env['BL_INSIDE'] = '1' if inside else ''
|
||||
script = match.group() + '\nstart_diagnostic_inventory\n'
|
||||
if installed and enabled and not inside:
|
||||
script += 'wait "$_bl_diagnostic_inventory"\n'
|
||||
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
return marker.read_text().splitlines() if marker.exists() else [], result.stdout
|
||||
|
||||
def test_starts_for_an_enhanced_outer_session(self):
|
||||
arguments, _ = self.run_inventory(True)
|
||||
self.assertEqual(arguments[:2], ['--watch', '--root-pid'])
|
||||
self.assertTrue(arguments[2].isdigit())
|
||||
|
||||
def test_does_not_start_when_disabled_or_inside_gamescope(self):
|
||||
self.assertEqual(self.run_inventory(False)[0], [])
|
||||
self.assertEqual(self.run_inventory(True, inside=True)[0], [])
|
||||
|
||||
def test_reports_when_the_provider_is_not_installed(self):
|
||||
_, output = self.run_inventory(True, installed=False)
|
||||
self.assertIn('DROIDDECK_PROCESS_TRACE', output)
|
||||
self.assertIn('"status":"unavailable"', output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,186 @@
|
||||
import contextlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from unittest import mock
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
GAME_ENV = BIN / "droiddeck-game-env"
|
||||
MODULE = runpy.run_path(str(GAME_ENV))
|
||||
|
||||
|
||||
class GameExitDiagnosticsTest(unittest.TestCase):
|
||||
def run_child(self, body, app_id="42"):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
status = MODULE["start"](
|
||||
[sys.executable, "-c", body], os.environ.copy(), None,
|
||||
diagnostic_app_id=app_id,
|
||||
)
|
||||
return status, said.getvalue()
|
||||
|
||||
def test_clean_and_nonzero_exits_are_authoritative(self):
|
||||
for child_status in (0, 7):
|
||||
with self.subTest(status=child_status):
|
||||
status, said = self.run_child("import sys; sys.exit(%d)" % child_status)
|
||||
self.assertEqual(status, child_status)
|
||||
self.assertIn("event=game_start app_id=42", said)
|
||||
self.assertIn(
|
||||
"event=game_exit app_id=42 raw_status=%d normalized_status=%d wrapper_status=%d signal=0" %
|
||||
(child_status, child_status, child_status), said,
|
||||
)
|
||||
|
||||
def test_signal_exit_is_normalized_and_records_the_signal(self):
|
||||
status, said = self.run_child("import os, signal; os.kill(os.getpid(), signal.SIGTERM)")
|
||||
self.assertEqual(status, 128 + signal.SIGTERM)
|
||||
self.assertIn(
|
||||
"event=game_exit app_id=42 raw_status=-15 normalized_status=143 wrapper_status=143 signal=15", said,
|
||||
)
|
||||
|
||||
def test_xbox_exit_is_recorded_without_inventing_a_start(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
MODULE["diagnostic_game_exit"]("42", -signal.SIGTERM, "xbox", 241)
|
||||
self.assertNotIn("event=game_start", said.getvalue())
|
||||
self.assertIn(
|
||||
"event=game_exit app_id=42 raw_status=-15 normalized_status=143 wrapper_status=241 signal=15 source=xbox",
|
||||
said.getvalue(),
|
||||
)
|
||||
|
||||
def test_signal_handler_forwards_to_the_child(self):
|
||||
class Process:
|
||||
def __init__(self):
|
||||
self.forwarded = []
|
||||
|
||||
def send_signal(self, signum):
|
||||
self.forwarded.append(signum)
|
||||
|
||||
def wait(self):
|
||||
os.kill(os.getpid(), signal.SIGTERM)
|
||||
return -signal.SIGTERM
|
||||
|
||||
process = Process()
|
||||
self.assertEqual(MODULE["wait_forwarding_signals"](process), 128 + signal.SIGTERM)
|
||||
self.assertEqual(process.forwarded, [signal.SIGTERM])
|
||||
|
||||
def test_default_path_still_execs_in_place_without_diagnostic_output(self):
|
||||
called = []
|
||||
with mock.patch("os.execvpe", side_effect=lambda *args: called.append(args)), \
|
||||
contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
MODULE["start"](["/game", "arg"], {"A": "B"}, None)
|
||||
self.assertEqual(called, [("/game", ["/game", "arg"], {"A": "B"})])
|
||||
self.assertNotIn("DROIDDECK_DIAGNOSTICS", said.getvalue())
|
||||
|
||||
def test_failed_selected_launch_does_not_invent_a_start_or_exit(self):
|
||||
with mock.patch("subprocess.Popen", side_effect=FileNotFoundError("missing")), \
|
||||
contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
with self.assertRaises(FileNotFoundError):
|
||||
MODULE["start"](["/missing"], {}, None, diagnostic_app_id="42")
|
||||
self.assertNotIn("DROIDDECK_DIAGNOSTICS", said.getvalue())
|
||||
|
||||
def test_cleanup_runs_after_a_diagnostic_child(self):
|
||||
cleaned = []
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
status = MODULE["start"](
|
||||
[sys.executable, "-c", "pass"], os.environ.copy(), None,
|
||||
after=lambda: cleaned.append(True), diagnostic_app_id="42",
|
||||
)
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(cleaned, [True])
|
||||
|
||||
def test_diagnostic_install_script_keeps_success_recording(self):
|
||||
recorded = []
|
||||
with mock.patch.dict(MODULE["start"].__globals__, record_install_scripts=lambda digest, env: recorded.append((digest, env))), \
|
||||
contextlib.redirect_stderr(io.StringIO()):
|
||||
status = MODULE["start"](
|
||||
[sys.executable, "-c", "pass"], {"CUSTOM": "kept"}, "digest",
|
||||
diagnostic_app_id="42",
|
||||
)
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(recorded, [("digest", {"CUSTOM": "kept"})])
|
||||
|
||||
def test_cleanup_path_keeps_the_original_install_recording_precedence(self):
|
||||
recorded = []
|
||||
with mock.patch.dict(MODULE["start"].__globals__, record_install_scripts=lambda digest, env: recorded.append((digest, env))):
|
||||
status = MODULE["start"](
|
||||
[sys.executable, "-c", "pass"], {"CUSTOM": "kept"}, "digest",
|
||||
after=lambda: None,
|
||||
)
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(recorded, [])
|
||||
|
||||
def test_main_only_traces_valid_waitforexitandrun_games(self):
|
||||
with tempfile.TemporaryDirectory(prefix="game-exit-diagnostics-") as directory:
|
||||
root = Path(directory)
|
||||
probe = root / "probe"
|
||||
probe.write_text("#!" + sys.executable + "\nimport sys\nsys.exit(7)\n")
|
||||
probe.chmod(0o755)
|
||||
base = dict(os.environ, HOME=directory, PATH=os.defpath,
|
||||
DROIDDECK_ENHANCED_DIAGNOSTICS="1")
|
||||
valid = subprocess.run(
|
||||
[sys.executable, str(GAME_ENV), str(probe), "waitforexitandrun"],
|
||||
env={**base, "STEAM_COMPAT_DATA_PATH": "/compatdata/42"},
|
||||
capture_output=True, text=True, timeout=15,
|
||||
)
|
||||
self.assertEqual(valid.returncode, 7, valid.stderr)
|
||||
self.assertIn("event=game_start app_id=42", valid.stderr)
|
||||
self.assertIn(
|
||||
"event=game_exit app_id=42 raw_status=7 normalized_status=7 wrapper_status=7 signal=0", valid.stderr,
|
||||
)
|
||||
|
||||
for verb, prefix in (("run", "/compatdata/42"), ("waitforexitandrun", "/compatdata/not-a-game")):
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(GAME_ENV), str(probe), verb],
|
||||
env={**base, "STEAM_COMPAT_DATA_PATH": prefix},
|
||||
capture_output=True, text=True, timeout=15,
|
||||
)
|
||||
self.assertEqual(result.returncode, 7, result.stderr)
|
||||
self.assertNotIn("DROIDDECK_DIAGNOSTICS", result.stderr)
|
||||
|
||||
def test_main_records_xbox_result_without_changing_it(self):
|
||||
launch = lambda command, env: 23
|
||||
with tempfile.TemporaryDirectory(prefix="xbox-exit-diagnostics-") as directory, \
|
||||
mock.patch.dict(os.environ, {
|
||||
"HOME": directory,
|
||||
"PATH": os.defpath,
|
||||
"STEAM_COMPAT_DATA_PATH": "/compatdata/42",
|
||||
"DROIDDECK_ENHANCED_DIAGNOSTICS": "1",
|
||||
}, clear=True), \
|
||||
mock.patch("sys.argv", ["droiddeck-game-env", "/proton", "waitforexitandrun", "game.exe"]), \
|
||||
mock.patch("runpy.run_path", return_value={"launch": launch}), \
|
||||
contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
status = MODULE["main"]()
|
||||
self.assertEqual(status, 23)
|
||||
self.assertNotIn("event=game_start", said.getvalue())
|
||||
self.assertIn(
|
||||
"event=game_exit app_id=42 raw_status=23 normalized_status=23 wrapper_status=23 signal=0 source=xbox",
|
||||
said.getvalue(),
|
||||
)
|
||||
|
||||
def test_main_preserves_negative_xbox_result_and_reports_wrapper_status(self):
|
||||
launch = lambda command, env: -signal.SIGTERM
|
||||
with tempfile.TemporaryDirectory(prefix="xbox-signal-diagnostics-") as directory, \
|
||||
mock.patch.dict(os.environ, {
|
||||
"HOME": directory,
|
||||
"PATH": os.defpath,
|
||||
"STEAM_COMPAT_DATA_PATH": "/compatdata/42",
|
||||
"DROIDDECK_ENHANCED_DIAGNOSTICS": "1",
|
||||
}, clear=True), \
|
||||
mock.patch("sys.argv", ["droiddeck-game-env", "/proton", "waitforexitandrun", "game.exe"]), \
|
||||
mock.patch("runpy.run_path", return_value={"launch": launch}), \
|
||||
contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
status = MODULE["main"]()
|
||||
self.assertEqual(status, -signal.SIGTERM)
|
||||
self.assertIn(
|
||||
"event=game_exit app_id=42 raw_status=-15 normalized_status=143 wrapper_status=241 signal=15 source=xbox",
|
||||
said.getvalue(),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,133 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PATCH = ROOT / "tools/gamescope/patches/0900-enhanced-frame-diagnostics.patch"
|
||||
|
||||
|
||||
def added_file(patch, name):
|
||||
lines = patch.read_text().splitlines()
|
||||
marker = f"diff --git a/{name} b/{name}"
|
||||
start = lines.index(marker)
|
||||
output = []
|
||||
in_hunk = False
|
||||
for line in lines[start + 1:]:
|
||||
if line.startswith("diff --git "):
|
||||
break
|
||||
if line.startswith("@@"):
|
||||
in_hunk = True
|
||||
elif in_hunk and line.startswith("+") and not line.startswith("+++"):
|
||||
output.append(line[1:])
|
||||
return "\n".join(output) + "\n"
|
||||
|
||||
|
||||
class GamescopeDiagnosticsTest(unittest.TestCase):
|
||||
def test_patch_covers_each_frame_boundary_without_payload_logging(self):
|
||||
text = PATCH.read_text()
|
||||
for path in ("src/wlserver.cpp", "src/steamcompmgr.cpp", "src/Backends/WaylandBackend.cpp"):
|
||||
self.assertIn(f"diff --git a/{path} b/{path}", text)
|
||||
self.assertIn("diff --git a/src/main.cpp b/src/main.cpp", text)
|
||||
self.assertIn("droiddeck::frame_trace::Start();", text)
|
||||
self.assertIn("droiddeck::frame_trace::Tick();", text)
|
||||
self.assertIn("pTraceFocus->focusWindow == w", text)
|
||||
self.assertNotIn("GetFocusForWindow( w ) != nullptr", text)
|
||||
for event in (
|
||||
"X11Damage", "X11DamageCurrent", "X11DamageOther", "SurfaceCommit",
|
||||
"SurfaceCommitBuffer", "SurfaceCommitNoBuffer", "CommitDequeued",
|
||||
"CommitDequeuedCurrent", "CommitDequeuedOther", "ImportSucceeded",
|
||||
"ImportSucceededCurrent", "ImportSucceededOther", "ImportFailed",
|
||||
"ImportFailedCurrent", "ImportFailedOther", "FenceReady", "FenceWaited",
|
||||
"CommitDone", "CommitDoneCurrent", "CommitDoneOther", "BaseLatched",
|
||||
"BaseLatchedCurrent", "BaseLatchedOther",
|
||||
"OutputPresent", "OutputAttach", "OutputDetach",
|
||||
"OutputCommit", "OutputRelease",
|
||||
):
|
||||
self.assertIn(f"Event::{event}", text)
|
||||
header = added_file(PATCH, "src/droiddeck_frame_trace.hpp")
|
||||
self.assertIn('std::getenv( "DROIDDECK_ENHANCED_DIAGNOSTICS" )', header)
|
||||
self.assertIn("DROIDDECK_FRAME_TRACE_FAST_INTERVAL_MS 2000", header)
|
||||
self.assertIn("DROIDDECK_FRAME_TRACE_SLOW_INTERVAL_MS 15000", header)
|
||||
self.assertIn("DROIDDECK_FRAME_TRACE_DURATION_MS 86400000", header)
|
||||
self.assertNotRegex(header, re.compile(r"title|pixel|address|argv", re.I))
|
||||
|
||||
def test_collector_is_default_off_bounded_and_thread_safe(self):
|
||||
compiler = shutil.which(os.environ.get("CXX", "c++"))
|
||||
if not compiler:
|
||||
self.skipTest("a C++ compiler is required")
|
||||
with tempfile.TemporaryDirectory(prefix="gamescope-frame-trace-") as directory:
|
||||
work = Path(directory)
|
||||
(work / "droiddeck_frame_trace.hpp").write_text(
|
||||
added_file(PATCH, "src/droiddeck_frame_trace.hpp"))
|
||||
(work / "trace.cpp").write_text(r'''
|
||||
#include "droiddeck_frame_trace.hpp"
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
int main() {
|
||||
droiddeck::frame_trace::Start();
|
||||
std::vector<std::thread> threads;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
threads.emplace_back([] { for (int n = 0; n < 1000; ++n)
|
||||
droiddeck::frame_trace::RecordWindow(
|
||||
droiddeck::frame_trace::Event::X11Damage,
|
||||
droiddeck::frame_trace::Event::X11DamageCurrent,
|
||||
droiddeck::frame_trace::Event::X11DamageOther,
|
||||
false); });
|
||||
for (auto &thread : threads) thread.join();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(60));
|
||||
droiddeck::frame_trace::Tick();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(70));
|
||||
droiddeck::frame_trace::Tick();
|
||||
droiddeck::frame_trace::Record(droiddeck::frame_trace::Event::SurfaceCommit);
|
||||
droiddeck::frame_trace::RecordWindow(
|
||||
droiddeck::frame_trace::Event::ImportSucceeded,
|
||||
droiddeck::frame_trace::Event::ImportSucceededCurrent,
|
||||
droiddeck::frame_trace::Event::ImportSucceededOther,
|
||||
true);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(70));
|
||||
droiddeck::frame_trace::Tick();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(120));
|
||||
droiddeck::frame_trace::Tick();
|
||||
droiddeck::frame_trace::Record(droiddeck::frame_trace::Event::OutputPresent);
|
||||
droiddeck::frame_trace::Tick();
|
||||
}
|
||||
''')
|
||||
program = work / "trace"
|
||||
built = subprocess.run([
|
||||
compiler, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-pthread",
|
||||
"-DDROIDDECK_FRAME_TRACE_FAST_INTERVAL_MS=50",
|
||||
"-DDROIDDECK_FRAME_TRACE_SLOW_INTERVAL_MS=60",
|
||||
"-DDROIDDECK_FRAME_TRACE_FAST_DURATION_MS=100",
|
||||
"-DDROIDDECK_FRAME_TRACE_DURATION_MS=300",
|
||||
str(work / "trace.cpp"), "-o", str(program),
|
||||
], capture_output=True, text=True)
|
||||
self.assertEqual(0, built.returncode, built.stdout + built.stderr)
|
||||
quiet = subprocess.run([str(program)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(0, quiet.returncode, quiet.stdout + quiet.stderr)
|
||||
self.assertEqual("", quiet.stderr)
|
||||
env = os.environ.copy()
|
||||
env["DROIDDECK_ENHANCED_DIAGNOSTICS"] = "1"
|
||||
traced = subprocess.run([str(program)], env=env, capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(0, traced.returncode, traced.stdout + traced.stderr)
|
||||
self.assertEqual(1, traced.stderr.count("schema=1"))
|
||||
summaries = [line for line in traced.stderr.splitlines() if "t_ms=" in line]
|
||||
self.assertIn("t_ms=0 x11_damage=0", summaries[0])
|
||||
self.assertTrue(any("x11_damage=4000" in line and "x11_damage_current=0" in line and
|
||||
"x11_damage_other=4000" in line and "surface_commit=0" in line
|
||||
for line in summaries[1:]))
|
||||
self.assertTrue(any("surface_commit=1" in line for line in summaries[1:]))
|
||||
self.assertTrue(any("import_ok=1" in line and "import_ok_current=1" in line and
|
||||
"import_ok_other=0" in line for line in summaries[1:]))
|
||||
self.assertIn("t_ms=300", summaries[-1])
|
||||
self.assertIn("output_present=0", summaries[-1])
|
||||
self.assertLessEqual(len(summaries), 5)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -11,7 +11,7 @@ SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/d
|
||||
|
||||
class SteamExitStatusTest(unittest.TestCase):
|
||||
def run_session(self, child_status, compositor_status=0, report=True, report_value=None,
|
||||
stale_status=None):
|
||||
stale_status=None, diagnostics=False, output=False):
|
||||
source = SESSION.read_text()
|
||||
function = re.search(r'^run_gamescope\(\) \(\n.*?^\)\n', source, re.M | re.S)
|
||||
self.assertIsNotNone(function)
|
||||
@@ -31,6 +31,7 @@ class SteamExitStatusTest(unittest.TestCase):
|
||||
child.chmod(0o755)
|
||||
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
|
||||
XDG_RUNTIME_DIR=str(root))
|
||||
env['DROIDDECK_ENHANCED_DIAGNOSTICS'] = '1' if diagnostics else '0'
|
||||
result = subprocess.run(['bash', '-c', function.group() + '\nrun_gamescope "$@"',
|
||||
'session', str(child), str(child_status),
|
||||
str(report_value) if report_value is not None else ''], env=env,
|
||||
@@ -38,7 +39,7 @@ class SteamExitStatusTest(unittest.TestCase):
|
||||
self.assertEqual(list(root.glob('droiddeck-steam-exit.??????')), [])
|
||||
if stale_status is not None:
|
||||
self.assertEqual(stale_file.read_text(), str(stale_status) + '\n')
|
||||
return result.returncode
|
||||
return result if output else result.returncode
|
||||
|
||||
def test_steam_crash_survives_successful_compositor_shutdown(self):
|
||||
self.assertEqual(self.run_session(139), 139)
|
||||
@@ -64,6 +65,21 @@ class SteamExitStatusTest(unittest.TestCase):
|
||||
def test_stale_marker_does_not_affect_a_new_launch(self):
|
||||
self.assertEqual(self.run_session(0, report=False, stale_status=139), 0)
|
||||
|
||||
def test_diagnostics_preserve_separate_steam_and_compositor_statuses(self):
|
||||
result = self.run_session(139, diagnostics=True, output=True)
|
||||
self.assertEqual(result.returncode, 139)
|
||||
self.assertIn('event=session_exit compositor_status=0 steam_status=139', result.stdout)
|
||||
|
||||
def test_diagnostics_report_an_unavailable_child_status(self):
|
||||
result = self.run_session(0, compositor_status=1, report=False, diagnostics=True, output=True)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertIn('event=session_exit compositor_status=1 steam_status=unavailable', result.stdout)
|
||||
|
||||
def test_diagnostics_are_disabled_by_default(self):
|
||||
result = self.run_session(0, output=True)
|
||||
self.assertEqual(result.returncode, 0)
|
||||
self.assertNotIn('DROIDDECK_DIAGNOSTICS', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user