DEPLOY-SOCKS-KEEP-PLAN-B.txt — 龍捌 (watcher-a567) socks-keep-ensure 長治方案 B 部署與驗收手冊 ================================================================================================== 應主持 61193 及 http://149.118.48.126:8080/socks-keep-plan-b/socks-keep-ensure-plan-b.txt(sha256 f2fb716a…)制定。 一、關鍵路徑與排程新叫法一覽 1. Wrapper 檔案路徑: - 新手包內路徑:/socks-ensure-detached.sh(mode 0755) - 部署機持久區標準路徑:$HOME/workspace/socks-ensure-detached.sh(mode 0755) 2. Muse Runtime 排程新設定(嚴禁 crontab / @reboot / systemd / 自寫 nohup loop): - 排程名稱(title):socks-keep-ensure - 觸發頻率:每 5 分鐘一次(時區:Asia/Hong_Kong) - Timeout:300 秒(實測單輪 < 0.2s–1.0s 內 exit 0) - 新執行命令(取代舊 `~/workspace/socks-ensure.sh`): bash $HOME/workspace/socks-ensure-detached.sh 3. 日誌路徑: - Wrapper 審計日誌:/tmp/socks-ensure-detached.log(含每次執行前後凍結腳本 SHA256 與 PID/SID 紀錄) - 兩條隧道 loop 日誌:/tmp/socks-keep.log、/tmp/socks90-keep.log 二、三支凍結腳本(嚴禁任何改動) - $HOME/workspace/socks-ensure.sh (凍結保留,排程唔再直接叫佢) - $HOME/workspace/socks-keep.sh (11080–11086 WG 隧道,ssh -L) - $HOME/workspace/socks90-keep.sh (11090 SERVER_DIRECT,必須 ssh -D 動態轉發,嚴禁 -L) - 現行方案 A 人手 setsid 嗰對 loop(如 PID 1993 / PID 2393)保留作 fallback,唔拆唔殺; wrapper 上線見到在生即輸出 ALIVE 並 exit 0,絕不重起或殺死。 三、操作員逐步部署與驗收 1–3 命令(一步唔跳) 步驟 1|部署前先鎖定三支凍結腳本 SHA256 基線: sha256sum ~/workspace/socks-ensure.sh ~/workspace/socks-keep.sh ~/workspace/socks90-keep.sh \ | tee /tmp/frozen-socks-scripts.before.sha256 步驟 2|安裝 wrapper 至 ~/workspace/socks-ensure-detached.sh(唔掂三支原檔): install -m 0755 /socks-ensure-detached.sh ~/workspace/socks-ensure-detached.sh 步驟 3|更新本機 Muse runtime 排程 `socks-keep-ensure`: - 將原本呼叫 `~/workspace/socks-ensure.sh` 改為: bash ~/workspace/socks-ensure-detached.sh - 確認頻率=每 5 分鐘、時區=Asia/Hong_Kong、只保留唯一一個 `socks-keep-ensure` job。 步驟 4|執行今輪三項必做驗收(第 4 項 reboot 驗收等 owner 安排平台側 reboot): [驗收 ①] 連續兩輪排程 run(即場觸發 + 等下一個 5 分鐘自然周期): - 核實兩輪均於數秒內 exit 0,`run_history` 唔再現 `T`(timeout); - 核實既有在生 loop PID 未被殺、未重複起。 [驗收 ②] 手動 kill 單一 keep loop 恢復與 SID==PID 驗證: - 記錄當前 PID:`ps -eo pid,sid,pgid,comm,args | grep -E 'socks(90)?-keep\.sh'` - 手動終止其中一條(例如 `kill `),保留另一條不動; - 觸發一輪排程 run(或等下一個 5 分鐘周期),核實: ps -eo pid,sid,pgid,comm,args | grep -E 'socks(90)?-keep\.sh' (a) 被 kill 嗰條已自動拉返,且 `SID == PID`(獨立 session); (b) 未被 kill 嗰條維持原 PID 不變; (c) 再過一輪排程後,新拉起嗰條 PID 依然存活(唔再每 5 分鐘被殺)。 [驗收 ③] 恒常單實例與凍結雜湊核對: - `pgrep -af 'socks-keep\.sh'` → 恒常 1 條 - `pgrep -af 'socks90-keep\.sh'` → 恒常 1 條 - `sha256sum -c /tmp/frozen-socks-scripts.before.sha256` → 3/3 OK(零改動) 四、Wrapper 完整源碼(符合「有程序名就要有程序」鐵律,與包內 socks-ensure-detached.sh 一致) -------------------------------------------------------------------------------------------------- #!/bin/bash # socks-ensure-detached.sh — Long-term Plan B scheduler-layer detached wrapper (r13 / v19.5 host-61220 final) # Addresses host rulings 61212 & 61220 + A87 61213/61219 (dKWkD) + A65 61200/61208/61215: # 1. Launches missing loops inside own session (`setsid -f`) with stdin=/dev/null, log redirection, # and full close of inherited FDs > 2. # 2. Post-spawn survival window (`SOCKS_START_SETTLE_SEC`, default `0.60s` >= `0.50s`): # declares `SPAWN_OK [START-OK]` ONLY if at window end the **exact same single PID** is still alive # (non-zombie `Z/X`, `kill -0`) AND `SID == PID` (`PGID == PID`); otherwise logs `ERROR [START-FAIL]` # to stderr (and `SOCKS_ENSURE_DETACHED_LOG` if set) and returns `rc=1`. # 3. Fast O(candidates) discovery (`pgrep -f` C pre-filter + exact `/proc//{stat,cmdline,cwd}` check) # + tight 5x0.03s (`0.15s`) exec-appearance budget: # - immediate `exit 7` failure path completes in `~0.35s` (`<< 2.0s` even on servers with thousands of processes!); # - delayed `sleep 0.30; exit 1` failure path completes in `~0.68s` (`<< 2.0s`); # - cold start of both healthy loops completes in `~0.68s` (`<< 3.0s`); warm check in `~0.03s`. # 4. Per host ruling 61220 §4: pre-existing duplicate loops (`count > 1`) log `[WARN-DUPLICATE-LOOPS]` # with all PIDs without spawning duplicates or killing processes and return `0` by default # (set `SOCKS_STRICT_DUPLICATE_RC3=1` for `rc=3` alert mode). set -euo pipefail if [ -n "${SOCKS_SCRIPTS_DIR:-}" ]; then WS_DIR="$SOCKS_SCRIPTS_DIR" elif [ -n "${SOCKS_WORKSPACE_DIR:-}" ]; then WS_DIR="$SOCKS_WORKSPACE_DIR" else WS_DIR="$HOME/workspace" fi WS_REAL="$(readlink -f "$WS_DIR" 2>/dev/null || printf '%s' "$WS_DIR")" LOCK_FILE="${SOCKS_ENSURE_LOCK:-${SOCKS_ENSURE_LOCK_FILE:-/tmp/socks-ensure-detached.$(id -u).lock}}" DETACHED_LOG="${SOCKS_ENSURE_DETACHED_LOG:-}" SOCKS_KEEP="${SOCKS_KEEP_SCRIPT:-$WS_REAL/socks-keep.sh}" SOCKS90_KEEP="${SOCKS90_KEEP_SCRIPT:-$WS_REAL/socks90-keep.sh}" SOCKS_KEEP_LOG="${SOCKS_KEEP_LOG:-/tmp/socks-keep.log}" SOCKS90_KEEP_LOG="${SOCKS90_KEEP_LOG:-/tmp/socks90-keep.log}" SETTLE_SEC="${SOCKS_START_SETTLE_SEC:-0.60}" ts_hkt() { TZ="Asia/Hong_Kong" date "+%Y-%m-%d %H:%M:%S HKT" } log_info() { local msg="$*" printf '%s\n' "$msg" if [ -n "$DETACHED_LOG" ]; then mkdir -p "$(dirname "$DETACHED_LOG")" 2>/dev/null || true printf '%s\n' "$msg" >>"$DETACHED_LOG" 2>/dev/null || true fi } log_error() { local msg="$*" printf '%s\n' "$msg" >&2 if [ -n "$DETACHED_LOG" ]; then mkdir -p "$(dirname "$DETACHED_LOG")" 2>/dev/null || true printf '%s\n' "$msg" >>"$DETACHED_LOG" 2>/dev/null || true fi } # Fail closed if LOCK_FILE cannot be opened/created; exit 0 ONLY on active concurrent flock contention. if ! { exec 9>"$LOCK_FILE"; } 2>/dev/null; then log_error "$(ts_hkt) ERROR [LOCK-ERROR] cannot open lock file: $LOCK_FILE" exit 1 fi if ! flock -n 9; then log_info "$(ts_hkt) [SKIP-LOCK] another socks-ensure-detached.sh instance holds $LOCK_FILE; exiting 0" exit 0 fi # Print " " for a live non-zombie PID, or return 1 if dead/zombie. read_proc_ids() { local pid="$1" stat_raw="" rest="" st="" ppid="" pgid="" sid="" [ -r "/proc/$pid/stat" ] || return 1 IFS= read -r stat_raw < "/proc/$pid/stat" 2>/dev/null || return 1 [ -n "$stat_raw" ] || return 1 rest="${stat_raw##*) }" set -- $rest st="${1:-}"; ppid="${2:-}"; pgid="${3:-}"; sid="${4:-}" case "$st" in ""|Z*|X*) return 1 ;; esac kill -0 "$pid" 2>/dev/null || return 1 printf '%s %s %s %s\n' "$st" "$ppid" "$pgid" "$sid" } # Fast O(matching candidates) PID discovery: # Uses native C `pgrep -f "$target_base"` when available to avoid O(N_all_procs) bash globbing on large servers, # then verifies EVERY candidate against `/proc//{stat,cmdline,cwd}` (zero COLUMNS truncation, zero zombie hits, # zero cross-directory contamination). find_live_loop_pids() { local target_script="$1" local target_real target_base pid proc_dir stat_raw rest st tok match_ok is_dash_c cwd_real raw_pids target_real="$(readlink -f "$target_script" 2>/dev/null || printf '%s' "$target_script")" target_base="${target_real##*/}" if command -v pgrep >/dev/null 2>&1; then raw_pids="$(pgrep -f "$target_base" 2>/dev/null || true)" else raw_pids="" for proc_dir in /proc/[0-9]*; do raw_pids="$raw_pids ${proc_dir#/proc/}" done fi for pid in $raw_pids; do if [ "$pid" = "$$" ] || [ "$pid" = "${PPID:-0}" ]; then continue fi proc_dir="/proc/$pid" [ -r "$proc_dir/stat" ] && [ -r "$proc_dir/cmdline" ] || continue stat_raw="" IFS= read -r stat_raw < "$proc_dir/stat" 2>/dev/null || continue [ -n "$stat_raw" ] || continue rest="${stat_raw##*) }" st="${rest%% *}" case "$st" in ""|Z*|X*) continue ;; esac kill -0 "$pid" 2>/dev/null || continue match_ok=0 is_dash_c=0 while IFS= read -r -d '' tok; do if [ "$tok" = "-c" ]; then is_dash_c=1 break fi if [ "$tok" = "$target_real" ] || [ "$tok" = "$target_script" ]; then match_ok=1 elif [ "$tok" = "$target_base" ] || [ "$tok" = "./$target_base" ]; then cwd_real="$(readlink -f "$proc_dir/cwd" 2>/dev/null || printf '')" if [ "$cwd_real" = "$WS_REAL" ]; then match_ok=1 fi fi done < "$proc_dir/cmdline" 2>/dev/null || true if [ "$is_dash_c" -eq 0 ] && [ "$match_ok" -eq 1 ]; then printf '%s\n' "$pid" fi done } readonly_check_socks90() { local s90="$1" if grep -Eq '^[[:space:]]*[^#]*ssh[[:space:]].*-L[[:space:]]*([0-9.]+:)?11090:' "$s90"; then log_error "$(ts_hkt) ERROR [FATAL-60564] $s90 contains forbidden '-L ... 11090:' static tunnel; refusing to start without modifying file" return 2 fi if [ "${SOCKS_REQUIRE_SSH_D:-0}" = "1" ] && ! grep -Eq '^[[:space:]]*[^#]*ssh[[:space:]].*-D[[:space:]]*([0-9.]+:)?11090([[:space:]]|$)' "$s90"; then log_error "$(ts_hkt) ERROR [FATAL-11090-NO-SSH-D] $s90 lacks affirmative executable 'ssh ... -D ... 11090'" return 2 fi return 0 } REPLY_CAND_PID="" REPLY_SPAWNED=0 prepare_or_launch_loop() { local label="$1" local script_path="$2" local log_path="$3" REPLY_CAND_PID="" REPLY_SPAWNED=0 if [ ! -f "$script_path" ]; then log_error "$(ts_hkt) ERROR [MISSING] $label script not found at $script_path" return 1 fi local live_pids live_count flat_pids live_pids="$(find_live_loop_pids "$script_path")" if [ -n "$live_pids" ]; then live_count="$(printf '%s\n' "$live_pids" | sed '/^$/d' | wc -l | tr -d ' ')" flat_pids="$(printf '%s' "$live_pids" | tr '\n' ' ' | sed 's/ $//')" if [ "$live_count" -gt 1 ]; then if [ "${SOCKS_STRICT_DUPLICATE_RC3:-0}" = "1" ]; then log_error "$(ts_hkt) ERROR [DUPLICATE-LOOPS] $label has $live_count live processes (pids: $flat_pids); strict mode returning rc=3" return 3 fi log_info "$(ts_hkt) [WARN-DUPLICATE-LOOPS] $label already has $live_count live processes (pids: $flat_pids); not spawning new duplicate (host ruling 61220 §4)" return 0 fi log_info "$(ts_hkt) [OK-ALIVE] $label already running (count=1 pid: $flat_pids)" return 0 fi if [ "$label" = "socks90-keep" ]; then readonly_check_socks90 "$script_path" || return $? fi mkdir -p "$(dirname "$log_path")" setsid -f /bin/bash -c ' for _fd in /proc/self/fd/*; do _fd="${_fd##*/}" case "$_fd" in 0|1|2) ;; *) eval "exec ${_fd}>&-" 2>/dev/null || true ;; esac done if [ -x "$1" ]; then exec "$1" else exec /bin/bash "$1" fi ' _ "$script_path" >"$log_path" 2>&1 # Tight 5 x 0.03s (0.15s max) exec-appearance budget so immediate-exit failures (`exit 7`) complete in ~0.35s << 2.0s! local attempt=0 new_pids="" cnt=0 while [ "$attempt" -lt 5 ]; do new_pids="$(find_live_loop_pids "$script_path")" if [ -n "$new_pids" ]; then cnt="$(printf '%s\n' "$new_pids" | sed '/^$/d' | wc -l | tr -d ' ')" if [ "$cnt" -eq 1 ]; then REPLY_CAND_PID="$(printf '%s' "$new_pids" | tr -d ' \n')" REPLY_SPAWNED=1 return 0 fi log_error "$(ts_hkt) ERROR [START-FAIL] $label unexpected candidate PID count=$cnt ($new_pids)" return 1 fi sleep 0.03 attempt=$((attempt + 1)) done log_error "$(ts_hkt) ERROR [START-FAIL] $label failed to start or exited immediately; check $log_path" return 1 } verify_post_window_survival() { local label="$1" local script_path="$2" local cand_pid="$3" local log_path="$4" local post_pids proc_info st ppid pgid sid post_pids="$(find_live_loop_pids "$script_path" | tr -d ' \n' || true)" if [ "$post_pids" != "$cand_pid" ]; then log_error "$(ts_hkt) ERROR [START-FAIL] $label candidate pid=$cand_pid did not survive ${SETTLE_SEC}s window (post_pids='${post_pids:-none}'); check $log_path" return 1 fi if ! proc_info="$(read_proc_ids "$cand_pid")"; then log_error "$(ts_hkt) ERROR [START-FAIL] $label candidate pid=$cand_pid became dead/zombie at end of ${SETTLE_SEC}s window; check $log_path" return 1 fi set -- $proc_info st="$1"; ppid="$2"; pgid="$3"; sid="$4" if [ "$sid" != "$cand_pid" ] || [ "$pgid" != "$cand_pid" ]; then log_error "$(ts_hkt) ERROR [START-FAIL] $label pid=$cand_pid failed session isolation check (sid=$sid pgid=$pgid != pid=$cand_pid)" return 1 fi log_info "$(ts_hkt) SPAWN_OK [START-OK] $label detached and survived ${SETTLE_SEC}s window (pid=$cand_pid sid=$sid pgid=$pgid ppid=$ppid)" return 0 } rc=0 SPAWNED_1=0; CAND_1="" SPAWNED_2=0; CAND_2="" if prepare_or_launch_loop "socks-keep" "$SOCKS_KEEP" "$SOCKS_KEEP_LOG"; then SPAWNED_1="$REPLY_SPAWNED"; CAND_1="$REPLY_CAND_PID" else rc=$? fi if prepare_or_launch_loop "socks90-keep" "$SOCKS90_KEEP" "$SOCKS90_KEEP_LOG"; then SPAWNED_2="$REPLY_SPAWNED"; CAND_2="$REPLY_CAND_PID" else _rc2=$? [ "$rc" -eq 0 ] && rc="$_rc2" fi if [ "$SPAWNED_1" -eq 1 ] || [ "$SPAWNED_2" -eq 1 ]; then sleep "$SETTLE_SEC" if [ "$SPAWNED_1" -eq 1 ]; then verify_post_window_survival "socks-keep" "$SOCKS_KEEP" "$CAND_1" "$SOCKS_KEEP_LOG" || { [ "$rc" -eq 0 ] && rc=1; } fi if [ "$SPAWNED_2" -eq 1 ]; then verify_post_window_survival "socks90-keep" "$SOCKS90_KEEP" "$CAND_2" "$SOCKS90_KEEP_LOG" || { [ "$rc" -eq 0 ] && rc=1; } fi fi exec 9>&- exit "$rc"