This commit is contained in:
eric 2026-06-08 09:21:48 -05:00
parent 573373be79
commit 19776fcdd1
5 changed files with 213 additions and 13 deletions

View File

@ -904,6 +904,42 @@ remove_legacy_neko_container() {
fi
}
docker_container_status() {
local name="$1"
docker ps -a --filter "name=^/${name}$" --format '{{.State}}|{{.Status}}' 2>/dev/null | head -n 1
}
docker_container_network_attached() {
local name="$1"
[ -n "$name" ] || return 1
docker inspect -f '{{if .NetworkSettings.Networks}}1{{else}}0{{end}}' "$name" 2>/dev/null | grep -qx '1'
}
docker_container_http_port_published() {
local name="$1" port="$2"
[ -n "$name" ] && [ -n "$port" ] || return 1
docker port "$name" 8080/tcp 2>/dev/null |
awk -F: -v port="$port" 'NF && $NF == port { found = 1 } END { exit(found ? 0 : 1) }'
}
remove_unreachable_neko_containers() {
local count="${1:-}" idx name port state
[ -n "$count" ] || count="$(resolve_neko_instance_count)"
have docker || return 0
for idx in $(seq 1 "$count"); do
name="live-neko-$idx"
port="$(resolve_neko_http_port_for_instance "$idx")"
state="$(docker_container_status "$name" || true)"
[ -n "$state" ] || continue
if echo "$state" | grep -Eqi 'running|created|restarting|dead'; then
if ! docker_container_network_attached "$name" || ! docker_container_http_port_published "$name" "$port"; then
log "Removing unreachable ${name}; compose will recreate it with port ${port}"
docker rm -f "$name" >/dev/null 2>&1 || true
fi
fi
done
}
ensure_live_user() {
if ! id -u live >/dev/null 2>&1; then
log "Creating live user"
@ -2066,6 +2102,7 @@ install_neko_browser() {
allow_udp_range_if_firewall_active "$range"
done
remove_legacy_neko_container
remove_unreachable_neko_containers "$instance_count"
compose_file="$(render_neko_compose_file)"
neko_timeout="${NEKO_INSTALL_TIMEOUT:-${DOCKER_OPTIONAL_INSTALL_TIMEOUT:-900}}"
if ! compose_in_service_dir_timed "$neko_timeout" "$compose_file" up -d; then

View File

@ -742,6 +742,61 @@ remove_neko_recreate_conflicts() {
done
}
docker_container_network_attached() {
local name="$1"
[ -n "$name" ] || return 1
docker inspect -f '{{if .NetworkSettings.Networks}}1{{else}}0{{end}}' "$name" 2>/dev/null | grep -qx '1'
}
docker_container_http_port_published() {
local name="$1" port="$2"
[ -n "$name" ] && [ -n "$port" ] || return 1
docker port "$name" 8080/tcp 2>/dev/null |
awk -F: -v port="$port" 'NF && $NF == port { found = 1 } END { exit(found ? 0 : 1) }'
}
neko_http_probe_code() {
local port="$1" code
if have curl; then
code="$(curl -kfsS -m 3 -o /dev/null -w '%{http_code}' "http://127.0.0.1:${port}/" 2>/dev/null || true)"
printf '%s' "${code:-000}"
return 0
fi
if have wget; then
if wget -q -O /dev/null --timeout=3 "http://127.0.0.1:${port}/" 2>/dev/null; then
printf '200'
else
printf '000'
fi
return 0
fi
printf 'skip'
}
neko_http_code_ok() {
case "${1:-}" in
2*|3*|skip) return 0 ;;
*) return 1 ;;
esac
}
remove_unreachable_neko_containers() {
local count="${1:-}" idx name port state
[ -n "$count" ] || count="$(resolve_neko_instance_count)"
have docker || return 0
for idx in $(seq 1 "$count"); do
name="live-neko-$idx"
port="$(resolve_neko_http_port_for_instance "$idx")"
state="$(docker_container_status "$name" || true)"
[ -n "$state" ] || continue
if echo "$state" | grep -Eqi 'running|created|restarting|dead'; then
if ! docker_container_network_attached "$name" || ! docker_container_http_port_published "$name" "$port"; then
docker_container_force_remove "$name"
fi
fi
done
}
is_physical_lan_iface_name() {
local name="${1:-}"
case "$name" in
@ -1859,6 +1914,7 @@ service_neko_status() {
local state browser_proxy status_value target_nat1to1 runtime_nat1to1
local running_count=0 total_count=0 states="" name instance_count idx ports="" profiles=""
local reconfigure_needed=0 nat_mismatches="" reconfigure_detail=""
local port network_ok port_ok http_code runtime_ok
instance_count="$(resolve_neko_instance_count)"
total_count="$instance_count"
if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then
@ -1867,17 +1923,37 @@ service_neko_status() {
target_nat1to1="${NEKO_WEBRTC_NAT1TO1:-}"
for idx in $(seq 1 "$instance_count"); do
name="live-neko-$idx"
port="$(resolve_neko_http_port_for_instance "$idx")"
state="$(docker_container_status "$name" || true)"
network_ok=0
port_ok=0
runtime_ok=0
http_code=skip
if echo "$state" | grep -qi running; then
running_count=$((running_count + 1))
if docker_container_network_attached "$name"; then
network_ok=1
fi
if docker_container_http_port_published "$name" "$port"; then
port_ok=1
http_code="$(neko_http_probe_code "$port")"
else
http_code=unpublished
fi
if [ "$network_ok" = "1" ] && [ "$port_ok" = "1" ] && neko_http_code_ok "$http_code"; then
runtime_ok=1
running_count=$((running_count + 1))
else
reconfigure_needed=1
nat_mismatches="${nat_mismatches}${name}:runtime_unreachable(port=${port},network=${network_ok},published=${port_ok},http=${http_code}),"
fi
runtime_nat1to1="$(docker_container_env_value "$name" NEKO_WEBRTC_NAT1TO1 || true)"
if [ -n "$target_nat1to1" ] && [ "$runtime_nat1to1" != "$target_nat1to1" ]; then
reconfigure_needed=1
nat_mismatches="${nat_mismatches}${name}:${runtime_nat1to1:-unset}->${target_nat1to1},"
fi
fi
states="${states}${name}:${state:-missing};"
ports="${ports}$(resolve_neko_http_port_for_instance "$idx"),"
states="${states}${name}:${state:-missing},port=${port},network=${network_ok},published=${port_ok},http=${http_code},ready=${runtime_ok};"
ports="${ports}${port},"
profiles="${profiles}$(resolve_neko_profile_dir_for_instance "$idx"),"
done
if [ "$running_count" -eq 0 ]; then
@ -1944,6 +2020,7 @@ service_neko_start() {
service_names="${service_names} neko${idx}"
done
remove_legacy_neko_container
remove_unreachable_neko_containers "$instance_count"
compose_file="$(render_neko_compose_file)"
# shellcheck disable=SC2086
compose_in_service_dir "$compose_file" up -d $service_names

View File

@ -636,7 +636,25 @@ def _neko_container_name(instance_id: int) -> str:
return f"live-neko-{instance_id}"
async def _neko_container_state(container: str) -> dict[str, Any]:
def _docker_port_output_has_port(output: str, expected_port: int) -> bool:
expected = str(expected_port)
for line in (output or "").splitlines():
if line.rsplit(":", 1)[-1].strip() == expected:
return True
return False
async def _neko_http_port_state(container: str, expected_port: int) -> dict[str, Any]:
code, output = await _run_command(["docker", "port", container, "8080/tcp"], timeout=10.0)
detail = (output or "").strip()
return {
"http_port": expected_port,
"port_published": code == 0 and _docker_port_output_has_port(detail, expected_port),
"port_detail": detail,
}
async def _neko_container_state(container: str, expected_port: int | None = None) -> dict[str, Any]:
code, output = await _run_command(
["docker", "inspect", "--format", "{{.State.Status}}", container],
timeout=10.0,
@ -650,19 +668,33 @@ async def _neko_container_state(container: str) -> dict[str, Any]:
"running": False,
"status": "missing" if missing else "error",
"detail": detail,
"http_port": expected_port,
"port_published": False if expected_port is not None else None,
}
status = (detail.splitlines()[-1] if detail else "unknown").strip().lower()
return {
state = {
"exists": True,
"running": status == "running",
"status": status or "unknown",
"detail": detail,
}
if expected_port is not None:
port_state = await _neko_http_port_state(container, expected_port)
state.update(port_state)
if state["running"] and not state["port_published"]:
state["status"] = "degraded"
state["detail"] = (
f"{detail}; docker port 8080/tcp missing expected {expected_port}: "
f"{port_state['port_detail'] or '-'}"
)
return state
def _neko_status_message(instance_id: int, state: dict[str, Any]) -> str:
if not state.get("exists"):
return f"Neko {instance_id} 容器不存在"
if state.get("running") and state.get("port_published") is False:
return f"Neko {instance_id} 容器运行中,但 HTTP 端口 {state.get('http_port') or '?'} 未发布"
if state.get("running"):
return f"Neko {instance_id} 正在运行"
return f"Neko {instance_id} 已停止"
@ -681,19 +713,21 @@ async def neko_instance_action(instance_id: int, action: str) -> dict[str, Any]:
action = action.strip().lower()
if action not in {"status", "start", "stop", "restart", "delete"}:
raise ValueError(f"Unsupported Neko action: {action}")
configured_count = _neko_configured_instance_count()
configured_ports = _neko_http_ports(load_stack_env())
configured_count = len(configured_ports)
if instance_id < 1 or instance_id > configured_count:
raise ValueError(f"Neko instance must be between 1 and {configured_count}")
if not shutil.which("docker"):
raise RuntimeError("Docker 不可用,无法控制 Neko 容器")
container = _neko_container_name(instance_id)
before = await _neko_container_state(container)
expected_port = configured_ports[instance_id - 1]
before = await _neko_container_state(container, expected_port)
message = _neko_status_message(instance_id, before)
detail = str(before.get("detail") or "")
if action == "start":
if before.get("running"):
if before.get("running") and before.get("port_published", True):
message = f"Neko {instance_id} 已经在运行"
elif before.get("exists"):
message, detail = await _neko_reconfigure_stack(instance_id)
@ -737,7 +771,8 @@ async def neko_instance_action(instance_id: int, action: str) -> dict[str, Any]:
message = f"Neko {instance_id} 容器已删除,浏览器配置数据已保留"
detail = output
after = await _neko_container_state(container)
after = await _neko_container_state(container, expected_port)
ready = bool(after.get("running")) and after.get("port_published", True) is not False
return {
"service_id": "neko",
"id": instance_id,
@ -747,9 +782,13 @@ async def neko_instance_action(instance_id: int, action: str) -> dict[str, Any]:
"available": True,
"exists": bool(after.get("exists")),
"running": bool(after.get("running")),
"ready": ready,
"status": str(after.get("status") or "unknown"),
"message": message,
"detail": detail or str(after.get("detail") or ""),
"http_port": after.get("http_port"),
"port_published": after.get("port_published"),
"port_detail": after.get("port_detail"),
"profile_preserved": True,
}

View File

@ -98,7 +98,14 @@ class ControlPlaneServiceTests(unittest.TestCase):
self.assertEqual([item["id"] for item in summary["neko_instances"]], [1, 2, 3, 4])
def test_neko_instance_status_reports_single_container_state(self) -> None:
runner = AsyncMock(return_value=(0, "running"))
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, "0.0.0.0:9201\n[::]:9201"),
(0, "running"),
(0, "0.0.0.0:9201\n[::]:9201"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane._run_command", runner):
@ -107,14 +114,18 @@ class ControlPlaneServiceTests(unittest.TestCase):
self.assertEqual(result["container"], "live-neko-2")
self.assertTrue(result["exists"])
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertTrue(result["port_published"])
self.assertEqual(result["http_port"], 9201)
self.assertEqual(result["status"], "running")
self.assertIn("Neko 2", result["message"])
self.assertEqual(runner.await_count, 2)
self.assertEqual(runner.await_count, 4)
def test_neko_instance_delete_removes_container_but_preserves_profile(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, "0.0.0.0:9200"),
(0, "live-neko-1"),
(1, "Error: No such object: live-neko-1"),
]
@ -136,6 +147,7 @@ class ControlPlaneServiceTests(unittest.TestCase):
(1, "Error: No such object: live-neko-1"),
(0, "message=Neko stack started"),
(0, "running"),
(0, "0.0.0.0:9200"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
@ -148,14 +160,17 @@ class ControlPlaneServiceTests(unittest.TestCase):
self.assertEqual(result["container"], "live-neko-1")
self.assertTrue(result["exists"])
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertIn("重建", result["message"])
def test_neko_instance_start_reconfigures_existing_stopped_container(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "exited"),
(0, "0.0.0.0:9200"),
(0, "message=Neko WebRTC config reapplied"),
(0, "running"),
(0, "0.0.0.0:9200"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
@ -165,17 +180,43 @@ class ControlPlaneServiceTests(unittest.TestCase):
self.assertEqual(result["container"], "live-neko-1")
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertIn("reconfigured", result["message"])
reconfigure_cmd = runner.await_args_list[1].args[0]
reconfigure_cmd = runner.await_args_list[2].args[0]
self.assertEqual(reconfigure_cmd[-2:], ["neko", "reconfigure"])
self.assertNotEqual(reconfigure_cmd[:2], ["docker", "start"])
def test_neko_instance_start_reconfigures_running_container_without_published_port(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, ""),
(0, "message=Neko WebRTC config reapplied"),
(0, "running"),
(0, "0.0.0.0:9201"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(2, "start"))
self.assertEqual(result["container"], "live-neko-2")
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertTrue(result["port_published"])
self.assertIn("reconfigured", result["message"])
reconfigure_cmd = runner.await_args_list[2].args[0]
self.assertEqual(reconfigure_cmd[-2:], ["neko", "reconfigure"])
def test_neko_instance_restart_reconfigures_existing_container(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, "0.0.0.0:9200"),
(0, "message=Neko WebRTC config reapplied"),
(0, "running"),
(0, "0.0.0.0:9200"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
@ -185,8 +226,9 @@ class ControlPlaneServiceTests(unittest.TestCase):
self.assertEqual(result["container"], "live-neko-1")
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertIn("reconfigured", result["message"])
reconfigure_cmd = runner.await_args_list[1].args[0]
reconfigure_cmd = runner.await_args_list[2].args[0]
self.assertEqual(reconfigure_cmd[-2:], ["neko", "reconfigure"])
self.assertNotEqual(reconfigure_cmd[:2], ["docker", "restart"])

View File

@ -225,8 +225,13 @@ class NekoConfigTests(unittest.TestCase):
self.assertIn('path.startswith("/")', script)
self.assertIn('value.get("location") == 8', script)
self.assertIn("neko_managed_policies_enabled()", script)
self.assertIn("docker_container_http_port_published()", script)
self.assertIn("docker_container_network_attached()", script)
self.assertIn("remove_unreachable_neko_containers", script)
self.assertIn("service_neko_restart()", service_ctl)
self.assertIn("service_neko_reconfigure", service_ctl)
self.assertIn("neko_http_probe_code()", service_ctl)
self.assertIn("published=", service_ctl)
def test_tampermonkey_external_extension_seed_is_available_without_managed_policy(self) -> None:
external = json.loads(