Harden Neko deploy against CrashCore UDP conflicts and CRLF env breakage.
Autofix WebRTC ranges before compose up, strip CR from stack env, and fail start when instances are unhealthy. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
9e267366ef
commit
88ad82add0
@ -153,12 +153,14 @@ NEKO_MANAGED_POLICIES=1
|
|||||||
NEKO_TAMPERMONKEY_REPAIR=1
|
NEKO_TAMPERMONKEY_REPAIR=1
|
||||||
# YouTube Studio 页面实时采集 Chrome 扩展:抓取在线人数、直播状态、健康提示、弹窗内容并写入控制台事件库。
|
# YouTube Studio 页面实时采集 Chrome 扩展:抓取在线人数、直播状态、健康提示、弹窗内容并写入控制台事件库。
|
||||||
NEKO_LIVE_OPS_EXTENSION=1
|
NEKO_LIVE_OPS_EXTENSION=1
|
||||||
NEKO_WEBRTC_EPR=52000-52099
|
# ICE UDP 段默认避开 52099:ShellCrash CrashCore 常占用该口,否则 live-neko-1 会 bind 失败。
|
||||||
NEKO_WEBRTC_EPR_1=52000-52099
|
# 部署时 render_neko_compose.py 仍会探测外国进程并自动收缩/平移端口。
|
||||||
|
NEKO_WEBRTC_EPR=52000-52098
|
||||||
|
NEKO_WEBRTC_EPR_1=52000-52098
|
||||||
NEKO_WEBRTC_EPR_2=52101-52199
|
NEKO_WEBRTC_EPR_2=52101-52199
|
||||||
NEKO_WEBRTC_EPR_3=52201-52299
|
NEKO_WEBRTC_EPR_3=52201-52299
|
||||||
NEKO_WEBRTC_UDP_RANGE=52000-52099
|
NEKO_WEBRTC_UDP_RANGE=52000-52098
|
||||||
NEKO_WEBRTC_UDP_RANGE_1=52000-52099
|
NEKO_WEBRTC_UDP_RANGE_1=52000-52098
|
||||||
NEKO_WEBRTC_UDP_RANGE_2=52101-52199
|
NEKO_WEBRTC_UDP_RANGE_2=52101-52199
|
||||||
NEKO_WEBRTC_UDP_RANGE_3=52201-52299
|
NEKO_WEBRTC_UDP_RANGE_3=52201-52299
|
||||||
NEKO_WEBRTC_ICELITE=0
|
NEKO_WEBRTC_ICELITE=0
|
||||||
|
|||||||
@ -17,8 +17,8 @@
|
|||||||
"NEKO_MAX_FPS": "15",
|
"NEKO_MAX_FPS": "15",
|
||||||
"NEKO_VIDEO_BITRATE": "1200",
|
"NEKO_VIDEO_BITRATE": "1200",
|
||||||
"NEKO_BROWSER_RENDER_MODE": "auto",
|
"NEKO_BROWSER_RENDER_MODE": "auto",
|
||||||
"NEKO_WEBRTC_UDP_RANGE": "52000-52099",
|
"NEKO_WEBRTC_UDP_RANGE": "52000-52098",
|
||||||
"NEKO_WEBRTC_UDP_RANGE_1": "52000-52099",
|
"NEKO_WEBRTC_UDP_RANGE_1": "52000-52098",
|
||||||
"NEKO_WEBRTC_UDP_RANGE_2": "52101-52199",
|
"NEKO_WEBRTC_UDP_RANGE_2": "52101-52199",
|
||||||
"NEKO_WEBRTC_UDP_RANGE_3": "52201-52299",
|
"NEKO_WEBRTC_UDP_RANGE_3": "52201-52299",
|
||||||
"NEKO_WEBRTC_TCPMUX": "52300",
|
"NEKO_WEBRTC_TCPMUX": "52300",
|
||||||
|
|||||||
@ -364,7 +364,7 @@ load_env() {
|
|||||||
NEKO_WEBRTC_UDPMUX_1="${NEKO_WEBRTC_UDPMUX_1:-$NEKO_WEBRTC_UDPMUX}"
|
NEKO_WEBRTC_UDPMUX_1="${NEKO_WEBRTC_UDPMUX_1:-$NEKO_WEBRTC_UDPMUX}"
|
||||||
NEKO_WEBRTC_UDPMUX_2="${NEKO_WEBRTC_UDPMUX_2:-52301}"
|
NEKO_WEBRTC_UDPMUX_2="${NEKO_WEBRTC_UDPMUX_2:-52301}"
|
||||||
NEKO_WEBRTC_UDPMUX_3="${NEKO_WEBRTC_UDPMUX_3:-52302}"
|
NEKO_WEBRTC_UDPMUX_3="${NEKO_WEBRTC_UDPMUX_3:-52302}"
|
||||||
NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52099}"
|
NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52098}"
|
||||||
NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
||||||
NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
||||||
NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
||||||
@ -936,7 +936,14 @@ render_neko_compose_file() {
|
|||||||
local count out
|
local count out
|
||||||
count="$(resolve_neko_instance_count)"
|
count="$(resolve_neko_instance_count)"
|
||||||
out="$ROOT_DIR/services/neko/docker-compose.generated.yml"
|
out="$ROOT_DIR/services/neko/docker-compose.generated.yml"
|
||||||
python3 "$ROOT_DIR/tools/render_neko_compose.py" --count "$count" --output "$out"
|
python3 "$ROOT_DIR/tools/render_neko_compose.py" \
|
||||||
|
--count "$count" \
|
||||||
|
--output "$out" \
|
||||||
|
--stack-env "$STACK_ENV"
|
||||||
|
if [ -f "$STACK_ENV" ]; then
|
||||||
|
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||||
|
set -a && . "$STACK_ENV" && set +a
|
||||||
|
fi
|
||||||
printf '%s' "$out"
|
printf '%s' "$out"
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2479,7 +2486,7 @@ install_neko_browser() {
|
|||||||
export NEKO_DESKTOP_SCREEN="${NEKO_DESKTOP_SCREEN:-1280x720@15}"
|
export NEKO_DESKTOP_SCREEN="${NEKO_DESKTOP_SCREEN:-1280x720@15}"
|
||||||
export NEKO_BROWSER_PROXY="$(resolve_neko_browser_proxy)"
|
export NEKO_BROWSER_PROXY="$(resolve_neko_browser_proxy)"
|
||||||
export NEKO_BROWSER_PROXY_BYPASS="${NEKO_BROWSER_PROXY_BYPASS:-$(neko_default_proxy_bypass)}"
|
export NEKO_BROWSER_PROXY_BYPASS="${NEKO_BROWSER_PROXY_BYPASS:-$(neko_default_proxy_bypass)}"
|
||||||
export NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52099}"
|
export NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52098}"
|
||||||
export NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
export NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
||||||
export NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
export NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
||||||
export NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
export NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
||||||
|
|||||||
@ -8,6 +8,7 @@ INSTALL_TAG="${INSTALL_TAG:-neko-ip-watch}"
|
|||||||
reload_watch_env() {
|
reload_watch_env() {
|
||||||
unset ENABLE_NEKO NEKO_ACCESS_MODE NEKO_WEBRTC_NAT1TO1 NEKO_IP_WATCH_INTERVAL
|
unset ENABLE_NEKO NEKO_ACCESS_MODE NEKO_WEBRTC_NAT1TO1 NEKO_IP_WATCH_INTERVAL
|
||||||
if [ -f "$STACK_ENV" ]; then
|
if [ -f "$STACK_ENV" ]; then
|
||||||
|
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||||
set -a
|
set -a
|
||||||
. "$STACK_ENV"
|
. "$STACK_ENV"
|
||||||
set +a
|
set +a
|
||||||
|
|||||||
@ -26,8 +26,15 @@ COTURN_COMPOSE="$ROOT_DIR/services/coturn/docker-compose.yml"
|
|||||||
BROWSER_LAUNCHER="$ROOT_DIR/scripts/linux/launch_browser.sh"
|
BROWSER_LAUNCHER="$ROOT_DIR/scripts/linux/launch_browser.sh"
|
||||||
KMSCUBE_LAUNCHER="$ROOT_DIR/scripts/linux/run_kmscube.sh"
|
KMSCUBE_LAUNCHER="$ROOT_DIR/scripts/linux/run_kmscube.sh"
|
||||||
|
|
||||||
[ -f "$STACK_ENV" ] && set -a && . "$STACK_ENV" && set +a
|
# SFTP/Windows editors often leave CR; sourcing then breaks ports as "9200\r".
|
||||||
[ -f "$HW_ENV" ] && set -a && . "$HW_ENV" && set +a
|
if [ -f "$STACK_ENV" ]; then
|
||||||
|
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||||
|
set -a && . "$STACK_ENV" && set +a
|
||||||
|
fi
|
||||||
|
if [ -f "$HW_ENV" ]; then
|
||||||
|
sed -i 's/\r$//' "$HW_ENV" 2>/dev/null || true
|
||||||
|
set -a && . "$HW_ENV" && set +a
|
||||||
|
fi
|
||||||
|
|
||||||
HOSTNAME_ALIAS="${HOSTNAME_ALIAS:-live}"
|
HOSTNAME_ALIAS="${HOSTNAME_ALIAS:-live}"
|
||||||
PORT="${PORT:-8001}"
|
PORT="${PORT:-8001}"
|
||||||
@ -86,7 +93,8 @@ NEKO_WEBRTC_TCPMUX_3="${NEKO_WEBRTC_TCPMUX_3:-52302}"
|
|||||||
NEKO_WEBRTC_UDPMUX_1="${NEKO_WEBRTC_UDPMUX_1:-$NEKO_WEBRTC_UDPMUX}"
|
NEKO_WEBRTC_UDPMUX_1="${NEKO_WEBRTC_UDPMUX_1:-$NEKO_WEBRTC_UDPMUX}"
|
||||||
NEKO_WEBRTC_UDPMUX_2="${NEKO_WEBRTC_UDPMUX_2:-52301}"
|
NEKO_WEBRTC_UDPMUX_2="${NEKO_WEBRTC_UDPMUX_2:-52301}"
|
||||||
NEKO_WEBRTC_UDPMUX_3="${NEKO_WEBRTC_UDPMUX_3:-52302}"
|
NEKO_WEBRTC_UDPMUX_3="${NEKO_WEBRTC_UDPMUX_3:-52302}"
|
||||||
NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52099}"
|
# Default ends at .98: ShellCrash CrashCore has been observed binding UDP 52099.
|
||||||
|
NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52098}"
|
||||||
NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
||||||
NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
||||||
NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
||||||
@ -219,11 +227,15 @@ stack_env_upsert() {
|
|||||||
[ -n "$key" ] || return 1
|
[ -n "$key" ] || return 1
|
||||||
mkdir -p "$(dirname "$STACK_ENV")"
|
mkdir -p "$(dirname "$STACK_ENV")"
|
||||||
touch "$STACK_ENV"
|
touch "$STACK_ENV"
|
||||||
|
# Always keep Unix newlines; CR breaks `source` and docker publish ports.
|
||||||
|
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||||
|
value="${value//$'\r'/}"
|
||||||
if grep -q "^${key}=" "$STACK_ENV" 2>/dev/null; then
|
if grep -q "^${key}=" "$STACK_ENV" 2>/dev/null; then
|
||||||
sed -i "s/^${key}=.*/${key}=${value}/" "$STACK_ENV"
|
sed -i "s|^${key}=.*|${key}=${value}|" "$STACK_ENV"
|
||||||
else
|
else
|
||||||
printf '%s=%s\n' "$key" "$value" >>"$STACK_ENV"
|
printf '%s=%s\n' "$key" "$value" >>"$STACK_ENV"
|
||||||
fi
|
fi
|
||||||
|
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||||
}
|
}
|
||||||
|
|
||||||
neko_browser_proxy_auto_enable_if_needed() {
|
neko_browser_proxy_auto_enable_if_needed() {
|
||||||
@ -777,7 +789,16 @@ render_neko_compose_file() {
|
|||||||
local count out
|
local count out
|
||||||
count="$(resolve_neko_instance_count)"
|
count="$(resolve_neko_instance_count)"
|
||||||
out="$ROOT_DIR/services/neko/docker-compose.generated.yml"
|
out="$ROOT_DIR/services/neko/docker-compose.generated.yml"
|
||||||
python3 "$ROOT_DIR/tools/render_neko_compose.py" --count "$count" --output "$out"
|
# Autofix skips CrashCore/foreign UDP holders inside ICE ranges and strips CRLF in stack env.
|
||||||
|
python3 "$ROOT_DIR/tools/render_neko_compose.py" \
|
||||||
|
--count "$count" \
|
||||||
|
--output "$out" \
|
||||||
|
--stack-env "$STACK_ENV"
|
||||||
|
# Reload ranges if renderer persisted changes.
|
||||||
|
if [ -f "$STACK_ENV" ]; then
|
||||||
|
sed -i 's/\r$//' "$STACK_ENV" 2>/dev/null || true
|
||||||
|
set -a && . "$STACK_ENV" && set +a
|
||||||
|
fi
|
||||||
printf '%s' "$out"
|
printf '%s' "$out"
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2509,6 +2530,10 @@ service_neko_start() {
|
|||||||
compose_file="$(render_neko_compose_file)"
|
compose_file="$(render_neko_compose_file)"
|
||||||
# shellcheck disable=SC2086
|
# shellcheck disable=SC2086
|
||||||
compose_in_service_dir "$compose_file" up -d $service_names
|
compose_in_service_dir "$compose_file" up -d $service_names
|
||||||
|
if ! verify_neko_instances_running "$instance_count"; then
|
||||||
|
kv message "Neko start incomplete; UDP port conflict autofix may need reconfigure. Check CrashCore/ss -ulnp"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
kv message "Neko stack started (${instance_count} browser instances)"
|
kv message "Neko stack started (${instance_count} browser instances)"
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2535,6 +2560,10 @@ service_neko_reconfigure() {
|
|||||||
# Recreate containers so WebRTC env changes take effect; profile volumes are left untouched.
|
# Recreate containers so WebRTC env changes take effect; profile volumes are left untouched.
|
||||||
# shellcheck disable=SC2086
|
# shellcheck disable=SC2086
|
||||||
compose_in_service_dir "$compose_file" up -d --force-recreate $service_names
|
compose_in_service_dir "$compose_file" up -d --force-recreate $service_names
|
||||||
|
if ! verify_neko_instances_running "$instance_count"; then
|
||||||
|
kv message "Neko reconfigure incomplete; inspect docker logs / ss -ulnp for UDP conflicts"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
kv message "Neko WebRTC config reapplied (${instance_count} browser instances)"
|
kv message "Neko WebRTC config reapplied (${instance_count} browser instances)"
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2576,7 +2605,7 @@ export_neko_env() {
|
|||||||
export NEKO_BROWSER_PROXY_BYPASS="${NEKO_BROWSER_PROXY_BYPASS:-$(neko_default_proxy_bypass)}"
|
export NEKO_BROWSER_PROXY_BYPASS="${NEKO_BROWSER_PROXY_BYPASS:-$(neko_default_proxy_bypass)}"
|
||||||
export NEKO_MANAGED_POLICIES="${NEKO_MANAGED_POLICIES:-1}"
|
export NEKO_MANAGED_POLICIES="${NEKO_MANAGED_POLICIES:-1}"
|
||||||
export NEKO_TAMPERMONKEY_REPAIR="${NEKO_TAMPERMONKEY_REPAIR:-1}"
|
export NEKO_TAMPERMONKEY_REPAIR="${NEKO_TAMPERMONKEY_REPAIR:-1}"
|
||||||
export NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52099}"
|
export NEKO_WEBRTC_UDP_RANGE="${NEKO_WEBRTC_UDP_RANGE:-52000-52098}"
|
||||||
export NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
export NEKO_WEBRTC_UDP_RANGE_1="${NEKO_WEBRTC_UDP_RANGE_1:-$NEKO_WEBRTC_UDP_RANGE}"
|
||||||
export NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
export NEKO_WEBRTC_UDP_RANGE_2="${NEKO_WEBRTC_UDP_RANGE_2:-52101-52199}"
|
||||||
export NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
export NEKO_WEBRTC_UDP_RANGE_3="${NEKO_WEBRTC_UDP_RANGE_3:-52201-52299}"
|
||||||
@ -2610,6 +2639,27 @@ export_neko_env() {
|
|||||||
export NEKO_PLUGINS_ENABLED="${NEKO_PLUGINS_ENABLED:-true}"
|
export NEKO_PLUGINS_ENABLED="${NEKO_PLUGINS_ENABLED:-true}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
verify_neko_instances_running() {
|
||||||
|
local count="${1:-}" idx name port state code failed=0
|
||||||
|
[ -n "$count" ] || count="$(resolve_neko_instance_count)"
|
||||||
|
sleep 2
|
||||||
|
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)"
|
||||||
|
code="$(neko_http_probe_code "$port")"
|
||||||
|
if [[ "$state" != running* ]] || [ "$code" = "000" ]; then
|
||||||
|
failed=1
|
||||||
|
kv message "Neko instance ${idx} unhealthy state=${state:-missing} http=${code} port=${port}"
|
||||||
|
if have docker; then
|
||||||
|
docker inspect "$name" --format 'err={{.State.Error}} exit={{.State.ExitCode}}' 2>/dev/null || true
|
||||||
|
docker logs --tail 30 "$name" 2>&1 | tail -20 || true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
return "$failed"
|
||||||
|
}
|
||||||
|
|
||||||
service_neko_stop() {
|
service_neko_stop() {
|
||||||
if [ ! -f "$ROOT_DIR/tools/render_neko_compose.py" ]; then
|
if [ ! -f "$ROOT_DIR/tools/render_neko_compose.py" ]; then
|
||||||
kv message "Neko compose missing"
|
kv message "Neko compose missing"
|
||||||
|
|||||||
221
d2ypp2/src/neko_webrtc_ports.py
Normal file
221
d2ypp2/src/neko_webrtc_ports.py
Normal file
@ -0,0 +1,221 @@
|
|||||||
|
"""Neko WebRTC UDP range helpers.
|
||||||
|
|
||||||
|
ShellCrash CrashCore (and similar) sometimes bind a UDP port inside the default
|
||||||
|
Neko ICE range (e.g. 52099 inside 52000-52099). Docker then fails with
|
||||||
|
``address already in use`` and leaves live-neko-N exited. Detect foreign holders
|
||||||
|
and shrink/shift the published range before compose up.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_SS_PORT_RE = re.compile(r":(\d+)\s")
|
||||||
|
_PROC_RE = re.compile(r'users:\(\("([^"]+)"')
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_env_text(value: str) -> str:
|
||||||
|
return (value or "").replace("\r", "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_udp_range(value: str, default: str) -> tuple[int, int]:
|
||||||
|
raw = sanitize_env_text(value) or default
|
||||||
|
match = re.fullmatch(r"(\d+)\s*-\s*(\d+)", raw)
|
||||||
|
if not match:
|
||||||
|
match = re.fullmatch(r"(\d+)\s*-\s*(\d+)", default)
|
||||||
|
if not match:
|
||||||
|
raise ValueError(f"invalid udp range: {value!r}")
|
||||||
|
start, end = int(match.group(1)), int(match.group(2))
|
||||||
|
if end < start:
|
||||||
|
start, end = end, start
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
|
||||||
|
def format_udp_range(start: int, end: int) -> str:
|
||||||
|
return f"{start}-{end}"
|
||||||
|
|
||||||
|
|
||||||
|
def default_udp_range(idx: int) -> str:
|
||||||
|
# End at .98 so the historically CrashCore-bound .99 is outside the default.
|
||||||
|
if idx == 1:
|
||||||
|
return "52000-52098"
|
||||||
|
if idx == 2:
|
||||||
|
return "52101-52199"
|
||||||
|
if idx == 3:
|
||||||
|
return "52201-52299"
|
||||||
|
start = 52400 + ((idx - 4) * 100)
|
||||||
|
return f"{start}-{start + 99}"
|
||||||
|
|
||||||
|
|
||||||
|
def _ignore_process(name: str) -> bool:
|
||||||
|
lowered = (name or "").lower()
|
||||||
|
return lowered in {
|
||||||
|
"docker-proxy",
|
||||||
|
"docker",
|
||||||
|
"dockerd",
|
||||||
|
"containerd",
|
||||||
|
"containerd-shim",
|
||||||
|
"containerd-shim-runc-v2",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def list_foreign_udp_holders(start: int, end: int) -> dict[int, str]:
|
||||||
|
"""Return {port: process} for UDP listeners in [start, end] not owned by Docker."""
|
||||||
|
if start > end:
|
||||||
|
return {}
|
||||||
|
if os.environ.get("NEKO_SKIP_UDP_PORT_PROBE", "").strip() in {"1", "true", "yes", "on"}:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
["ss", "-ulnpH"],
|
||||||
|
check=False,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=5,
|
||||||
|
)
|
||||||
|
except (OSError, subprocess.TimeoutExpired):
|
||||||
|
return {}
|
||||||
|
holders: dict[int, str] = {}
|
||||||
|
for line in (proc.stdout or "").splitlines():
|
||||||
|
ports = [int(p) for p in _SS_PORT_RE.findall(line)]
|
||||||
|
if not ports:
|
||||||
|
continue
|
||||||
|
proc_match = _PROC_RE.search(line)
|
||||||
|
proc_name = proc_match.group(1) if proc_match else "unknown"
|
||||||
|
if _ignore_process(proc_name):
|
||||||
|
continue
|
||||||
|
for port in ports:
|
||||||
|
if start <= port <= end:
|
||||||
|
holders[port] = proc_name
|
||||||
|
return holders
|
||||||
|
|
||||||
|
|
||||||
|
def fit_udp_range(start: int, end: int, blocked: set[int], *, min_ports: int = 16) -> tuple[int, int]:
|
||||||
|
"""Keep start when possible; shrink end around foreign holders; else shift nearby."""
|
||||||
|
width = max(1, end - start + 1)
|
||||||
|
blocked_in = {p for p in blocked if start <= p <= end}
|
||||||
|
if not blocked_in:
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
# Prefer keeping the original start and cutting before the first blocker.
|
||||||
|
first_block = min(blocked_in)
|
||||||
|
shrunk_end = first_block - 1
|
||||||
|
if shrunk_end - start + 1 >= min_ports:
|
||||||
|
return start, shrunk_end
|
||||||
|
|
||||||
|
# Search for a free window of the original width near the intended range.
|
||||||
|
search_lo = max(1024, start - 200)
|
||||||
|
search_hi = end + 800
|
||||||
|
for cand_start in range(search_lo, search_hi + 1):
|
||||||
|
cand_end = cand_start + width - 1
|
||||||
|
if any(p in blocked for p in range(cand_start, cand_end + 1)):
|
||||||
|
continue
|
||||||
|
return cand_start, cand_end
|
||||||
|
|
||||||
|
# Last resort: largest prefix free from start.
|
||||||
|
if shrunk_end >= start:
|
||||||
|
return start, shrunk_end
|
||||||
|
return start, start
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_env_file(path: Path, updates: dict[str, str]) -> None:
|
||||||
|
"""Write KEY=VALUE with Unix newlines; strip any existing CR."""
|
||||||
|
if not updates:
|
||||||
|
return
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
raw = path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""
|
||||||
|
raw = raw.replace("\r\n", "\n").replace("\r", "\n")
|
||||||
|
lines = raw.split("\n")
|
||||||
|
# Drop trailing empty line artifact for rewrite; restore one at end.
|
||||||
|
if lines and lines[-1] == "":
|
||||||
|
lines = lines[:-1]
|
||||||
|
seen: set[str] = set()
|
||||||
|
out: list[str] = []
|
||||||
|
for line in lines:
|
||||||
|
matched = False
|
||||||
|
for key, value in updates.items():
|
||||||
|
if line.startswith(f"{key}=") or line.startswith(f"export {key}="):
|
||||||
|
out.append(f"{key}={value}")
|
||||||
|
seen.add(key)
|
||||||
|
matched = True
|
||||||
|
break
|
||||||
|
if not matched:
|
||||||
|
out.append(line)
|
||||||
|
for key, value in updates.items():
|
||||||
|
if key not in seen:
|
||||||
|
out.append(f"{key}={value}")
|
||||||
|
path.write_text("\n".join(out) + "\n", encoding="utf-8", newline="\n")
|
||||||
|
|
||||||
|
|
||||||
|
def apply_neko_udp_range_autofix(
|
||||||
|
count: int,
|
||||||
|
*,
|
||||||
|
stack_env: Path | None = None,
|
||||||
|
persist: bool = True,
|
||||||
|
) -> list[dict[str, str]]:
|
||||||
|
"""Adjust NEKO_WEBRTC_UDP_RANGE_* / EPR_* in os.environ; optionally persist.
|
||||||
|
|
||||||
|
Returns a list of change records for logging.
|
||||||
|
"""
|
||||||
|
changes: list[dict[str, str]] = []
|
||||||
|
updates: dict[str, str] = {}
|
||||||
|
# Collect all blocked ports across candidate ranges so shifted windows stay free.
|
||||||
|
probe_lo, probe_hi = 52000, 53000
|
||||||
|
blocked = set(list_foreign_udp_holders(probe_lo, probe_hi))
|
||||||
|
|
||||||
|
for idx in range(1, max(1, count) + 1):
|
||||||
|
default = default_udp_range(idx)
|
||||||
|
udp_key = f"NEKO_WEBRTC_UDP_RANGE_{idx}"
|
||||||
|
epr_key = f"NEKO_WEBRTC_EPR_{idx}"
|
||||||
|
# Fallbacks mirror bash / renderer precedence.
|
||||||
|
raw_udp = (
|
||||||
|
os.environ.get(udp_key)
|
||||||
|
or (os.environ.get("NEKO_WEBRTC_UDP_RANGE") if idx == 1 else None)
|
||||||
|
or default
|
||||||
|
)
|
||||||
|
start, end = parse_udp_range(raw_udp, default)
|
||||||
|
# Re-probe exact window in case the wide probe missed a late bind.
|
||||||
|
blocked.update(list_foreign_udp_holders(start, end))
|
||||||
|
new_start, new_end = fit_udp_range(start, end, blocked)
|
||||||
|
new_range = format_udp_range(new_start, new_end)
|
||||||
|
old_range = format_udp_range(start, end)
|
||||||
|
holders = {p: n for p, n in list_foreign_udp_holders(start, end).items()}
|
||||||
|
if new_range != old_range:
|
||||||
|
changes.append(
|
||||||
|
{
|
||||||
|
"instance": str(idx),
|
||||||
|
"from": old_range,
|
||||||
|
"to": new_range,
|
||||||
|
"holders": ",".join(f"{p}={name}" for p, name in sorted(holders.items())),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
# Reserve chosen window so later instances do not collide when shifting.
|
||||||
|
blocked.update(range(new_start, new_end + 1))
|
||||||
|
os.environ[udp_key] = new_range
|
||||||
|
os.environ[epr_key] = new_range
|
||||||
|
updates[udp_key] = new_range
|
||||||
|
updates[epr_key] = new_range
|
||||||
|
if idx == 1:
|
||||||
|
os.environ["NEKO_WEBRTC_UDP_RANGE"] = new_range
|
||||||
|
os.environ["NEKO_WEBRTC_EPR"] = new_range
|
||||||
|
updates["NEKO_WEBRTC_UDP_RANGE"] = new_range
|
||||||
|
updates["NEKO_WEBRTC_EPR"] = new_range
|
||||||
|
|
||||||
|
if persist and stack_env is not None and updates:
|
||||||
|
needs_write = bool(changes)
|
||||||
|
if stack_env.exists():
|
||||||
|
existing = stack_env.read_text(encoding="utf-8", errors="replace")
|
||||||
|
if "\r" in existing:
|
||||||
|
needs_write = True
|
||||||
|
else:
|
||||||
|
for key, value in updates.items():
|
||||||
|
if not re.search(rf"^{re.escape(key)}={re.escape(value)}$", existing, re.M):
|
||||||
|
needs_write = True
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
needs_write = True
|
||||||
|
if needs_write:
|
||||||
|
upsert_env_file(stack_env, updates)
|
||||||
|
return changes
|
||||||
102
d2ypp2/tests/test_neko_webrtc_ports.py
Normal file
102
d2ypp2/tests/test_neko_webrtc_ports.py
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
|
||||||
|
|
||||||
|
def _load():
|
||||||
|
path = ROOT / "src" / "neko_webrtc_ports.py"
|
||||||
|
spec = importlib.util.spec_from_file_location("neko_webrtc_ports", path)
|
||||||
|
assert spec and spec.loader
|
||||||
|
mod = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(mod)
|
||||||
|
return mod
|
||||||
|
|
||||||
|
|
||||||
|
class NekoWebrtcPortsTests(unittest.TestCase):
|
||||||
|
def test_sanitize_strips_cr(self) -> None:
|
||||||
|
mod = _load()
|
||||||
|
self.assertEqual(mod.sanitize_env_text("9200\r"), "9200")
|
||||||
|
self.assertEqual(mod.sanitize_env_text("52000-52099\r\n"), "52000-52099")
|
||||||
|
|
||||||
|
def test_fit_udp_range_shrinks_before_crashcore(self) -> None:
|
||||||
|
mod = _load()
|
||||||
|
start, end = mod.fit_udp_range(52000, 52099, {52099})
|
||||||
|
self.assertEqual((start, end), (52000, 52098))
|
||||||
|
|
||||||
|
def test_fit_udp_range_shifts_when_prefix_too_small(self) -> None:
|
||||||
|
mod = _load()
|
||||||
|
blocked = set(range(52000, 52090))
|
||||||
|
start, end = mod.fit_udp_range(52000, 52099, blocked, min_ports=16)
|
||||||
|
self.assertGreaterEqual(end - start + 1, 16)
|
||||||
|
self.assertTrue(all(p not in blocked for p in range(start, end + 1)))
|
||||||
|
|
||||||
|
def test_upsert_env_file_normalizes_crlf_and_updates(self) -> None:
|
||||||
|
mod = _load()
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
path = Path(tmp) / "system-stack.env"
|
||||||
|
path.write_bytes(b"FOO=1\r\nNEKO_WEBRTC_UDP_RANGE=52000-52099\r\n")
|
||||||
|
mod.upsert_env_file(path, {"NEKO_WEBRTC_UDP_RANGE": "52000-52098", "NEKO_WEBRTC_EPR": "52000-52098"})
|
||||||
|
text = path.read_bytes()
|
||||||
|
self.assertNotIn(b"\r", text)
|
||||||
|
decoded = text.decode("utf-8")
|
||||||
|
self.assertIn("NEKO_WEBRTC_UDP_RANGE=52000-52098\n", decoded)
|
||||||
|
self.assertIn("NEKO_WEBRTC_EPR=52000-52098\n", decoded)
|
||||||
|
self.assertIn("FOO=1\n", decoded)
|
||||||
|
|
||||||
|
def test_autofix_updates_environ_when_52099_blocked(self) -> None:
|
||||||
|
mod = _load()
|
||||||
|
with patch.dict(
|
||||||
|
os.environ,
|
||||||
|
{
|
||||||
|
"NEKO_WEBRTC_UDP_RANGE": "52000-52099",
|
||||||
|
"NEKO_WEBRTC_UDP_RANGE_1": "52000-52099",
|
||||||
|
"NEKO_WEBRTC_EPR": "52000-52099",
|
||||||
|
"NEKO_WEBRTC_EPR_1": "52000-52099",
|
||||||
|
"NEKO_SKIP_UDP_PORT_PROBE": "1",
|
||||||
|
},
|
||||||
|
clear=False,
|
||||||
|
):
|
||||||
|
with patch.object(mod, "list_foreign_udp_holders", return_value={52099: "CrashCore"}):
|
||||||
|
changes = mod.apply_neko_udp_range_autofix(2, stack_env=None, persist=False)
|
||||||
|
self.assertEqual(os.environ["NEKO_WEBRTC_UDP_RANGE_1"], "52000-52098")
|
||||||
|
self.assertEqual(os.environ["NEKO_WEBRTC_EPR_1"], "52000-52098")
|
||||||
|
self.assertTrue(any(c["to"] == "52000-52098" for c in changes))
|
||||||
|
|
||||||
|
def test_renderer_strips_cr_from_ports(self) -> None:
|
||||||
|
path = ROOT / "tools" / "render_neko_compose.py"
|
||||||
|
spec = importlib.util.spec_from_file_location("render_neko_compose", path)
|
||||||
|
assert spec and spec.loader
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
with patch.dict(
|
||||||
|
os.environ,
|
||||||
|
{
|
||||||
|
"NEKO_IMAGE": "test-image",
|
||||||
|
"NEKO_PROFILE_HOST_DIR": f"{tmp}/profile",
|
||||||
|
"NEKO_HTTP_PORT": "9200\r",
|
||||||
|
"NEKO_HTTP_PORT_1": "9200\r",
|
||||||
|
"NEKO_WEBRTC_TCPMUX_1": "52300\r",
|
||||||
|
"NEKO_WEBRTC_UDPMUX_1": "52300\r",
|
||||||
|
"NEKO_WEBRTC_UDP_RANGE_1": "52000-52098\r",
|
||||||
|
"NEKO_WEBRTC_EPR_1": "52000-52098\r",
|
||||||
|
"NEKO_SKIP_UDP_PORT_PROBE": "1",
|
||||||
|
},
|
||||||
|
clear=False,
|
||||||
|
):
|
||||||
|
rendered = module.render(1)
|
||||||
|
self.assertIn('"9200:8080"', rendered)
|
||||||
|
self.assertNotIn("9200\\r", rendered)
|
||||||
|
self.assertIn('"52000-52098:52000-52098/udp"', rendered)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@ -14,12 +14,11 @@ if str(ROOT) not in sys.path:
|
|||||||
sys.path.insert(0, str(ROOT))
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
|
|
||||||
def _load_neko_docker_host_helpers():
|
def _load_standalone(module_name: str, relative: str):
|
||||||
# Keep this renderer usable from Linux service scripts with system Python.
|
# Keep this renderer usable from Linux service scripts with system Python.
|
||||||
# Importing src.neko_docker_host normally executes src/__init__.py, which
|
# Importing src.* normally executes src/__init__.py, which pulls app deps.
|
||||||
# pulls app dependencies that are not required for compose rendering.
|
module_path = ROOT / relative
|
||||||
module_path = ROOT / "src" / "neko_docker_host.py"
|
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
||||||
spec = importlib.util.spec_from_file_location("_neko_docker_host_standalone", module_path)
|
|
||||||
if spec is None or spec.loader is None:
|
if spec is None or spec.loader is None:
|
||||||
raise RuntimeError(f"Unable to load {module_path}")
|
raise RuntimeError(f"Unable to load {module_path}")
|
||||||
module = importlib.util.module_from_spec(spec)
|
module = importlib.util.module_from_spec(spec)
|
||||||
@ -27,23 +26,30 @@ def _load_neko_docker_host_helpers():
|
|||||||
return module
|
return module
|
||||||
|
|
||||||
|
|
||||||
_neko_docker_host = _load_neko_docker_host_helpers()
|
_neko_docker_host = _load_standalone("_neko_docker_host_standalone", "src/neko_docker_host.py")
|
||||||
|
_neko_webrtc_ports = _load_standalone("_neko_webrtc_ports_standalone", "src/neko_webrtc_ports.py")
|
||||||
build_neko_browser_proxy_url = _neko_docker_host.build_neko_browser_proxy_url
|
build_neko_browser_proxy_url = _neko_docker_host.build_neko_browser_proxy_url
|
||||||
neko_extra_hosts_mapping = _neko_docker_host.neko_extra_hosts_mapping
|
neko_extra_hosts_mapping = _neko_docker_host.neko_extra_hosts_mapping
|
||||||
sanitize_docker_host_ip = _neko_docker_host.sanitize_docker_host_ip
|
sanitize_docker_host_ip = _neko_docker_host.sanitize_docker_host_ip
|
||||||
sanitize_neko_browser_proxy = _neko_docker_host.sanitize_neko_browser_proxy
|
sanitize_neko_browser_proxy = _neko_docker_host.sanitize_neko_browser_proxy
|
||||||
|
apply_neko_udp_range_autofix = _neko_webrtc_ports.apply_neko_udp_range_autofix
|
||||||
|
default_udp_range = _neko_webrtc_ports.default_udp_range
|
||||||
|
sanitize_env_text = _neko_webrtc_ports.sanitize_env_text
|
||||||
|
|
||||||
|
|
||||||
def env(name: str, default: str) -> str:
|
def env(name: str, default: str) -> str:
|
||||||
value = os.environ.get(name)
|
value = os.environ.get(name)
|
||||||
return value if value not in {None, ""} else default
|
if value in {None, ""}:
|
||||||
|
return default
|
||||||
|
# Windows/SFTP edits often inject CR; compose then fails with invalid hostPort.
|
||||||
|
return sanitize_env_text(value) or default
|
||||||
|
|
||||||
|
|
||||||
def env_enabled(name: str, default: bool = False) -> bool:
|
def env_enabled(name: str, default: bool = False) -> bool:
|
||||||
raw = os.environ.get(name)
|
raw = os.environ.get(name)
|
||||||
if raw in {None, ""}:
|
if raw in {None, ""}:
|
||||||
return default
|
return default
|
||||||
return raw.strip().lower() in {"1", "true", "yes", "on", "enable", "enabled"}
|
return sanitize_env_text(raw).lower() in {"1", "true", "yes", "on", "enable", "enabled"}
|
||||||
|
|
||||||
|
|
||||||
def q(value: str) -> str:
|
def q(value: str) -> str:
|
||||||
@ -55,23 +61,12 @@ def instance_value(prefix: str, idx: int, default: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def host_path(base: str, name: str) -> str:
|
def host_path(base: str, name: str) -> str:
|
||||||
base = base.strip()
|
base = sanitize_env_text(base)
|
||||||
if base in {"", ".", "./"}:
|
if base in {"", ".", "./"}:
|
||||||
return f"./{name}"
|
return f"./{name}"
|
||||||
return f"{base.rstrip('/')}/{name}"
|
return f"{base.rstrip('/')}/{name}"
|
||||||
|
|
||||||
|
|
||||||
def default_udp_range(idx: int) -> str:
|
|
||||||
if idx == 1:
|
|
||||||
return "52000-52099"
|
|
||||||
if idx == 2:
|
|
||||||
return "52101-52199"
|
|
||||||
if idx == 3:
|
|
||||||
return "52201-52299"
|
|
||||||
start = 52400 + ((idx - 4) * 100)
|
|
||||||
return f"{start}-{start + 99}"
|
|
||||||
|
|
||||||
|
|
||||||
def render(count: int) -> str:
|
def render(count: int) -> str:
|
||||||
image = env("NEKO_IMAGE", "ghcr.io/m1k1o/neko/chromium:3.0.0")
|
image = env("NEKO_IMAGE", "ghcr.io/m1k1o/neko/chromium:3.0.0")
|
||||||
shm = env("NEKO_SHM_SIZE", "512mb")
|
shm = env("NEKO_SHM_SIZE", "512mb")
|
||||||
@ -227,11 +222,35 @@ def main() -> int:
|
|||||||
parser = argparse.ArgumentParser(description="Render Neko docker compose")
|
parser = argparse.ArgumentParser(description="Render Neko docker compose")
|
||||||
parser.add_argument("--count", type=int, required=True)
|
parser.add_argument("--count", type=int, required=True)
|
||||||
parser.add_argument("--output", required=True)
|
parser.add_argument("--output", required=True)
|
||||||
|
parser.add_argument(
|
||||||
|
"--stack-env",
|
||||||
|
default="",
|
||||||
|
help="Optional system-stack.env path; UDP range autofix + CRLF normalize persist here",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--no-udp-autofix",
|
||||||
|
action="store_true",
|
||||||
|
help="Skip probing foreign UDP holders (CrashCore) before rendering",
|
||||||
|
)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
count = max(1, min(64, args.count))
|
count = max(1, min(64, args.count))
|
||||||
|
stack_env = Path(args.stack_env) if args.stack_env else None
|
||||||
|
if stack_env and stack_env.exists():
|
||||||
|
# Normalize CRLF on the whole file before compose uses sourced values again.
|
||||||
|
text = stack_env.read_text(encoding="utf-8", errors="replace")
|
||||||
|
if "\r" in text:
|
||||||
|
stack_env.write_text(text.replace("\r\n", "\n").replace("\r", "\n"), encoding="utf-8", newline="\n")
|
||||||
|
if not args.no_udp_autofix:
|
||||||
|
changes = apply_neko_udp_range_autofix(count, stack_env=stack_env, persist=True)
|
||||||
|
for change in changes:
|
||||||
|
print(
|
||||||
|
f"[neko-udp-autofix] instance={change['instance']} "
|
||||||
|
f"{change['from']} -> {change['to']} holders={change.get('holders') or '-'}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
output = Path(args.output)
|
output = Path(args.output)
|
||||||
output.parent.mkdir(parents=True, exist_ok=True)
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
output.write_text(render(count), encoding="utf-8")
|
output.write_text(render(count), encoding="utf-8", newline="\n")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user