mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 05:16:01 +00:00
fix(droiddeckctl): logs latest works without root
`logs latest` pulled the session folder under getFilesDir(), which adb cannot read on an unrooted device, so it always failed with "Permission denied" and droiddeck-scenario kept no logs for failed runs. The agent bridge gets a `logs` method that writes the Share logs archive to the app's external files folder (agent-logs/), and droiddeckctl pulls that zip and unpacks it into the destination with the session's files at the top, as before. Builds without the method still get the old pull.
This commit is contained in:
1 parent
4b6cba0a6d
commit
2fb066507a
7 files changed
+128
-6
No files matched your search
+29
-1
@@ -16,6 +16,7 @@ import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
import zipfile
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
@@ -421,6 +422,23 @@ def start_session(adb: str, serial: str, request: dict) -> dict:
|
||||
return confirm_start(adb, serial, request, current["session"])
|
||||
|
||||
|
||||
def unpack_logs(archive: Path, destination: Path, session_id: str) -> None:
|
||||
"""Unpack a Share logs zip so the session's own files sit at the top of destination."""
|
||||
try:
|
||||
with zipfile.ZipFile(archive) as z:
|
||||
for entry in z.infolist():
|
||||
name = entry.filename
|
||||
if name.startswith(session_id + "/"):
|
||||
name = name[len(session_id) + 1:]
|
||||
target = (destination / name).resolve()
|
||||
if entry.is_dir() or not name or not target.is_relative_to(destination):
|
||||
continue
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(z.read(entry))
|
||||
except (OSError, zipfile.BadZipFile) as exc:
|
||||
raise ControlError(f"Could not unpack the session logs: {exc}", "LOG_PULL_FAILED") from exc
|
||||
|
||||
|
||||
def require_commands(adb: str, serial: str) -> dict:
|
||||
access = checked(provider_call(adb, serial, "access"), "ACCESS_FAILED")
|
||||
if access.get("commands") is not True:
|
||||
@@ -741,7 +759,17 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
|
||||
if not remote_dir or not session.get("id") or not session.get("artifactsAvailable"):
|
||||
raise ControlError("No session artifact directory is available", "NO_SESSION_LOGS")
|
||||
destination = Path(args.destination or session["id"]).expanduser().resolve()
|
||||
result = run_adb(adb, serial, "pull", remote_dir, str(destination), timeout=120)
|
||||
exported = provider_call(adb, serial, "logs", timeout=args.timeout + 40)
|
||||
if (exported.get("error") or {}).get("code") == "UNKNOWN_COMMAND":
|
||||
# Older builds have no logs method; their private folder only pulls on a rooted device.
|
||||
result = run_adb(adb, serial, "pull", remote_dir, str(destination), timeout=120)
|
||||
else:
|
||||
zip_path = checked(exported, "LOG_PULL_FAILED")["zip"]
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
local_zip = Path(temp) / "logs.zip"
|
||||
result = run_adb(adb, serial, "pull", zip_path, str(local_zip), timeout=120)
|
||||
if result.returncode == 0:
|
||||
unpack_logs(local_zip, destination, exported.get("sessionId") or session["id"])
|
||||
if result.returncode != 0:
|
||||
detail = (result.stderr or result.stdout).decode(errors="replace").strip()
|
||||
raise ControlError(detail or "adb pull failed", "LOG_PULL_FAILED")
|
||||
|
||||
@@ -12,6 +12,7 @@ import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
import unittest.mock
|
||||
import zipfile
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
@@ -70,8 +71,14 @@ FAKE_ADB = textwrap.dedent('''\
|
||||
print(config.get("thermalservice", ""))
|
||||
elif args[:3] == ["shell", "grep", "."]:
|
||||
print(config.get("cpufreq", ""))
|
||||
elif args[:1] == ["pull"] and args[1] in config.get("files", {}):
|
||||
open(args[2], "wb").write(base64.b64decode(config["files"][args[1]]))
|
||||
elif args[:1] == ["pull"]:
|
||||
entry["denied"] = True
|
||||
print(f"adb: error: failed to stat remote object '{args[1]}': Permission denied", file=sys.stderr)
|
||||
with open(config["log"], "a") as log:
|
||||
log.write(json.dumps(entry) + "\\n")
|
||||
sys.exit(1 if entry.get("denied") else 0)
|
||||
''')
|
||||
|
||||
DUMPSYS_DISPLAY = textwrap.dedent('''\
|
||||
@@ -130,6 +137,22 @@ CPUFREQ = textwrap.dedent('''\
|
||||
|
||||
def battery(tenths):
|
||||
return f"Current Battery Service state:\n level: 80\n temperature: {tenths}\n technology: Li-poly"
|
||||
PRIVATE_LOG_DIR = "/data/user/0/com.droiddeck.launcher/files/logs/sessions/s1"
|
||||
EXPORTED_ZIP = "/storage/emulated/0/Android/data/com.droiddeck.launcher/files/agent-logs/DroidDeck-s1.zip"
|
||||
|
||||
|
||||
def share_zip(entries):
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w") as z:
|
||||
for name, text in entries.items():
|
||||
z.writestr(name, text)
|
||||
return base64.b64encode(buffer.getvalue()).decode()
|
||||
|
||||
|
||||
def ended_state():
|
||||
ended = state(phase="IDLE")
|
||||
ended["session"].update(logDir=PRIVATE_LOG_DIR, artifactsAvailable=True, artifactsComplete=True)
|
||||
return ended
|
||||
|
||||
|
||||
def state(phase="READY", focused=None, focusable=()):
|
||||
@@ -507,6 +530,33 @@ class DroiddeckctlTest(FakeAdbTest):
|
||||
self.assertEqual(["INVALID_ARGUMENTS", 2], [out["error"]["code"], code])
|
||||
code, out = self.run_ctl("wait", "cool", "--below", "38")
|
||||
self.assertEqual("THERMAL_FAILED", out["error"]["code"])
|
||||
def test_logs_pull_the_exported_zip_instead_of_the_private_folder(self):
|
||||
self.configure({"state": ended_state(), "logs": {"ok": True, "sessionId": "s1", "zip": EXPORTED_ZIP}},
|
||||
files={EXPORTED_ZIP: share_zip({"s1/session.log": "booted", "s1/steam/console.log": "c",
|
||||
"stores/epic.log": "e", "../outside": "x"})})
|
||||
destination = self.dir / "artifacts"
|
||||
code, out = self.run_ctl("logs", "latest", str(destination))
|
||||
self.assertEqual(0, code, out)
|
||||
self.assertEqual("booted", (destination / "session.log").read_text())
|
||||
self.assertEqual("c", (destination / "steam" / "console.log").read_text())
|
||||
self.assertEqual("e", (destination / "stores" / "epic.log").read_text())
|
||||
self.assertFalse((self.dir / "outside").exists())
|
||||
self.assertEqual([["pull", EXPORTED_ZIP]], [c["args"][:2] for c in self.calls() if c["args"][:1] == ["pull"]])
|
||||
|
||||
def test_logs_from_an_older_build_fall_back_to_the_private_folder(self):
|
||||
self.configure({"state": ended_state()})
|
||||
code, out = self.run_ctl("logs", "latest", str(self.dir / "artifacts"))
|
||||
self.assertEqual(6, code)
|
||||
self.assertEqual("LOG_PULL_FAILED", out["error"]["code"])
|
||||
self.assertIn("Permission denied", out["error"]["message"])
|
||||
self.assertEqual([["pull", PRIVATE_LOG_DIR]], [c["args"][:2] for c in self.calls() if c["args"][:1] == ["pull"]])
|
||||
|
||||
def test_logs_without_a_session_folder_exit_6(self):
|
||||
self.configure({"state": ended_state(),
|
||||
"logs": {"ok": False, "error": {"code": "NO_SESSION_LOGS", "message": "none"}}})
|
||||
code, out = self.run_ctl("logs", "latest", str(self.dir / "artifacts"))
|
||||
self.assertEqual(6, code)
|
||||
self.assertEqual("NO_SESSION_LOGS", out["error"]["code"])
|
||||
|
||||
|
||||
class ScenarioTest(FakeAdbTest):
|
||||
@@ -550,6 +600,19 @@ class ScenarioTest(FakeAdbTest):
|
||||
evidence = json.loads((Path(report["runs"][0]["folder"]) / "evidence.json").read_text())
|
||||
self.assertEqual(769, evidence["focus"]["focusedApp"])
|
||||
|
||||
def test_a_failed_run_keeps_the_session_logs(self):
|
||||
failing = ended_state()
|
||||
failing["session"]["focus"] = {"focusedApp": 769}
|
||||
self.configure({"state": failing, "focus": {"ok": True, "focusedApp": 769},
|
||||
"logs": {"ok": True, "sessionId": "s1", "zip": EXPORTED_ZIP}},
|
||||
dumpsys_display=DUMPSYS_DISPLAY, files={EXPORTED_ZIP: share_zip({"s1/session.log": "booted"})})
|
||||
path = self.write({"name": "t", "steps": [["state"], {"assert": "session.focus.focusedApp", "equals": 7}]})
|
||||
code, report = self.run_scenario(path)
|
||||
self.assertEqual(1, code)
|
||||
folder = Path(report["runs"][0]["folder"])
|
||||
self.assertTrue(json.loads((folder / "evidence.json").read_text())["logs"]["ok"])
|
||||
self.assertEqual("booted", (folder / "session" / "session.log").read_text())
|
||||
|
||||
def test_after_steps_run_after_a_failure(self):
|
||||
self.configure({"state": state(focused=769), "quit": {"ok": True, "remaining": []}})
|
||||
path = self.write({"name": "t", "repeat": 2, "vars": {"appId": 7},
|
||||
|
||||
Reference in new issue
Block a user