Files
zapret-autotune/managed-target-supervision.sh
T

98 lines
3.2 KiB
Bash

#!/bin/sh
# Shared owned-tree signalling; sourced by PID 1, executed afresh for watchdogs.
signal_tree() {
if [ -r "/proc/$1/task/$1/children" ]; then
descendants=
read -r descendants < "/proc/$1/task/$1/children" || true
for descendant in $descendants; do
signal_tree "$descendant" "$2"
done
fi
kill "-$2" "$1" 2>/dev/null || true
}
# /proc comm may contain spaces and closing parentheses: remove through the
# LAST ') ', then fields are state, PPID, PGID, SID (not whitespace-split comm).
proc_identity() {
proc_sid=
proc_state=
proc_line=
[ -r "/proc/$1/stat" ] || return 1
read -r proc_line < "/proc/$1/stat" || return 1
[ "${proc_line%% *}" = "$1" ] || return 1
proc_tail=${proc_line##*) }
[ "$proc_tail" != "$proc_line" ] || return 1
set -- $proc_tail
[ "$#" -ge 4 ] || return 1
proc_state=$1
proc_sid=$4
}
signal_session() {
case "$1" in ''|*[!0-9]*) return 1 ;; esac
[ "$1" -gt 1 ] && [ "$1" != "$$" ] || return 1
proc_identity "$$" || return 1
[ "$proc_sid" != "$1" ] || return 1
session_live=0
for session_stat in /proc/[0-9]*/stat; do
session_pid=${session_stat#/proc/}
session_pid=${session_pid%/stat}
if ! proc_identity "$session_pid"; then
# Disappearing processes are normal; an unreadable surviving stat
# is not evidence that the owned session is empty.
[ ! -e "$session_stat" ] || return 1
continue
fi
[ "$proc_sid" = "$1" ] || continue
[ "$session_pid" -gt 1 ] && [ "$session_pid" != "$$" ] || return 1
if [ "$proc_state" = Z ]; then
# PID 1 may have adopted this worker. Nonchildren return immediately;
# zombies never block. Shell SIGCHLD handling also reaps adoptees.
wait "$session_pid" 2>/dev/null || true
continue
fi
session_live=1
[ "$2" = CHECK ] || kill "-$2" "$session_pid" 2>/dev/null || true
done
}
if [ "${1-}" = --monitor ]; then
set -eu
[ "$#" -ge 3 ] || exit 64
config_dir=$2
shift 2
proc_identity "$$" && [ "$proc_sid" = "$$" ] && [ "$$" -gt 1 ] || exit 78
# Acknowledge the private session before exec, so even an immediate monitor
# crash leaves its ownership recorded. No worker can precede this handshake.
trap 'exit 143' INT TERM
printf '%s\n' "$$" > "$config_dir/monitor-ready"
exec "$@"
elif [ "${1-}" = --watchdog ]; then
set -eu
[ "$#" -eq 4 ] || exit 64
case "$2" in ''|*[!0-9]*) exit 64 ;; esac
case "$3" in ''|*[!0-9]*) exit 64 ;; esac
[ "$2" -gt 1 ] && [ "$3" -gt 0 ] || exit 64
child=$2
seconds=$3
config_dir=$4
sleeper=
watchdog_cleanup() {
trap - EXIT
trap ':' INT TERM
if [ -n "$sleeper" ]; then
kill "$sleeper" 2>/dev/null || true
wait "$sleeper" 2>/dev/null || true
fi
}
trap watchdog_cleanup EXIT
trap 'exit 0' INT TERM
sleep "$seconds" & sleeper=$!
: > "$config_dir/join-ready"
wait "$sleeper"
: > "$config_dir/join-timeout"
signal_tree "$child" KILL
elif [ "$#" -ne 0 ]; then
exit 64
fi