Harden local debug stale listener cleanup
This commit is contained in:
@@ -23,6 +23,24 @@ port_listener_pid() {
|
||||
lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | head -n 1 || true
|
||||
}
|
||||
|
||||
listener_owned_by_local_debug() {
|
||||
local pid="$1"
|
||||
local details
|
||||
details="$(lsof -nP -p "$pid" 2>/dev/null || true)"
|
||||
[[ "$details" == *"$ROOT_DIR"* || "$details" == *"$LOCAL_DEBUG_ROOT"* ]]
|
||||
}
|
||||
|
||||
wait_for_pid_exit() {
|
||||
local pid="$1"
|
||||
for _ in $(seq 1 20); do
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
sleep 0.25
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
ensure_port_available() {
|
||||
local name="$1"
|
||||
local port="$2"
|
||||
@@ -35,6 +53,17 @@ ensure_port_available() {
|
||||
if managed_pid_running "$pid_file" && [[ "$listener_pid" == "$(cat "$pid_file")" ]]; then
|
||||
return 0
|
||||
fi
|
||||
if listener_owned_by_local_debug "$listener_pid"; then
|
||||
printf 'stopping stale %s listener pid %s on port %s\n' "$name" "$listener_pid" "$port"
|
||||
kill "$listener_pid" 2>/dev/null || true
|
||||
if ! wait_for_pid_exit "$listener_pid"; then
|
||||
printf 'stale %s listener pid %s did not stop after SIGTERM; sending SIGKILL\n' "$name" "$listener_pid"
|
||||
kill -9 "$listener_pid" 2>/dev/null || true
|
||||
wait_for_pid_exit "$listener_pid" || true
|
||||
fi
|
||||
rm -f "$pid_file"
|
||||
return 0
|
||||
fi
|
||||
printf '%s port %s is already used by pid %s; choose another LOCAL_DEBUG_*_PORT or stop the existing listener\n' "$name" "$port" "$listener_pid" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user