417 lines
16 KiB
Python
417 lines
16 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import contextlib
|
|
import json
|
|
import platform
|
|
import re
|
|
import shutil
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from src.android_control import _adb_text, _shell, adb_available
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
CONFIG_DIR = BASE_DIR / "config"
|
|
STACK_ENV = CONFIG_DIR / "system-stack.env"
|
|
|
|
|
|
def _load_env_file(path: Path) -> dict[str, str]:
|
|
values: dict[str, str] = {}
|
|
if not path.is_file():
|
|
return values
|
|
for raw in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
line = raw.strip()
|
|
if not line or line.startswith("#") or "=" not in line:
|
|
continue
|
|
key, _, value = line.partition("=")
|
|
values[key.strip()] = value.strip().strip('"').strip("'")
|
|
return values
|
|
|
|
|
|
def load_redroid_env() -> dict[str, str]:
|
|
env = _load_env_file(STACK_ENV)
|
|
machine = platform.machine().lower()
|
|
legacy_arm_image = "cnflysky/redroid-rk3588:lineage-20"
|
|
env.setdefault("ENABLE_REDROID", "1")
|
|
env.setdefault("REDROID_IMAGE_X86", "fahaddz/redroid:13")
|
|
env.setdefault("REDROID_IMAGE_X86_ALT", "fahaddz/redroid:13")
|
|
env.setdefault("REDROID_IMAGE_ARM64", "fahaddz/redroid:13-arm-pi5")
|
|
env.setdefault("REDROID_IMAGE_ARM64_ALT", "fahaddz/redroid:13-arm-pi5")
|
|
env.setdefault("REDROID_DEFAULT_PORT", "5555")
|
|
env.setdefault("REDROID_PORT_STEP", "1")
|
|
env.setdefault("REDROID_INSTANCE_PREFIX", "redroid13")
|
|
env.setdefault("REDROID_DEFAULT_COUNT", "1")
|
|
env.setdefault("REDROID_DATA_PREFIX", "/var/lib/live-redroid")
|
|
env.setdefault("REDROID_GPU_MODE", "guest")
|
|
env.setdefault("REDROID_DEVICE_PROFILE", "pixel-7-pro")
|
|
env.setdefault("REDROID_ADB_INSECURE", "1")
|
|
env.setdefault("REDROID_BOOT_ARGS", "androidboot.redroid_magisk=1")
|
|
env.setdefault("REDROID_EXPECT_GMS", "1")
|
|
env.setdefault("REDROID_EXPECT_MAGISK", "1")
|
|
env.setdefault("REDROID_WEB_CONSOLE_PORT", "9010")
|
|
if env.get("REDROID_IMAGE_ARM64") == legacy_arm_image:
|
|
env["REDROID_IMAGE_ARM64"] = "fahaddz/redroid:13-arm-pi5"
|
|
if env.get("REDROID_IMAGE_ARM64_ALT") == legacy_arm_image:
|
|
env["REDROID_IMAGE_ARM64_ALT"] = "fahaddz/redroid:13-arm-pi5"
|
|
if env.get("REDROID_IMAGE") == legacy_arm_image:
|
|
env["REDROID_IMAGE"] = "fahaddz/redroid:13-arm-pi5"
|
|
boot_args = " ".join(item.strip() for item in str(env.get("REDROID_BOOT_ARGS", "")).split() if item.strip())
|
|
if "androidboot.redroid_gpu_mode=" not in boot_args:
|
|
boot_args = f"{boot_args} androidboot.redroid_gpu_mode={env.get('REDROID_GPU_MODE', 'guest')}".strip()
|
|
env["REDROID_BOOT_ARGS"] = boot_args
|
|
if "REDROID_IMAGE" not in env:
|
|
if machine in {"x86_64", "amd64"}:
|
|
env["REDROID_IMAGE"] = env.get("REDROID_IMAGE_X86_ALT") or env["REDROID_IMAGE_X86"]
|
|
elif machine in {"aarch64", "arm64"}:
|
|
env["REDROID_IMAGE"] = env.get("REDROID_IMAGE_ARM64_ALT") or env["REDROID_IMAGE_ARM64"]
|
|
else:
|
|
env["REDROID_IMAGE"] = env["REDROID_IMAGE_X86"]
|
|
return env
|
|
|
|
|
|
def redroid_enabled() -> bool:
|
|
return load_redroid_env().get("ENABLE_REDROID", "1") == "1"
|
|
|
|
|
|
def redroid_instance_name(index: int = 1) -> str:
|
|
env = load_redroid_env()
|
|
prefix = env.get("REDROID_INSTANCE_PREFIX", "redroid13").strip() or "redroid13"
|
|
return f"{prefix}-{index}"
|
|
|
|
|
|
def redroid_instance_port(index: int = 1) -> int:
|
|
env = load_redroid_env()
|
|
base = int(env.get("REDROID_DEFAULT_PORT", "5555") or 5555)
|
|
step = int(env.get("REDROID_PORT_STEP", "1") or 1)
|
|
return base + max(index - 1, 0) * step
|
|
|
|
|
|
async def _run_command(command: list[str], timeout: float = 30.0) -> tuple[int, str, str]:
|
|
proc = await asyncio.create_subprocess_exec(
|
|
*command,
|
|
stdout=asyncio.subprocess.PIPE,
|
|
stderr=asyncio.subprocess.PIPE,
|
|
cwd=str(BASE_DIR),
|
|
)
|
|
try:
|
|
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
|
except asyncio.TimeoutError:
|
|
with contextlib.suppress(ProcessLookupError):
|
|
proc.kill()
|
|
with contextlib.suppress(ProcessLookupError):
|
|
await proc.wait()
|
|
return 124, "", "Command timed out"
|
|
return (
|
|
int(proc.returncode or 0),
|
|
(stdout or b"").decode("utf-8", "replace").strip(),
|
|
(stderr or b"").decode("utf-8", "replace").strip(),
|
|
)
|
|
|
|
|
|
def _docker_available() -> bool:
|
|
return shutil.which("docker") is not None
|
|
|
|
|
|
def _extract_host_port(ports_text: str) -> int | None:
|
|
if not ports_text:
|
|
return None
|
|
match = re.search(r"(?P<host>\d+)->5555/tcp", ports_text)
|
|
if match:
|
|
return int(match.group("host"))
|
|
return None
|
|
|
|
|
|
def _looks_like_redroid(name: str, image: str) -> bool:
|
|
low = f"{name} {image}".lower()
|
|
return "redroid" in low
|
|
|
|
|
|
async def _docker_ps_rows() -> list[dict[str, str]]:
|
|
if not _docker_available():
|
|
return []
|
|
code, out, _err = await _run_command(
|
|
[
|
|
"docker",
|
|
"ps",
|
|
"-a",
|
|
"--format",
|
|
"{{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}",
|
|
],
|
|
timeout=20.0,
|
|
)
|
|
if code != 0 or not out:
|
|
return []
|
|
rows: list[dict[str, str]] = []
|
|
for raw in out.splitlines():
|
|
parts = raw.split("\t")
|
|
if len(parts) < 4:
|
|
continue
|
|
name, image, status, ports = parts[:4]
|
|
if not _looks_like_redroid(name, image):
|
|
continue
|
|
rows.append(
|
|
{
|
|
"name": name.strip(),
|
|
"image": image.strip(),
|
|
"status_text": status.strip(),
|
|
"ports_text": ports.strip(),
|
|
}
|
|
)
|
|
return rows
|
|
|
|
|
|
async def _docker_inspect_mounts(container_name: str) -> dict[str, str]:
|
|
if not _docker_available():
|
|
return {}
|
|
code, out, _err = await _run_command(["docker", "inspect", container_name], timeout=20.0)
|
|
if code != 0 or not out:
|
|
return {}
|
|
try:
|
|
payload = json.loads(out)
|
|
except json.JSONDecodeError:
|
|
return {}
|
|
mounts = {}
|
|
for item in payload or []:
|
|
for mount in item.get("Mounts") or []:
|
|
dst = str(mount.get("Destination") or "").strip()
|
|
src = str(mount.get("Source") or "").strip()
|
|
if dst and src:
|
|
mounts[dst] = src
|
|
return mounts
|
|
|
|
|
|
async def _probe_adb_serial(serial: str) -> dict[str, Any]:
|
|
details: dict[str, Any] = {
|
|
"adb_serial": serial,
|
|
"adb_ok": False,
|
|
"boot_completed": "",
|
|
"google_play": False,
|
|
"google_services": False,
|
|
"magisk": False,
|
|
"root": False,
|
|
"model": "",
|
|
"fingerprint": "",
|
|
"android_version": "",
|
|
}
|
|
if not adb_available():
|
|
return details
|
|
try:
|
|
boot, model, fp, av, packages = await asyncio.gather(
|
|
_shell(serial, "getprop sys.boot_completed", timeout=12.0),
|
|
_shell(serial, "getprop ro.product.model", timeout=12.0),
|
|
_shell(serial, "getprop ro.build.fingerprint", timeout=12.0),
|
|
_shell(serial, "getprop ro.build.version.release", timeout=12.0),
|
|
_shell(
|
|
serial,
|
|
"pm list packages | grep -E 'com.android.vending|com.google.android.gms|io.github.huskydg.magisk|com.topjohnwu.magisk' || true",
|
|
timeout=18.0,
|
|
),
|
|
)
|
|
except Exception as exc: # noqa: BLE001
|
|
details["error"] = str(exc)
|
|
return details
|
|
|
|
root_ok = False
|
|
for cmd in ("su root id", "su 0 id"):
|
|
try:
|
|
root_out = await _shell(serial, cmd, timeout=12.0)
|
|
except Exception: # noqa: BLE001
|
|
continue
|
|
if "uid=0" in root_out:
|
|
root_ok = True
|
|
break
|
|
|
|
package_text = packages.lower()
|
|
details.update(
|
|
{
|
|
"adb_ok": True,
|
|
"boot_completed": boot.strip(),
|
|
"google_play": "com.android.vending" in package_text,
|
|
"google_services": "com.google.android.gms" in package_text,
|
|
"magisk": "magisk" in package_text,
|
|
"root": root_ok,
|
|
"model": model.strip(),
|
|
"fingerprint": fp.strip(),
|
|
"android_version": av.strip(),
|
|
"ready": boot.strip() == "1",
|
|
}
|
|
)
|
|
return details
|
|
|
|
|
|
async def list_redroid_instances() -> list[dict[str, Any]]:
|
|
rows = await _docker_ps_rows()
|
|
items: list[dict[str, Any]] = []
|
|
for row in rows:
|
|
name = row["name"]
|
|
ports_text = row["ports_text"]
|
|
port = _extract_host_port(ports_text)
|
|
mounts = await _docker_inspect_mounts(name)
|
|
item: dict[str, Any] = {
|
|
"name": name,
|
|
"image": row["image"],
|
|
"status_text": row["status_text"],
|
|
"ports_text": ports_text,
|
|
"port": port,
|
|
"running": row["status_text"].lower().startswith("up "),
|
|
"data_dir": mounts.get("/data", ""),
|
|
"transport": "tcp",
|
|
"adb_serial": f"127.0.0.1:{port}" if port else "",
|
|
}
|
|
if port and adb_available():
|
|
await _adb_text(None, "connect", f"127.0.0.1:{port}", timeout=15.0)
|
|
item["diagnostics"] = await _probe_adb_serial(f"127.0.0.1:{port}")
|
|
items.append(item)
|
|
return items
|
|
|
|
|
|
def redroid_runtime_requirements() -> dict[str, Any]:
|
|
binderfs = Path("/dev/binderfs")
|
|
return {
|
|
"docker_available": _docker_available(),
|
|
"adb_available": adb_available(),
|
|
"kvm": Path("/dev/kvm").exists(),
|
|
"binderfs": binderfs.exists(),
|
|
"binder_nodes": sorted(p.name for p in binderfs.glob("*")) if binderfs.is_dir() else [],
|
|
"ashmem": Path("/dev/ashmem").exists(),
|
|
}
|
|
|
|
|
|
async def redroid_runtime_summary() -> dict[str, Any]:
|
|
env = load_redroid_env()
|
|
instances = await list_redroid_instances()
|
|
requirements = redroid_runtime_requirements()
|
|
return {
|
|
"enabled": env.get("ENABLE_REDROID", "1") == "1",
|
|
"arch": platform.machine(),
|
|
"image": env.get("REDROID_IMAGE", ""),
|
|
"device_profile": env.get("REDROID_DEVICE_PROFILE", "pixel-7-pro"),
|
|
"gpu_mode": env.get("REDROID_GPU_MODE", "guest"),
|
|
"boot_args": env.get("REDROID_BOOT_ARGS", ""),
|
|
"expect_gms": env.get("REDROID_EXPECT_GMS", "1") == "1",
|
|
"expect_magisk": env.get("REDROID_EXPECT_MAGISK", "1") == "1",
|
|
"default_port": int(env.get("REDROID_DEFAULT_PORT", "5555") or 5555),
|
|
"instance_prefix": env.get("REDROID_INSTANCE_PREFIX", "redroid13"),
|
|
"requirements": requirements,
|
|
"instances": instances,
|
|
"running": any(item.get("running") for item in instances),
|
|
"ready_count": sum(1 for item in instances if (item.get("diagnostics") or {}).get("ready")),
|
|
}
|
|
|
|
|
|
def _redroid_run_command(name: str, port: int, data_dir: str, image: str, env: dict[str, str]) -> list[str]:
|
|
command = [
|
|
"docker",
|
|
"run",
|
|
"-d",
|
|
"--name",
|
|
name,
|
|
"--privileged",
|
|
"--pull",
|
|
"always",
|
|
"--restart",
|
|
"unless-stopped",
|
|
"-p",
|
|
f"{port}:5555",
|
|
"-v",
|
|
f"{data_dir}:/data",
|
|
"-e",
|
|
f"REDROID_GPU_MODE={env.get('REDROID_GPU_MODE', 'guest')}",
|
|
"-e",
|
|
f"REDROID_DEVICE_PROFILE={env.get('REDROID_DEVICE_PROFILE', 'pixel-7-pro')}",
|
|
image,
|
|
]
|
|
insert_at = 7
|
|
if Path("/dev/kvm").exists():
|
|
command[insert_at:insert_at] = ["--device", "/dev/kvm"]
|
|
insert_at += 2
|
|
if Path("/dev/rga").exists():
|
|
command[insert_at:insert_at] = ["--device", "/dev/rga"]
|
|
insert_at += 2
|
|
if Path("/dev/dri").exists():
|
|
command[insert_at:insert_at] = ["-v", "/dev/dri:/dev/dri"]
|
|
insert_at += 2
|
|
if Path("/dev/dma_heap").exists():
|
|
command[insert_at:insert_at] = ["-v", "/dev/dma_heap:/dev/dma_heap"]
|
|
insert_at += 2
|
|
if Path("/dev/binderfs").exists():
|
|
command[insert_at:insert_at] = ["-v", "/dev/binderfs:/dev/binderfs"]
|
|
insert_at += 2
|
|
if Path("/dev/mpp_service").exists():
|
|
command[insert_at:insert_at] = ["--device", "/dev/mpp_service"]
|
|
insert_at += 2
|
|
if env.get("REDROID_ADB_INSECURE", "1") == "1":
|
|
command[insert_at:insert_at] = ["-e", "REDROID_ADB_INSECURE=1"]
|
|
boot_args = [item.strip() for item in str(env.get("REDROID_BOOT_ARGS", "")).split() if item.strip()]
|
|
if boot_args:
|
|
command.extend(boot_args)
|
|
return command
|
|
|
|
|
|
async def redroid_action(action: str, name: str | None = None) -> dict[str, Any]:
|
|
env = load_redroid_env()
|
|
target_name = (name or redroid_instance_name(1)).strip()
|
|
if not target_name:
|
|
raise ValueError("Missing Redroid instance name")
|
|
if not _docker_available():
|
|
raise RuntimeError("docker is not installed")
|
|
if env.get("ENABLE_REDROID", "1") != "1":
|
|
raise RuntimeError("ENABLE_REDROID is disabled in config/system-stack.env")
|
|
|
|
existing = {item["name"]: item for item in await list_redroid_instances()}
|
|
if action == "start":
|
|
if target_name in existing and existing[target_name].get("running"):
|
|
summary = await redroid_runtime_summary()
|
|
return {"message": f"{target_name} already running", "summary": summary}
|
|
if target_name in existing and not existing[target_name].get("running"):
|
|
code, out, err = await _run_command(["docker", "start", target_name], timeout=30.0)
|
|
if code != 0:
|
|
raise RuntimeError(err or out or "docker start failed")
|
|
else:
|
|
index_match = re.search(r"(\d+)$", target_name)
|
|
index = int(index_match.group(1)) if index_match else 1
|
|
port = redroid_instance_port(index)
|
|
data_prefix = env.get("REDROID_DATA_PREFIX", "/var/lib/live-redroid").rstrip("/ ")
|
|
data_dir = f"{data_prefix}-{target_name}"
|
|
image = env.get("REDROID_IMAGE", "")
|
|
Path(data_dir).mkdir(parents=True, exist_ok=True)
|
|
code, out, err = await _run_command(
|
|
_redroid_run_command(target_name, port, data_dir, image, env),
|
|
timeout=60.0,
|
|
)
|
|
if code != 0:
|
|
raise RuntimeError(err or out or "docker run failed")
|
|
return {"message": f"Redroid {target_name} started", "summary": await redroid_runtime_summary()}
|
|
|
|
if action == "stop":
|
|
code, out, err = await _run_command(["docker", "stop", target_name], timeout=30.0)
|
|
if code != 0:
|
|
raise RuntimeError(err or out or "docker stop failed")
|
|
return {"message": f"Redroid {target_name} stopped", "summary": await redroid_runtime_summary()}
|
|
|
|
if action == "restart":
|
|
code, out, err = await _run_command(["docker", "restart", target_name], timeout=45.0)
|
|
if code != 0:
|
|
raise RuntimeError(err or out or "docker restart failed")
|
|
return {"message": f"Redroid {target_name} restarted", "summary": await redroid_runtime_summary()}
|
|
|
|
if action == "remove":
|
|
code, out, err = await _run_command(["docker", "rm", "-f", target_name], timeout=45.0)
|
|
if code != 0:
|
|
raise RuntimeError(err or out or "docker rm failed")
|
|
return {"message": f"Redroid {target_name} removed", "summary": await redroid_runtime_summary()}
|
|
|
|
if action == "adb_connect":
|
|
item = existing.get(target_name)
|
|
if not item or not item.get("port"):
|
|
raise RuntimeError("Redroid instance port is unavailable")
|
|
port = int(item["port"])
|
|
result = await _adb_text(None, "connect", f"127.0.0.1:{port}", timeout=20.0)
|
|
return {
|
|
"message": result[1] or result[2] or "adb connect finished",
|
|
"summary": await redroid_runtime_summary(),
|
|
}
|
|
|
|
raise ValueError(f"Unsupported Redroid action: {action}")
|