From e7618149c6c929345aa86517fe2711940ee0c322 Mon Sep 17 00:00:00 2001 From: eric Date: Wed, 10 Jun 2026 02:20:06 -0500 Subject: [PATCH] 's' --- d2ypp2/install.sh | 11 + d2ypp2/scripts/linux/lib/common.sh | 37 +- d2ypp2/scripts/linux/service_ctl.sh | 201 ++++++- d2ypp2/src/control_plane.py | 47 +- d2ypp2/tests/test_control_plane_services.py | 31 +- d2ypp2/tests/test_deploy_full_paramiko.py | 114 ++++ d2ypp2/tests/test_frigate_usb.py | 44 ++ d2ypp2/tests/test_install_bootstrap.py | 60 ++ d2ypp2/tools/deploy_full_paramiko.py | 532 ++++++++++++++++++ d2ypp2/tools/render_neko_compose.py | 2 +- .../live-product/LiveControlApp.tsx | 1 + .../live-product/LiveYoutubeUnmannedView.tsx | 16 +- 12 files changed, 1057 insertions(+), 39 deletions(-) create mode 100644 d2ypp2/tests/test_deploy_full_paramiko.py create mode 100644 d2ypp2/tests/test_frigate_usb.py create mode 100644 d2ypp2/tools/deploy_full_paramiko.py diff --git a/d2ypp2/install.sh b/d2ypp2/install.sh index 478057f..f079b71 100755 --- a/d2ypp2/install.sh +++ b/d2ypp2/install.sh @@ -292,8 +292,19 @@ sync_to_install_dir() { --exclude '.pm2/' \ --exclude '.process_runner/' \ --exclude 'services/neko/data/' \ + --exclude 'services/filebrowser/database/' \ + --exclude 'services/filebrowser/config/' \ + --exclude 'services/uptime-kuma/data/' \ + --exclude 'services/mitmproxy/data/' \ + --exclude 'services/vscode-server/config/' \ + --exclude 'services/homepage/config/logs/' \ + --exclude 'services/homepage/config/kubernetes.yaml' \ --exclude 'config/system-stack.env' \ + --exclude 'config/hardware-profile.json' \ --exclude 'config/hub_state.sqlite' \ + --exclude 'config/*.sqlite' \ + --exclude 'config/*.sqlite3' \ + --exclude 'config/*.db' \ --exclude 'config/youtube.*.ini' \ --exclude 'config/URL_config.*.ini' \ "$source_dir/" "$target/" diff --git a/d2ypp2/scripts/linux/lib/common.sh b/d2ypp2/scripts/linux/lib/common.sh index 5e9cabc..0b8778f 100644 --- a/d2ypp2/scripts/linux/lib/common.sh +++ b/d2ypp2/scripts/linux/lib/common.sh @@ -1052,7 +1052,15 @@ ensure_runtime_dirs_owned_by_live() { web-console \ web-console/out \ web-console/.next \ - web-console/node_modules + web-console/node_modules \ + services/filebrowser/database \ + services/filebrowser/config \ + services/uptime-kuma/data \ + services/mitmproxy/data \ + services/vscode-server/config \ + services/homepage/config \ + services/frigate/config \ + services/srs/data do path="$ROOT_DIR/$rel" mkdir -p "$path" @@ -1070,6 +1078,12 @@ ensure_runtime_dirs_owned_by_live() { configure_host_dns() { local server [ -n "${LIVE_DNS_SERVERS:-}" ] || LIVE_DNS_SERVERS="223.5.5.5 119.29.29.29 1.1.1.1 8.8.8.8" + if systemctl is-active --quiet systemd-resolved 2>/dev/null; then + log "systemd-resolved is active; keeping dnsmasq disabled to avoid port 53 conflicts" + systemctl disable --now dnsmasq >/dev/null 2>&1 || true + systemctl reset-failed dnsmasq >/dev/null 2>&1 || true + return 0 + fi if have dnsmasq || systemctl list-unit-files dnsmasq.service --no-legend >/dev/null 2>&1; then log "Configuring dnsmasq upstream DNS fallback" mkdir -p /etc/dnsmasq.d /run/dnsmasq @@ -2603,9 +2617,20 @@ prepare_filebrowser() { local fb_tmp_json fb_hash fb_timeout fb_timeout="${FILEBROWSER_INSTALL_TIMEOUT:-${DOCKER_OPTIONAL_INSTALL_TIMEOUT:-900}}" mkdir -p "$ROOT_DIR/services/filebrowser/database" "$ROOT_DIR/services/filebrowser/config" - rm -f "$fb_db" - touch "$fb_db" chmod -R 0777 "$ROOT_DIR/services/filebrowser/database" "$ROOT_DIR/services/filebrowser/config" + if [ "${FILEBROWSER_RESET:-0}" != "1" ] && [ -s "$fb_db" ] && [ -s "$fb_settings" ]; then + log "File Browser database exists; preserving users and settings" + compose_in_service_dir_timed "${FILEBROWSER_INSTALL_TIMEOUT:-${DOCKER_OPTIONAL_INSTALL_TIMEOUT:-900}}" "$ROOT_DIR/services/filebrowser/docker-compose.yml" up -d || \ + log "WARN: File Browser failed to start before timeout; continuing" + return 0 + fi + + if [ "${FILEBROWSER_RESET:-0}" = "1" ]; then + log "FILEBROWSER_RESET=1; rebuilding File Browser database" + rm -f "$fb_db" "$fb_settings" + fi + + touch "$fb_db" compose_in_service_dir "$ROOT_DIR/services/filebrowser/docker-compose.yml" down >/dev/null 2>&1 || true if ! run_optional_with_timeout "$fb_timeout" docker run --rm \ @@ -2928,7 +2953,11 @@ prepare_srs() { run_hardware_probe() { log "Probing hardware profile" - as_live ". .venv/bin/activate && python scripts/hardware_probe.py --write" + ensure_runtime_dirs_owned_by_live + if ! as_live ". .venv/bin/activate && python scripts/hardware_probe.py --write"; then + log "WARN: hardware probe failed; continuing without refreshed hardware-profile.json" + return 0 + fi } install_live_edge_proxy() { diff --git a/d2ypp2/scripts/linux/service_ctl.sh b/d2ypp2/scripts/linux/service_ctl.sh index f65ff25..926d417 100644 --- a/d2ypp2/scripts/linux/service_ctl.sh +++ b/d2ypp2/scripts/linux/service_ctl.sh @@ -20,6 +20,7 @@ UPTIME_KUMA_COMPOSE="$ROOT_DIR/services/uptime-kuma/docker-compose.yml" OPENCLAW_COMPOSE="$ROOT_DIR/services/openclaw/docker-compose.yml" HOMEASSISTANT_COMPOSE="$ROOT_DIR/services/homeassistant/docker-compose.yml" FRIGATE_COMPOSE="$ROOT_DIR/services/frigate/docker-compose.yml" +FRIGATE_USB_COMPOSE="$ROOT_DIR/services/frigate/docker-compose.usb.yml" NTFY_COMPOSE="$ROOT_DIR/services/ntfy/docker-compose.yml" COTURN_COMPOSE="$ROOT_DIR/services/coturn/docker-compose.yml" BROWSER_LAUNCHER="$ROOT_DIR/scripts/linux/launch_browser.sh" @@ -311,7 +312,7 @@ compose_run() { compose_in_service_dir() { local compose_file="$1" shift - local d base + local d base cmd d="$(cd "$(dirname "$compose_file")" && pwd)" base="$(basename "$compose_file")" ( @@ -325,12 +326,40 @@ compose_in_service_dir() { ) } +compose_frigate() { + local d base cmd + d="$(cd "$(dirname "$FRIGATE_COMPOSE")" && pwd)" + base="$(basename "$FRIGATE_COMPOSE")" + ( + cd "$d" || exit 1 + cmd="$(compose_bin)" || exit 1 + if [ "$cmd" = "docker compose" ]; then + if [ -s "$FRIGATE_USB_COMPOSE" ]; then + docker compose -f "$base" -f "$FRIGATE_USB_COMPOSE" "$@" + else + docker compose -f "$base" "$@" + fi + else + if [ -s "$FRIGATE_USB_COMPOSE" ]; then + docker-compose -f "$base" -f "$FRIGATE_USB_COMPOSE" "$@" + else + docker-compose -f "$base" "$@" + fi + fi + ) +} + docker_container_status() { local name="$1" + local output if ! have docker; then return 1 fi - docker ps -a --filter "name=^/${name}$" --format '{{.State}}|{{.Status}}' | head -n 1 + if ! output="$(docker ps -a --filter "name=^/${name}$" --format '{{.State}}|{{.Status}}' 2>&1)"; then + printf 'error=%s\n' "$(printf '%s' "$output" | tr '\n' ' ' | cut -c1-240)" + return 0 + fi + printf '%s\n' "$output" | head -n 1 } docker_container_env_value() { @@ -605,7 +634,7 @@ resolve_neko_instance_count() { case "$max_count" in ''|*[!0-9]*) max_count=64 ;; esac - [ "$max_count" -lt 2 ] && max_count=2 + [ "$max_count" -lt 1 ] && max_count=1 [ "$max_count" -gt 64 ] && max_count=64 cpu="$(nproc 2>/dev/null || echo 4)" case "$requested" in @@ -621,8 +650,8 @@ resolve_neko_instance_count() { count="$requested" ;; esac - if [ "$count" -lt 2 ]; then - count=2 + if [ "$count" -lt 1 ]; then + count=1 fi if [ "$count" -gt "$max_count" ]; then count="$max_count" @@ -1229,6 +1258,34 @@ if old in text: PY } +patch_shellcrash_nftables_redirect() { + local fw="$SHELLCRASH_DIR/starts/fw_nftables.sh" + [ -f "$fw" ] || return 0 + command -v python3 >/dev/null 2>&1 || return 0 + python3 - "$fw" <<'PY' || true +import sys +from pathlib import Path + +path = Path(sys.argv[1]) +text = path.read_text(encoding="utf-8", errors="replace") +text = text.replace( + 'nft add rule inet shellcrash "$1" "$JUMP"', + 'nft add rule inet shellcrash "$1" $JUMP', +) +needle = "start_nftables() { #nftables配置总入口\n" +insert = ( + needle + + " modprobe nft_redir >/dev/null 2>&1 || true\n" + + " modprobe nft_chain_nat >/dev/null 2>&1 || true\n" + + " modprobe nf_nat >/dev/null 2>&1 || true\n" +) +if "modprobe nft_redir" not in text and needle in text: + text = text.replace(needle, insert, 1) +path.write_text(text, encoding="utf-8") +PY + chmod +x "$fw" 2>/dev/null || true +} + shellcrash_prepare_runtime() { if ! shellcrash_sync_runtime_config; then return 1 @@ -1237,6 +1294,7 @@ shellcrash_prepare_runtime() { CRASHDIR="$SHELLCRASH_DIR" "$SHELLCRASH_DIR/starts/bfstart.sh" >/dev/null 2>&1 || true fi patch_shellcrash_dns_repair + patch_shellcrash_nftables_redirect [ -x /tmp/ShellCrash/CrashCore ] } @@ -1377,7 +1435,6 @@ service_shellcrash_status() { running=1 fi fi - shellcrash_set_systemd_autostart_for_policy enabled="$(systemctl is-enabled shellcrash.service 2>/dev/null || true)" [ -z "$detail" ] && detail="dir=$SHELLCRASH_DIR" kv available 1 @@ -2380,24 +2437,116 @@ service_homeassistant_stop() { kv message "Home Assistant stopped" } +frigate_video_stable_path() { + local dev="$1" dir link target + for dir in /dev/v4l/by-id /dev/v4l/by-path; do + [ -d "$dir" ] || continue + for link in "$dir"/*; do + [ -e "$link" ] || continue + target="$(readlink -f "$link" 2>/dev/null || true)" + if [ "$target" = "$dev" ]; then + printf '%s' "$link" + return 0 + fi + done + done + printf '%s' "$dev" +} + +frigate_video_node_is_capture() { + local dev="$1" stable="${2:-}" info formats + case "$stable" in + *video-index0*) return 0 ;; + *video-index[1-9]*) return 1 ;; + esac + if have v4l2-ctl; then + info="$(v4l2-ctl -D -d "$dev" 2>/dev/null || true)" + if printf '%s\n' "$info" | grep -Eiq 'Video Capture|Video Capture Multiplanar'; then + return 0 + fi + if printf '%s\n' "$info" | grep -Eiq 'Metadata Capture|Video Output|VBI'; then + return 1 + fi + formats="$(v4l2-ctl -d "$dev" --list-formats-ext 2>/dev/null || true)" + [ -n "$formats" ] && return 0 + fi + return 0 +} + frigate_detect_usb_cameras() { - local dev base props name bus - for dev in /dev/video*; do + local dev base props name bus stable + for dev in $(find /dev -maxdepth 1 -type c -name 'video*' 2>/dev/null | sort -V); do [ -e "$dev" ] || continue base="$(basename "$dev")" props="$(udevadm info -q property -n "$dev" 2>/dev/null || true)" name="$(cat "/sys/class/video4linux/${base}/name" 2>/dev/null || true)" bus="$(printf '%s\n' "$props" | awk -F= '$1=="ID_BUS"{print $2; exit}')" if [ "$bus" = "usb" ] || printf '%s\n%s\n' "$props" "$name" | grep -Eiq 'uvc|usb|webcam|camera'; then - printf '%s|%s\n' "$dev" "${name:-USB camera}" + stable="$(frigate_video_stable_path "$dev")" + frigate_video_node_is_capture "$dev" "$stable" || continue + printf '%s|%s\n' "$stable" "${name:-USB camera}" fi done } +frigate_config_has_camera_entries() { + local cfg="$1" + awk ' + /^[[:space:]]*cameras:[[:space:]]*$/ { in_cameras=1; next } + in_cameras && /^[^[:space:]]/ { in_cameras=0 } + in_cameras && /^[[:space:]]{2}[A-Za-z0-9_-]+:[[:space:]]*$/ { found=1 } + END { exit found ? 0 : 1 } + ' "$cfg" +} + +frigate_config_can_be_autogenerated() { + local cfg="$1" + [ ! -s "$cfg" ] && return 0 + grep -q 'Managed by live stack USB camera autodetect' "$cfg" 2>/dev/null && return 0 + grep -Eq '^[[:space:]]*cameras:[[:space:]]*\{\}[[:space:]]*$' "$cfg" 2>/dev/null && return 0 + if grep -Eq '^[[:space:]]*cameras:[[:space:]]*$' "$cfg" 2>/dev/null && ! frigate_config_has_camera_entries "$cfg"; then + return 0 + fi + return 1 +} + +render_frigate_usb_compose_override() { + local devices="$1" tmp dev host + if [ -z "$devices" ]; then + rm -f "$FRIGATE_USB_COMPOSE" + return 0 + fi + tmp="$(mktemp)" + printf '%s\n' "$devices" | while IFS='|' read -r dev _name; do + [ -n "$dev" ] || continue + host="$(readlink -f "$dev" 2>/dev/null || true)" + [ -n "$host" ] || host="$dev" + case "$host" in + /dev/video*) [ -e "$host" ] && printf ' - "%s:%s"\n' "$host" "$host" ;; + esac + done | awk '!seen[$0]++' >"$tmp" + if [ ! -s "$tmp" ]; then + rm -f "$tmp" "$FRIGATE_USB_COMPOSE" + return 0 + fi + { + printf '%s\n' '# Generated by service_ctl.sh - do not hand-edit' + printf '%s\n' 'services:' + printf '%s\n' ' frigate:' + printf '%s\n' ' devices:' + cat "$tmp" + if [ -d /dev/v4l ]; then + printf '%s\n' ' volumes:' + printf '%s\n' ' - "/dev/v4l:/dev/v4l:ro"' + fi + } >"$FRIGATE_USB_COMPOSE" + rm -f "$tmp" +} + render_frigate_usb_config() { local devices="$1" cfg="$FRIGATE_CONFIG_DIR/config.yml" dev name cam mkdir -p "$FRIGATE_CONFIG_DIR" - if [ -s "$cfg" ] && ! grep -q 'Managed by live stack USB camera autodetect' "$cfg" 2>/dev/null; then + if ! frigate_config_can_be_autogenerated "$cfg"; then return 0 fi { @@ -2416,11 +2565,12 @@ render_frigate_usb_config() { printf '%s\n' "$devices" | while IFS='|' read -r dev name; do [ -n "$dev" ] || continue cam="$(basename "$dev" | tr -c 'A-Za-z0-9_' '_')" + [ -n "$cam" ] || cam="video" printf ' usb_%s:\n' "$cam" printf ' enabled: true\n' printf ' ffmpeg:\n' printf ' inputs:\n' - printf ' - path: %s\n' "$dev" + printf ' - path: "%s"\n' "$dev" printf ' input_args:\n' printf ' - -f\n' printf ' - v4l2\n' @@ -2466,28 +2616,38 @@ service_frigate_status() { kv detail "Docker or Frigate compose file is missing" return 0 fi - local state + local state status_value state="$(docker_container_status live-frigate || true)" local usb_count usb_count="$(frigate_detect_usb_cameras | awk 'NF{n++} END{print n+0}')" + if [[ "$state" == running* ]]; then + status_value=online + elif [[ "$state" == error=* ]]; then + status_value=error + else + status_value=stopped + fi kv available 1 kv running "$([[ "$state" == running* ]] && echo 1 || echo 0)" - kv status "$([[ "$state" == running* ]] && echo online || echo stopped)" + kv status "$status_value" kv host "${HOSTNAME_ALIAS}.local" kv port "$FRIGATE_WEB_PORT" kv url "http://${HOSTNAME_ALIAS}.local:${FRIGATE_WEB_PORT}" - kv detail "${state:-container=missing};usb_cameras=${usb_count};rtsp=${FRIGATE_RTSP_PORT};webrtc=${FRIGATE_WEBRTC_PORT};config=${FRIGATE_CONFIG_DIR};media=${FRIGATE_MEDIA_DIR}" + kv detail "${state:-container=missing};usb_cameras=${usb_count};rtsp=${FRIGATE_RTSP_PORT};webrtc=${FRIGATE_WEBRTC_PORT};config=${FRIGATE_CONFIG_DIR};media=${FRIGATE_MEDIA_DIR};usb_compose=${FRIGATE_USB_COMPOSE}" } service_frigate_start() { + local devices ensure_frigate_default_config - render_frigate_usb_config "$(frigate_detect_usb_cameras || true)" - compose_in_service_dir "$FRIGATE_COMPOSE" up -d + devices="$(frigate_detect_usb_cameras || true)" + render_frigate_usb_config "$devices" + render_frigate_usb_compose_override "$devices" + compose_frigate up -d kv message "Frigate started" } service_frigate_stop() { - compose_in_service_dir "$FRIGATE_COMPOSE" down + compose_frigate down kv message "Frigate stopped" } @@ -2500,16 +2660,19 @@ service_frigate_auto() { devices="$(frigate_detect_usb_cameras || true)" count="$(printf '%s\n' "$devices" | awk 'NF{n++} END{print n+0}')" if [ "$count" -le 0 ]; then + render_frigate_usb_compose_override "" kv message "No USB/UVC camera detected" return 0 fi render_frigate_usb_config "$devices" + render_frigate_usb_compose_override "$devices" state="$(docker_container_status live-frigate || true)" if [[ "$state" == running* ]]; then - kv message "Frigate already running; usb_cameras=${count}" + compose_frigate up -d + kv message "Frigate USB config applied; usb_cameras=${count}" return 0 fi - compose_in_service_dir "$FRIGATE_COMPOSE" up -d + compose_frigate up -d kv message "Frigate auto-started; usb_cameras=${count}" } diff --git a/d2ypp2/src/control_plane.py b/d2ypp2/src/control_plane.py index 8258326..84aab12 100644 --- a/d2ypp2/src/control_plane.py +++ b/d2ypp2/src/control_plane.py @@ -762,14 +762,28 @@ async def neko_instance_action(instance_id: int, action: str) -> dict[str, Any]: message = f"Neko {instance_id} 容器不存在,已重建并启动" detail = output elif action == "delete": - if not before.get("exists"): - message = f"Neko {instance_id} 容器已不存在" - else: + if configured_count > 1 and instance_id != configured_count: + raise ValueError(f"只能删除最后一个 Neko 实例;当前最后一个是 Neko {configured_count}") + if before.get("exists"): code, output = await _run_command(["docker", "rm", "-f", container], timeout=45.0) if code != 0: raise RuntimeError(f"Neko {instance_id} 删除失败:{output or 'docker rm failed'}") - message = f"Neko {instance_id} 容器已删除,浏览器配置数据已保留" detail = output + else: + detail = str(before.get("detail") or "") + if configured_count > 1: + next_count = configured_count - 1 + write_stack_env_value("NEKO_INSTANCE_COUNT", str(next_count)) + configured_count = next_count + invalidate_service_status_cache() + if SERVICE_CTL.is_file(): + code, output = await _run_command([BASH_BIN, str(SERVICE_CTL), "neko", "reconfigure"], timeout=180.0) + if code != 0: + raise RuntimeError(f"Neko {instance_id} 已删除,但重配实例数量失败:{output or 'neko reconfigure failed'}") + detail = "\n".join(part for part in (detail, output) if part) + message = f"Neko {instance_id} 已删除,实例数量已调整为 {configured_count},浏览器配置数据已保留" + else: + message = f"Neko {instance_id} 容器已删除,浏览器配置数据已保留" after = await _neko_container_state(container, expected_port) ready = bool(after.get("running")) and after.get("port_published", True) is not False @@ -852,6 +866,27 @@ def load_stack_env() -> dict[str, str]: return values +def write_stack_env_value(key: str, value: str) -> None: + CONFIG_DIR.mkdir(parents=True, exist_ok=True) + next_line = f"{key}={value}" + lines = STACK_ENV.read_text(encoding="utf-8").splitlines() if STACK_ENV.is_file() else [] + pattern = re.compile(rf"^\s*{re.escape(key)}\s*=") + replaced = False + next_lines: list[str] = [] + for raw in lines: + if pattern.match(raw): + if not replaced: + next_lines.append(next_line) + replaced = True + continue + next_lines.append(raw) + if not replaced: + if next_lines and next_lines[-1].strip(): + next_lines.append("") + next_lines.append(next_line) + STACK_ENV.write_text("\n".join(next_lines).rstrip() + "\n", encoding="utf-8") + + def _env_flag(env: dict[str, str], key: str, default: bool = True) -> bool: raw = str(env.get(key, "1" if default else "0")).strip().lower() if raw in {"", "default"}: @@ -870,8 +905,8 @@ def _env_int(env: dict[str, str], key: str, default: int) -> int: def _neko_http_ports(env: dict[str, str]) -> list[int]: - max_count = max(2, min(64, _env_int(env, "NEKO_MAX_INSTANCE_COUNT", 64))) - count = max(2, min(max_count, _env_int(env, "NEKO_INSTANCE_COUNT", 2))) + max_count = max(1, min(64, _env_int(env, "NEKO_MAX_INSTANCE_COUNT", 64))) + count = max(1, min(max_count, _env_int(env, "NEKO_INSTANCE_COUNT", 2))) base = _env_int(env, "NEKO_HTTP_PORT", 9200) return [_env_int(env, f"NEKO_HTTP_PORT_{idx}", base + idx - 1) for idx in range(1, count + 1)] diff --git a/d2ypp2/tests/test_control_plane_services.py b/d2ypp2/tests/test_control_plane_services.py index d9bc7fa..f0cf47d 100644 --- a/d2ypp2/tests/test_control_plane_services.py +++ b/d2ypp2/tests/test_control_plane_services.py @@ -125,22 +125,41 @@ class ControlPlaneServiceTests(unittest.TestCase): runner = AsyncMock( side_effect=[ (0, "running"), - (0, "0.0.0.0:9200"), - (0, "live-neko-1"), - (1, "Error: No such object: live-neko-1"), + (0, "0.0.0.0:9201"), + (0, "live-neko-2"), + (0, "message=Neko WebRTC config reapplied (1 browser instances)"), + (1, "Error: No such object: live-neko-2"), ] ) 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(1, "delete")) + with patch("src.control_plane.SERVICE_CTL") as service_ctl: + service_ctl.is_file.return_value = True + with patch("src.control_plane.write_stack_env_value") as write_env: + with patch("src.control_plane._run_command", runner): + result = asyncio.run(neko_instance_action(2, "delete")) - self.assertEqual(result["container"], "live-neko-1") + write_env.assert_called_once_with("NEKO_INSTANCE_COUNT", "1") + self.assertEqual(result["container"], "live-neko-2") + self.assertEqual(result["configured_count"], 1) self.assertFalse(result["exists"]) self.assertFalse(result["running"]) self.assertTrue(result["profile_preserved"]) self.assertIn("配置数据已保留", result["message"]) + def test_neko_instance_delete_rejects_non_last_instance(self) -> None: + runner = AsyncMock( + side_effect=[ + (0, "running"), + (0, "0.0.0.0:9200"), + ] + ) + with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "3"}): + with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"): + with patch("src.control_plane._run_command", runner): + with self.assertRaisesRegex(ValueError, "最后一个"): + asyncio.run(neko_instance_action(1, "delete")) + def test_neko_instance_start_rebuilds_missing_container(self) -> None: runner = AsyncMock( side_effect=[ diff --git a/d2ypp2/tests/test_deploy_full_paramiko.py b/d2ypp2/tests/test_deploy_full_paramiko.py new file mode 100644 index 0000000..278d0f3 --- /dev/null +++ b/d2ypp2/tests/test_deploy_full_paramiko.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import importlib.util +import os +import sys +import tarfile +import unittest +from pathlib import Path +from unittest.mock import patch + + +ROOT = Path(__file__).resolve().parents[1] + + +def load_module(): + spec = importlib.util.spec_from_file_location( + "deploy_full_paramiko_for_test", + ROOT / "tools" / "deploy_full_paramiko.py", + ) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + try: + spec.loader.exec_module(module) + finally: + sys.modules.pop(spec.name, None) + return module + + +class DeployFullParamikoTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.deploy = load_module() + + def tarinfo(self, name: str) -> tarfile.TarInfo: + return tarfile.TarInfo(name) + + def test_defaults_target_live_install_without_stored_password(self) -> None: + with patch.dict(os.environ, {}, clear=True): + config = self.deploy.load_config() + self.assertEqual(config.host, "192.168.2.101") + self.assertEqual(config.user, "eric") + self.assertEqual(config.password, "") + self.assertEqual(config.remote_path, "/opt/live/d2ypp") + self.assertEqual(config.profile, "all") + + def test_main_requires_password_from_environment(self) -> None: + with patch.dict(os.environ, {}, clear=True): + with self.assertRaisesRegex(SystemExit, "LIVE_DEPLOY_PASS is required"): + self.deploy.main() + + def test_remote_sync_preserves_runtime_state(self) -> None: + excludes = set(self.deploy.REMOTE_RSYNC_EXCLUDES) + for item in { + "/config/", + "/services/neko/data/", + "/services/filebrowser/database/", + "/services/filebrowser/config/", + "/services/uptime-kuma/data/", + "/services/mitmproxy/data/", + "/services/vscode-server/config/", + "/services/homepage/config/logs/", + "/vendor/scrcpy-server.jar", + }: + self.assertIn(item, excludes) + + def test_archive_filter_excludes_runtime_and_sensitive_config(self) -> None: + for rel in [ + "config/config.ini", + "config/google_oauth.json", + "config/youtube.ini", + "config/URL_config.ini", + "config/web2_api_token.txt", + "config/easytier_network.json", + "config/hub_state.sqlite", + "logs/app.log", + "web-console/node_modules/pkg/index.js", + "services/neko/data/profile/Default/Preferences", + "services/filebrowser/database/filebrowser.db", + "services/mitmproxy/data/mitmproxy-ca.pem", + "vendor/scrcpy-server.jar", + ]: + with self.subTest(rel=rel): + self.assertIsNone(self.deploy._tar_filter(self.tarinfo(rel))) + + def test_archive_filter_allows_publishable_templates(self) -> None: + for rel in [ + "config/system-stack.env.example", + "config/runtime.env.example", + "config/hardware.env.example", + "config/proxychains-youtube.conf", + "services/frigate/config/config.yml", + "services/srs/data/index.html", + ]: + with self.subTest(rel=rel): + info = self.tarinfo(rel) + self.assertIs(self.deploy._tar_filter(info), info) + + def test_remote_script_runs_full_install_and_health_checks(self) -> None: + script = self.deploy.build_remote_script() + for snippet in [ + "rsync -a --delete", + "scripts/linux/install_stack.sh \"$PROFILE\"", + "ensure_runtime_dirs_owned_by_live", + "http://127.0.0.1:8001/health", + "systemctl reset-failed dnsmasq.service", + "write_missing_config youtube.ini", + "write_missing_config URL_config.ini", + ]: + self.assertIn(snippet, script) + + +if __name__ == "__main__": + unittest.main() diff --git a/d2ypp2/tests/test_frigate_usb.py b/d2ypp2/tests/test_frigate_usb.py new file mode 100644 index 0000000..d463a63 --- /dev/null +++ b/d2ypp2/tests/test_frigate_usb.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] + + +class FrigateUsbRuntimeTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.service_ctl = (ROOT / "scripts" / "linux" / "service_ctl.sh").read_text(encoding="utf-8") + cls.compose = (ROOT / "services" / "frigate" / "docker-compose.yml").read_text(encoding="utf-8") + + def test_usb_camera_autodetect_uses_v4l2_capture_nodes(self) -> None: + script = self.service_ctl + self.assertIn("frigate_video_stable_path()", script) + self.assertIn("/dev/v4l/by-id", script) + self.assertIn("video-index0", script) + self.assertIn("Video Capture", script) + self.assertIn("frigate_detect_usb_cameras()", script) + self.assertIn("ID_BUS", script) + + def test_usb_compose_override_passes_video_devices_to_frigate(self) -> None: + script = self.service_ctl + self.assertIn('FRIGATE_USB_COMPOSE="$ROOT_DIR/services/frigate/docker-compose.usb.yml"', script) + self.assertIn("render_frigate_usb_compose_override()", script) + self.assertIn('printf \' - "%s:%s"\\n\' "$host" "$host"', script) + self.assertIn('"/dev/v4l:/dev/v4l:ro"', script) + self.assertIn("compose_frigate up -d", script) + self.assertIn("docker compose -f \"$base\" -f \"$FRIGATE_USB_COMPOSE\"", script) + self.assertIn("/dev/bus/usb:/dev/bus/usb", self.compose) + + def test_default_empty_frigate_config_can_be_autogenerated(self) -> None: + script = self.service_ctl + self.assertIn("frigate_config_can_be_autogenerated()", script) + self.assertIn("cameras:[[:space:]]*\\{\\}", script) + self.assertIn("Managed by live stack USB camera autodetect", script) + self.assertIn('path: "%s"', script) + + +if __name__ == "__main__": + unittest.main() diff --git a/d2ypp2/tests/test_install_bootstrap.py b/d2ypp2/tests/test_install_bootstrap.py index 9ef1f45..df8f4bd 100644 --- a/d2ypp2/tests/test_install_bootstrap.py +++ b/d2ypp2/tests/test_install_bootstrap.py @@ -75,7 +75,21 @@ class InstallBootstrapTests(unittest.TestCase): ".pm2/", ".process_runner/", "services/neko/data/", + "services/filebrowser/database/", + "services/filebrowser/config/", + "services/uptime-kuma/data/", + "services/mitmproxy/data/", + "services/vscode-server/config/", + "services/homepage/config/logs/", + "services/homepage/config/kubernetes.yaml", "config/system-stack.env", + "config/hardware-profile.json", + "config/hub_state.sqlite", + "config/*.sqlite", + "config/*.sqlite3", + "config/*.db", + "config/youtube.*.ini", + "config/URL_config.*.ini", ] for item in required_excludes: self.assertIn(f"--exclude '{item}'", self.script) @@ -142,5 +156,51 @@ class InstallBootstrapTests(unittest.TestCase): self.assertIsNone(re.search(r"\bpass\b", self.script)) +class InstallCommonShellTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.common = (ROOT / "scripts" / "linux" / "lib" / "common.sh").read_text(encoding="utf-8") + + def _function_body(self, name: str, next_name: str) -> str: + start = self.common.index(f"{name}() {{") + end = self.common.index(f"\n{next_name}() {{", start) + return self.common[start:end] + + def test_runtime_ownership_includes_service_state_dirs(self) -> None: + body = self._function_body("ensure_runtime_dirs_owned_by_live", "configure_host_dns") + for rel in [ + "services/filebrowser/database", + "services/filebrowser/config", + "services/uptime-kuma/data", + "services/mitmproxy/data", + "services/vscode-server/config", + "services/homepage/config", + "services/frigate/config", + "services/srs/data", + ]: + self.assertIn(rel, body) + + def test_systemd_resolved_keeps_dnsmasq_disabled(self) -> None: + body = self._function_body("configure_host_dns", "install_base_packages") + self.assertIn("systemctl is-active --quiet systemd-resolved", body) + self.assertIn("keeping dnsmasq disabled", body) + self.assertIn("systemctl disable --now dnsmasq", body) + self.assertIn("systemctl reset-failed dnsmasq", body) + self.assertIn("return 0", body) + + def test_filebrowser_install_preserves_existing_database(self) -> None: + body = self._function_body("prepare_filebrowser", "prepare_mitmproxy") + self.assertIn('FILEBROWSER_RESET:-0', body) + self.assertIn('[ -s "$fb_db" ] && [ -s "$fb_settings" ]', body) + self.assertIn("File Browser database exists; preserving users and settings", body) + self.assertIn('rm -f "$fb_db" "$fb_settings"', body) + + def test_hardware_probe_is_best_effort_after_runtime_permissions(self) -> None: + body = self._function_body("run_hardware_probe", "install_live_edge_proxy") + self.assertIn("ensure_runtime_dirs_owned_by_live", body) + self.assertIn("WARN: hardware probe failed; continuing", body) + self.assertIn("return 0", body) + + if __name__ == "__main__": unittest.main() diff --git a/d2ypp2/tools/deploy_full_paramiko.py b/d2ypp2/tools/deploy_full_paramiko.py new file mode 100644 index 0000000..87f6498 --- /dev/null +++ b/d2ypp2/tools/deploy_full_paramiko.py @@ -0,0 +1,532 @@ +#!/usr/bin/env python3 +"""Full source deployment over SSH/SFTP. + +This tool is for updating an existing live stack from the local checkout. +It replaces source files with rsync --delete while preserving machine-local +runtime state such as config, logs, databases, browser profiles, and service +data directories. +""" +from __future__ import annotations + +import fnmatch +import io +import os +import posixpath +import shlex +import subprocess +import sys +import tarfile +import tempfile +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path + + +REPO_ROOT = Path(__file__).resolve().parent.parent +LOG_DIR = REPO_ROOT / ".deploy_logs" + +SOURCE_ARCHIVE_EXCLUDES = ( + ".git", + ".deploy_logs", + ".venv", + "__pycache__", + "*/__pycache__", + ".pytest_cache", + "node_modules", + "web-console/node_modules", + "web-console/.next", + "web-console/.turbo", + "logs", + "downloads", + "backup_config", + "tmp", + "temp", + ".pm2", + ".process_runner", + "services/neko/data", + "services/filebrowser/database", + "services/filebrowser/config", + "services/uptime-kuma/data", + "services/mitmproxy/data", + "services/vscode-server/config", + "services/homepage/config/logs", + "services/homepage/config/kubernetes.yaml", + "services/frigate/media", + "vendor/scrcpy-server.jar", + "*.tar", + "*.tar.gz", + "*.tgz", + "*.zip", + "*.7z", + "*.log", + "*.pid", + "*.sock", +) + +CONFIG_ARCHIVE_INCLUDES = ( + "config/*.example", + "config/*.conf", +) + +REMOTE_RSYNC_EXCLUDES = ( + "/.git/", + "/.deploy_logs/", + "/.venv/", + "/node_modules/", + "/web-console/node_modules/", + "/web-console/.next/", + "/logs/", + "/downloads/", + "/backup_config/", + "/.pm2/", + "/.process_runner/", + "/config/", + "/backup/", + "/services/neko/data/", + "/services/filebrowser/database/", + "/services/filebrowser/config/", + "/services/uptime-kuma/data/", + "/services/mitmproxy/data/", + "/services/vscode-server/config/", + "/services/homepage/config/logs/", + "/services/homepage/config/kubernetes.yaml", + "/services/frigate/media/", + "/vendor/scrcpy-server.jar", + "/codex-live-stack.tgz", +) + +OBSOLETE_SOURCE_RUNTIME_FILES = ( + "config/URL_config.youtube.ini", + "config/URL_config.youtube2__ch_mp9mm36r_2wn0r.ini", + "config/URL_config.youtube2__ch_mp9n7yu2_83vci.ini", + "config/youtube.youtube.ini", + "config/youtube.youtube2__ch_mp9mm36r_2wn0r.ini", + "config/youtube.youtube2__ch_mp9mm9lz_a6jfx.ini", + "config/youtube.youtube2__ch_mp9n7yu2_83vci.ini", +) + + +@dataclass(frozen=True) +class DeployConfig: + host: str + user: str + password: str + port: int + remote_path: str + profile: str + run_install: bool + timeout: int + jump_host: str = "" + jump_port: int = 22 + jump_user: str = "" + jump_pass: str = "" + + +def _env_bool(name: str, default: bool) -> bool: + value = os.environ.get(name) + if value is None: + return default + return value.strip().lower() in {"1", "true", "yes", "on"} + + +def load_config() -> DeployConfig: + profile = os.environ.get("LIVE_DEPLOY_PROFILE", "all").strip() or "all" + if profile in {"full"}: + profile = "all" + if profile not in {"all", "hub", "business"}: + raise SystemExit(f"LIVE_DEPLOY_PROFILE must be all, hub, or business; got {profile!r}") + return DeployConfig( + host=os.environ.get("LIVE_DEPLOY_HOST", "192.168.2.101"), + user=os.environ.get("LIVE_DEPLOY_USER", "eric"), + password=os.environ.get("LIVE_DEPLOY_PASS", ""), + port=int(os.environ.get("LIVE_DEPLOY_PORT", os.environ.get("LIVE_SSH_PORT", "22"))), + remote_path=os.environ.get("LIVE_DEPLOY_PATH", "/opt/live/d2ypp").rstrip("/"), + profile=profile, + run_install=_env_bool("LIVE_DEPLOY_RUN_INSTALL", True), + timeout=int(os.environ.get("LIVE_DEPLOY_TIMEOUT", "3600")), + jump_host=os.environ.get("LIVE_DEPLOY_JUMP_HOST", ""), + jump_port=int(os.environ.get("LIVE_DEPLOY_JUMP_PORT", "22")), + jump_user=os.environ.get("LIVE_DEPLOY_JUMP_USER", ""), + jump_pass=os.environ.get("LIVE_DEPLOY_JUMP_PASS", ""), + ) + + +def _safe_print(text: str) -> None: + try: + print(text) + except UnicodeEncodeError: + enc = getattr(sys.stdout, "encoding", None) or "utf-8" + sys.stdout.buffer.write(text.encode(enc, errors="replace") + b"\n") + + +def _decode(data: bytes) -> str: + return data.decode("utf-8", errors="replace") if data else "" + + +def _redact(text: str, secret: str) -> str: + return text.replace(secret, "") if secret else text + + +def _revision() -> str: + try: + return subprocess.check_output( + ["git", "rev-parse", "--short", "HEAD"], + cwd=REPO_ROOT.parent, + text=True, + stderr=subprocess.DEVNULL, + ).strip() + except Exception: + return "unknown" + + +def _matches_exclude(rel: str, pattern: str) -> bool: + rel = rel.strip("/") + pattern = pattern.strip("/") + if not rel or not pattern: + return False + if rel == pattern or rel.startswith(pattern + "/"): + return True + return fnmatch.fnmatch(rel, pattern) + + +def _tar_filter(info: tarfile.TarInfo) -> tarfile.TarInfo | None: + rel = info.name.replace("\\", "/").removeprefix("./").strip("/") + if not rel: + return info + if rel == "config" or rel.startswith("config/"): + if rel == "config" or info.isdir() or any(fnmatch.fnmatch(rel, pattern) for pattern in CONFIG_ARCHIVE_INCLUDES): + return info + return None + for pattern in SOURCE_ARCHIVE_EXCLUDES: + if _matches_exclude(rel, pattern): + return None + return info + + +def create_source_archive(stamp: str) -> Path: + archive = Path(tempfile.gettempdir()) / f"d2ypp2-full-{stamp}.tar.gz" + with tarfile.open(archive, "w:gz") as tf: + tf.add(REPO_ROOT, arcname=".", filter=_tar_filter) + return archive + + +def _mkdir_p(sftp, remote_dir: str) -> None: + remote_dir = remote_dir.replace("\\", "/").rstrip("/") + if not remote_dir or remote_dir == "/": + return + cur = "" + for part in [p for p in remote_dir.split("/") if p]: + cur = f"{cur}/{part}" if cur else f"/{part}" + try: + sftp.stat(cur) + except OSError: + try: + sftp.mkdir(cur) + except OSError: + pass + + +def _sftp_put_text(sftp, text: str, remote_path: str) -> None: + _mkdir_p(sftp, posixpath.dirname(remote_path)) + data = text.replace("\r\n", "\n").replace("\r", "\n").encode("utf-8") + sftp.putfo(io.BytesIO(data), remote_path) + sftp.chmod(remote_path, 0o755) + + +def connect(config: DeployConfig): + try: + import paramiko + except ImportError as exc: + raise SystemExit("Install paramiko first: python -m pip install paramiko") from exc + + sock = None + jump = None + if config.jump_host: + jump = paramiko.SSHClient() + jump.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + jump.connect( + config.jump_host, + port=config.jump_port, + username=config.jump_user or config.user, + password=config.jump_pass or config.password, + timeout=30, + banner_timeout=40, + auth_timeout=30, + ) + sock = jump.get_transport().open_channel( + "direct-tcpip", + (config.host, config.port), + ("127.0.0.1", 0), + timeout=30, + ) + + client = paramiko.SSHClient() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + if jump is not None: + client._live_jump_client = jump + client.connect( + config.host, + port=config.port, + username=config.user, + password=config.password, + sock=sock, + timeout=30, + banner_timeout=40, + auth_timeout=30, + ) + return client, client.open_sftp() + + +def build_remote_script() -> str: + rsync_excludes = " \\\n".join(f" --exclude={shlex.quote(value)}" for value in REMOTE_RSYNC_EXCLUDES) + obsolete_files = " ".join(shlex.quote(value) for value in OBSOLETE_SOURCE_RUNTIME_FILES) + return f"""#!/usr/bin/env bash +set -Eeuo pipefail + +ARCHIVE="$1" +TARGET="$2" +STAMP="$3" +REVISION="$4" +PROFILE="$5" +RUN_INSTALL="$6" + +case "$TARGET" in + ""|"/"|"/opt"|"/home"|"/var"|"/usr"|"/etc") + echo "[full-deploy] unsafe target: $TARGET" >&2 + exit 2 + ;; +esac + +STAGE="/tmp/d2ypp2-full-stage-${{STAMP}}" +LOG_DIR="${{TARGET}}/.deploy_logs" +FULL_LOG="${{LOG_DIR}}/full_deploy_${{STAMP}}.log" +mkdir -p "$(dirname "$TARGET")" "$TARGET" "$LOG_DIR" /opt/live/deploy_backups +exec > >(tee -a "$FULL_LOG") 2>&1 + +echo "[full-deploy] stamp=$STAMP revision=$REVISION target=$TARGET profile=$PROFILE run_install=$RUN_INSTALL" + +for cmd in tar rsync sed systemctl curl; do + if ! command -v "$cmd" >/dev/null 2>&1; then + echo "[full-deploy] missing required command: $cmd" >&2 + exit 3 + fi +done + +echo "[full-deploy] stopping control-plane services" +pkill -TERM -f "${{TARGET}}/web-console/node_modules/.bin/next build" 2>/dev/null || true +pkill -TERM -f "npm run build" 2>/dev/null || true +sleep 2 +pkill -KILL -f "${{TARGET}}/web-console/node_modules/.bin/next build" 2>/dev/null || true +systemctl stop live-edge-watch.service live-edge.service live-console.service 2>/dev/null || true + +BACKUP="/opt/live/deploy_backups/d2ypp-before-${{STAMP}}.tar.gz" +echo "[full-deploy] backup current tree to $BACKUP" +if [ -d "$TARGET" ]; then + tar -czf "$BACKUP" \\ + --exclude='./.venv' \\ + --exclude='./web-console/node_modules' \\ + --exclude='./web-console/.next' \\ + --exclude='./logs' \\ + --exclude='./downloads' \\ + --exclude='./backup_config' \\ + --exclude='./.pm2' \\ + --exclude='./.process_runner' \\ + --exclude='./services/neko/data' \\ + --exclude='./codex-live-stack.tgz' \\ + -C "$TARGET" . || true +fi + +echo "[full-deploy] extracting source archive" +rm -rf "$STAGE" +mkdir -p "$STAGE" +tar -xzf "$ARCHIVE" -C "$STAGE" + +echo "[full-deploy] normalizing Linux text files" +find "$STAGE" -type f \\( \\ + -name '*.sh' -o -name '*.py' -o -name 'Dockerfile' -o -name '*.cjs' -o -name '*.mjs' -o \\ + -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.json' -o -name '*.yml' -o -name '*.yaml' -o \\ + -name '*.ini' -o -name '*.conf' \\ +\\) -exec sed -i 's/\\r$//' {{}} + + +echo "[full-deploy] syncing source with runtime-state protection" +rsync -a --delete \\ +{rsync_excludes} \\ + "$STAGE"/ "$TARGET"/ | tee "${{LOG_DIR}}/rsync_items_${{STAMP}}.log" + +echo "[full-deploy] syncing config templates and missing default config only" +mkdir -p "$TARGET/config" "$TARGET/backup" +if [ -d "$STAGE/config" ]; then + rsync -a "$STAGE/config/" "$TARGET/config/" --include='*/' --include='*.example' --include='*.conf' --exclude='*' || true +fi +write_missing_config() {{ + local rel="$1" + local dest="$TARGET/config/$rel" + if [ -e "$dest" ]; then + cat >/dev/null + return 0 + fi + mkdir -p "$(dirname "$dest")" + cat >"$dest" + chmod 0666 "$dest" 2>/dev/null || true +}} +write_missing_config config.ini <<'EOF_CONFIG_INI' +EOF_CONFIG_INI +write_missing_config URL_config.ini <<'EOF_URL_CONFIG' +EOF_URL_CONFIG +write_missing_config youtube.ini <<'EOF_YOUTUBE_INI' +[youtube] +key = +rtmps = yes +bitrate = 4500 +fast_audio = 1 +EOF_YOUTUBE_INI +write_missing_config web2_bind_host.txt <<'EOF_WEB2_HOST' +0.0.0.0 +EOF_WEB2_HOST +write_missing_config web2_api_token.txt <<'EOF_WEB2_TOKEN' +EOF_WEB2_TOKEN +write_missing_config easytier_network.json <<'EOF_EASYTIER' +{{"networkName":"","networkSecret":"","peerUrls":[]}} +EOF_EASYTIER +if [ -d "$STAGE/backup" ]; then + rsync -a "$STAGE/backup/" "$TARGET/backup/" --include='*/' --include='*.py' --exclude='*' || true +fi + +cd "$TARGET" +rm -f {obsolete_files} 2>/dev/null || true +rm -rf src/__pycache__ backup/__pycache__ tests/__pycache__ __pycache__ 2>/dev/null || true +chmod +x install*.sh upgrade*.sh uninstall.sh doctor.sh web.sh dev.sh start.sh obs.sh probe-live.sh refresh-live-unit.sh 2>/dev/null || true +find scripts live-platform/scripts services/neko -type f -name '*.sh' -exec chmod +x {{}} + 2>/dev/null || true +find tools scripts live-platform/tools -type f -name '*.py' -exec chmod +x {{}} + 2>/dev/null || true + +echo "[full-deploy] preparing runtime permissions before install" +if id live >/dev/null 2>&1; then + chown -R live:live "$TARGET" 2>/dev/null || true +fi +chmod -R a+rwX "$TARGET" 2>/dev/null || true +if [ -f scripts/linux/lib/common.sh ]; then + bash -lc "cd '$TARGET'; . scripts/linux/lib/common.sh; ensure_live_user; load_env; ensure_runtime_dirs_owned_by_live" +fi + +printf 'stamp=%s\\nrevision=%s\\nprofile=%s\\narchive=%s\\n' "$STAMP" "$REVISION" "$PROFILE" "$ARCHIVE" > "${{LOG_DIR}}/deployed_${{STAMP}}.txt" + +if [ "$RUN_INSTALL" = "1" ]; then + echo "[full-deploy] running full stack installer" + LIVE_STACK_REPO_ROOT="$TARGET" bash scripts/linux/install_stack.sh "$PROFILE" +else + echo "[full-deploy] LIVE_DEPLOY_RUN_INSTALL=0; skipping installer" +fi + +echo "[full-deploy] final service refresh" +systemctl reset-failed dnsmasq.service 2>/dev/null || true +systemctl daemon-reload +systemctl try-restart live-console.service live-edge.service live-edge-watch.service live-neko-ip-watch.service live-webtty.service live-android-panel.service live-pulseaudio.service 2>/dev/null || true +systemctl start live-console.service 2>/dev/null || true +systemctl start live-edge.service live-edge-watch.service 2>/dev/null || true + +echo "[full-deploy] waiting for control plane health" +ok=0 +for _ in $(seq 1 75); do + if curl -sf -m 4 http://127.0.0.1:8001/health >/dev/null 2>&1; then + ok=1 + break + fi + sleep 2 +done +if [ "$ok" != "1" ]; then + echo "[full-deploy] ERROR: control plane did not become healthy" >&2 + journalctl -u live-console.service -n 120 --no-pager 2>/dev/null || true + exit 4 +fi +echo "[full-deploy] health_ok_8001" + +echo "[full-deploy] HTTP checks" +curl -sS -m 10 -o /dev/null -w 'root_http=%{{http_code}}\\n' http://127.0.0.1/ || true +curl -sS -m 10 -o /dev/null -w 'health_http=%{{http_code}}\\n' http://127.0.0.1:8001/health || true +curl -sS -m 10 http://127.0.0.1:8001/server_info | head -c 1200 || true +echo + +echo "[full-deploy] systemd state" +systemctl --no-pager --plain is-active live-console.service live-edge.service live-edge-watch.service live-neko-ip-watch.service live-webtty.service live-android-panel.service live-pulseaudio.service 2>/dev/null || true + +echo "[full-deploy] docker state" +docker ps -a --format '{{{{.Names}}}} {{{{.Status}}}}' 2>/dev/null | grep -E 'live-|redroid' | sort || true + +echo "[full-deploy] done" +""" + + +def execute_remote(ssh, config: DeployConfig, remote_script: str, remote_archive: str, stamp: str, revision: str) -> tuple[int, str]: + args = [ + remote_script, + remote_archive, + config.remote_path, + stamp, + revision, + config.profile, + "1" if config.run_install else "0", + ] + command = "sudo -S -p '' bash " + " ".join(shlex.quote(arg) for arg in args) + stdin, stdout, stderr = ssh.exec_command(command, timeout=config.timeout, get_pty=False) + stdin.write(config.password + "\n") + stdin.flush() + try: + stdin.channel.shutdown_write() + except Exception: + pass + out = _decode(stdout.read()) + err = _decode(stderr.read()) + code = stdout.channel.recv_exit_status() + return code, f"--- stdout ---\n{out}\n--- stderr ---\n{err}\n" + + +def main() -> int: + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + sys.stderr.reconfigure(encoding="utf-8", errors="replace") + + config = load_config() + if not config.password: + raise SystemExit("LIVE_DEPLOY_PASS is required for password and sudo authentication") + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + revision = _revision() + LOG_DIR.mkdir(parents=True, exist_ok=True) + local_log = LOG_DIR / f"full_deploy_{stamp}.log" + local_log.write_text( + f"full deploy {stamp} revision={revision} -> {config.user}@{config.host}:{config.port}:{config.remote_path}\n", + encoding="utf-8", + ) + + archive = create_source_archive(stamp) + _safe_print(f"local archive: {archive} ({archive.stat().st_size} bytes)") + remote_archive = f"/tmp/d2ypp2-full-{stamp}.tar.gz" + remote_script = f"/tmp/d2ypp2-full-deploy-{stamp}.sh" + + ssh = None + sftp = None + try: + ssh, sftp = connect(config) + _safe_print(f"uploading archive to {remote_archive}") + sftp.put(str(archive), remote_archive) + _sftp_put_text(sftp, build_remote_script(), remote_script) + sftp.close() + sftp = None + + _safe_print("running remote full deployment") + code, output = execute_remote(ssh, config, remote_script, remote_archive, stamp, revision) + output = _redact(output, config.password) + with local_log.open("a", encoding="utf-8", errors="replace") as fh: + fh.write(output) + tail = "\n".join(output.splitlines()[-140:]) + _safe_print(tail) + _safe_print(f"local log: {local_log}") + return code + finally: + if sftp is not None: + sftp.close() + if ssh is not None: + ssh.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/d2ypp2/tools/render_neko_compose.py b/d2ypp2/tools/render_neko_compose.py index b002df7..7aa616b 100644 --- a/d2ypp2/tools/render_neko_compose.py +++ b/d2ypp2/tools/render_neko_compose.py @@ -175,7 +175,7 @@ def main() -> int: parser.add_argument("--count", type=int, required=True) parser.add_argument("--output", required=True) args = parser.parse_args() - count = max(2, min(64, args.count)) + count = max(1, min(64, args.count)) output = Path(args.output) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(render(count), encoding="utf-8") diff --git a/d2ypp2/web-console/components/live-product/LiveControlApp.tsx b/d2ypp2/web-console/components/live-product/LiveControlApp.tsx index bb7e445..f93b28d 100644 --- a/d2ypp2/web-console/components/live-product/LiveControlApp.tsx +++ b/d2ypp2/web-console/components/live-product/LiveControlApp.tsx @@ -2245,6 +2245,7 @@ export default function LiveControlApp() { liveProcesses={processRows.length ? processRows : (dash?.live?.processes ?? [])} notify={notify} quickLinks={ql} + onRefresh={() => refreshDashboard()} onNavigate={(target: PortalNavTarget) => setView(target)} /> ) : null} diff --git a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx index 7139e5a..a4eb5fe 100644 --- a/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx +++ b/d2ypp2/web-console/components/live-product/LiveYoutubeUnmannedView.tsx @@ -47,6 +47,7 @@ type NekoActionResult = { id?: number; action?: string; container?: string; + configured_count?: number; exists?: boolean; running?: boolean; status?: string; @@ -608,6 +609,7 @@ type Props = { liveProcesses: LiveProcRow[]; notify: (msg: string) => void; onNavigate?: (target: PortalNavTarget) => void; + onRefresh?: () => void | Promise; quickLinks?: QuickLinkMap; }; @@ -625,6 +627,7 @@ export function LiveYoutubeUnmannedView({ liveProcesses, notify, onNavigate, + onRefresh, quickLinks, }: Props) { const ytEntries = useMemo(() => entries.filter(isYoutubeProcess), [entries]); @@ -1677,6 +1680,7 @@ export function LiveYoutubeUnmannedView({ : t("容器不存在", "missing"); const message = result.message || `${link.label}: ${state}`; setNekoActionNote(`${message} · ${state}`); + await onRefresh?.(); } catch (e) { const message = (e as Error).message; setNekoActionNote(message); @@ -1685,7 +1689,7 @@ export function LiveYoutubeUnmannedView({ setNekoBusy(null); } }, - [fetchJson, nekoBusy, notify, t], + [fetchJson, nekoBusy, notify, onRefresh, t], ); const flushProChannelsBeforeRun = useCallback( @@ -1831,6 +1835,8 @@ export function LiveYoutubeUnmannedView({ const stopBusy = nekoBusy === `${link.id}:stop`; const deleteBusy = nekoBusy === `${link.id}:delete`; const disabled = !!nekoBusy; + const canDelete = link.id === nekoLinks.length && nekoLinks.length > 1; + const deleteDisabled = disabled || !canDelete; return (