Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Retain rc.d and SysV recovery until removal is observed
pulse-triage[bot]bad484550830
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 131f24bb44..933ebc6fb6 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -15,6 +15,38 @@## Purpose+### FreeBSD rc.d and SysV removal retains recovery on unknown or live state++Before server deregistration or local erasure, Unix uninstall selects its+FreeBSD rc.d or SysV manager and requires observed quiescence. Bounded combined+reads reject failed, incomplete, empty, duplicate or diagnostic-bearing state.+The kernel process inventory checks both collector and daemon supervisor, while+PID files must be regular numeric records that cannot identify another process.+Process arguments are never returned from the reader. Rendered rc.d/SysV stops+retain PID files after refused signals or when termination remains unconfirmed.++FreeBSD requires effective `pulse_agent_enable=NO` readback plus matching stopped+status and supervisor/child absence. SysV removes every owned activation link+across both rc*.d layouts, including custom runlevels and priorities, with checked+manager commands or exact owned-link removal. Foreign, malformed or inaccessible+paths refuse, rather than deleting another service. Both paths recheck after+remote confirmation and before script, PID or credential erasure. Remote refusal+keeps the stopped installation's recovery material; no automatic restart occurs.+Missing/repeated removal still requires known disabled activation and process+absence. Existing systemd/OpenRC gates and credential/transport ownership remain.++TrueNAS bootstrap re-enables rc.conf and recreates the service link independently.+A linked rc.d service or existing appliance bootstrap therefore refuses *before*+remote removal or erasure until its owning activation task can be reconciled;+this step does not claim appliance task, launchd, Windows or native acceptance.+Missing timeout/sysrc or unrecognised manager output also remains a safe refusal.+`TestInstallSHLegacyTeardownRequiresObservedQuiescence` requires all sixteen+production-function/caller/rendered-stop methods in `agent_legacy_teardown.py`,+using closed ordinary-user models and private deletion/signal targets, plus a+real timeout-child termination control. Source models are not installed signed+agent, real TLS, native manager, published availability or whole #1099 resolution.++### OpenRC removal confirms stopped and unlinked state before erasureOpenRC removal must observe a complete, diagnostic-free runlevel inventory anddiff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.mdindex 2ac6f51014..11638d6979 100644--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md@@ -16,6 +16,38 @@## Purpose+### FreeBSD rc.d and SysV removal retains recovery on unknown or live state++Before server deregistration or local erasure, Unix uninstall selects its+FreeBSD rc.d or SysV manager and requires observed quiescence. Bounded combined+reads reject failed, incomplete, empty, duplicate or diagnostic-bearing state.+The kernel process inventory checks both collector and daemon supervisor, while+PID files must be regular numeric records that cannot identify another process.+Process arguments are never returned from the reader. Rendered rc.d/SysV stops+retain PID files after refused signals or when termination remains unconfirmed.++FreeBSD requires effective `pulse_agent_enable=NO` readback plus matching stopped+status and supervisor/child absence. SysV removes every owned activation link+across both rc*.d layouts, including custom runlevels and priorities, with checked+manager commands or exact owned-link removal. Foreign, malformed or inaccessible+paths refuse, rather than deleting another service. Both paths recheck after+remote confirmation and before script, PID or credential erasure. Remote refusal+keeps the stopped installation's recovery material; no automatic restart occurs.+Missing/repeated removal still requires known disabled activation and process+absence. Existing systemd/OpenRC gates and credential/transport ownership remain.++TrueNAS bootstrap re-enables rc.conf and recreates the service link independently.+A linked rc.d service or existing appliance bootstrap therefore refuses *before*+remote removal or erasure until its owning activation task can be reconciled;+this step does not claim appliance task, launchd, Windows or native acceptance.+Missing timeout/sysrc or unrecognised manager output also remains a safe refusal.+`TestInstallSHLegacyTeardownRequiresObservedQuiescence` requires all sixteen+production-function/caller/rendered-stop methods in `agent_legacy_teardown.py`,+using closed ordinary-user models and private deletion/signal targets, plus a+real timeout-child termination control. Source models are not installed signed+agent, real TLS, native manager, published availability or whole #1099 resolution.++### OpenRC removal retains recovery on an unconfirmed manager resultThe OpenRC agent-removal path must finish stop and all-runlevel disable withdiff --git a/scripts/install.sh b/scripts/install.shindex 4bd96fec8e..fcaec08609 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -1338,46 +1338,212 @@ teardown_openrc_agent_service() {rm -f "$init_path"}-teardown_freebsd_agent_service() {- local service_path="${1:-/usr/local/etc/rc.d/${AGENT_NAME}}"+# Read one complete kernel process inventory. Return only PID/parent/role,+# never command arguments (which can contain credentials). Both the agent and+# daemon(8) supervising it must disappear; a stopped-looking rc.d status alone+# cannot establish that after an ignored signal or lost PID file.+read_legacy_agent_removal_processes() {+ local observation="" line="" pid="" parent="" comm="" args="" role=""+ local complete="false" count=0 parents=" " seen=" "+ local -a rows=()+ observation=$(LC_ALL=C timeout -k 1 5 ps -ax -o pid= -o ppid= -o comm= -o args= 2>&1 &&+ printf '%s' '__pulse_processes_complete__') || return 1+ while IFS= read -r line; do+ [[ "$complete" == false ]] || return 1+ if [[ "$line" == __pulse_processes_complete__ ]]; then+ complete="true"+ continue+ fi+ [[ "$line" =~ ^[[:space:]]*([1-9][0-9]*)[[:space:]]+([0-9]+)[[:space:]]+([^[:space:]]+)[[:space:]]+(.+)$ ]] || return 1+ pid="${BASH_REMATCH[1]}" parent="${BASH_REMATCH[2]}" comm="${BASH_REMATCH[3]}" args="${BASH_REMATCH[4]}"+ [[ "$seen" != *" $pid "* ]] || return 1+ seen+="$pid "+ role="other"+ if [[ "${comm##*/}" == "$BINARY_NAME" ]]; then+ role="agent"+ parents+="$parent "+ elif [[ "${comm##*/}" == daemon && "$args" =~ (^|[[:space:]/])pulse-agent([[:space:]\[]|$) ]]; then+ role="supervisor"+ fi+ rows+=("$pid $parent $role ${comm##*/}")+ count=$((count + 1))+ [[ $count -le 65536 ]] || return 1+ done <<< "$observation"+ [[ "$complete" == true && $count -gt 0 ]] || return 1+ for line in "${rows[@]}"; do+ read -r pid parent role comm <<< "$line"+ if [[ "$comm" == daemon && "$parents" == *" $pid "* ]]; then role="supervisor"; fi+ printf '%s %s %s\n' "$pid" "$parent" "$role"+ done+}- # Stop the rc.d supervisor before removing the executable. Killing only the- # child is insufficient because daemon(8) immediately restarts it.- if [[ -x "$service_path" ]]; then- "$service_path" stop 2>/dev/null || true- elif command -v service >/dev/null 2>&1; then- service "${AGENT_NAME}" stop 2>/dev/null || true- fi+legacy_agent_processes_absent() {+ [[ "$1" != *' agent'* && "$1" != *' supervisor'* ]]+}- if command -v sysrc >/dev/null 2>&1; then- sysrc -x pulse_agent_enable >/dev/null 2>&1 || true- else- for rc_config in /etc/rc.conf /etc/rc.conf.local; do- if [[ -f "$rc_config" ]]; then- sed -i '' '/^[[:space:]]*pulse_agent_enable[[:space:]]*=/d' "$rc_config" 2>/dev/null || \- sed -i '/^[[:space:]]*pulse_agent_enable[[:space:]]*=/d' "$rc_config" 2>/dev/null || true+validate_legacy_agent_removal_pidfiles() {+ local inventory="$1" path="" pid="" row="" observed="" parent="" role=""+ shift+ for path in "$@"; do+ [[ -e "$path" || -L "$path" ]] || continue+ [[ -f "$path" && ! -L "$path" && -r "$path" ]] || return 1+ # Preserve trailing diagnostics/extra lines; do not evaluate a PID file.+ pid=$(cat "$path" && printf '%s' '__pulse_pid_complete__') || return 1+ [[ "$pid" =~ ^([1-9][0-9]*)($'\n')?__pulse_pid_complete__$ ]] || return 1+ pid="${BASH_REMATCH[1]}"+ while read -r observed parent role; do+ if [[ "$observed" == "$pid" ]]; then+ [[ "$role" == agent || "$role" == supervisor ]] || return 1fi- done+ done <<< "$inventory"+ done+}++read_legacy_agent_removal_status() {+ local path="$1" platform="$2" verb=status observation="" line="" state="" code="" count=0+ [[ "$platform" != FreeBSD ]] || verb=onestatus+ observation=$(LC_ALL=C timeout -k 1 5 "$path" "$verb" 2>&1 &&+ printf '%s' '__pulse_status_exit__=0' || printf '%s' "__pulse_status_exit__=$?") || return 1+ while IFS= read -r line; do+ case "$line" in+ __pulse_status_exit__=*)+ [[ "$count" == 1 && -z "$code" ]] || return 1+ code="${line#__pulse_status_exit__=}" ;;+ *)+ [[ "$count" == 0 && -z "$code" ]] || return 1+ if [[ "$platform" == FreeBSD ]]; then+ if [[ "$line" == 'pulse_agent is not running.' ]]; then state=stopped+ elif [[ "$line" =~ ^pulse_agent\ is\ running\ as\ (supervisor|child)\ pid\ [1-9][0-9]*(\ with\ child\ pid\ [1-9][0-9]*)?\.$ ||+ "$line" =~ ^pulse_agent\ is\ running\ as\ legacy\ child\ pid\ [1-9][0-9]*\ supervised\ by\ pid\ [1-9][0-9]*\.$ ]]; then state=started+ else return 1; fi+ else+ if [[ "$line" == "$AGENT_NAME is not running." || "$line" == "$AGENT_NAME is not running (stale PID file)." ]]; then state=stopped+ elif [[ "$line" =~ ^pulse-agent\ is\ running\ \(PID\ [1-9][0-9]*\)\.$ ]]; then state=started+ else return 1; fi+ fi+ count=1 ;;+ esac+ done <<< "$observation"+ [[ "$count" == 1 && -n "$code" ]] || return 1+ if [[ "$state" == started ]]; then [[ "$code" == 0 ]] || return 1+ else [[ "$code" == 1 || ( "$platform" != FreeBSD && "$code" == 3 ) ]] || return 1; fi+ printf '%s\n' "$state"+}++read_freebsd_agent_removal_enablement() {+ local observation=""+ observation=$(LC_ALL=C timeout -k 1 5 sysrc -n pulse_agent_enable 2>&1 &&+ printf '%s' '__pulse_enablement_complete__') || return 1+ case "$observation" in+ $'YES\n__pulse_enablement_complete__') printf 'enabled\n' ;;+ $'NO\n__pulse_enablement_complete__') printf 'disabled\n' ;;+ *) return 1 ;;+ esac+}++quiesce_freebsd_agent_for_removal() {+ local service_path="${1:-/usr/local/etc/rc.d/${AGENT_NAME}}" enabled="" inventory="" state=""+ # TrueNAS's bootstrap re-enables rc.conf and recreates this link. Until its+ # separate task is observably disabled, ordinary rc.d cannot authorise it.+ [[ ! -L "$service_path" && ! -e "${TRUENAS_BOOTSTRAP_SCRIPT:-}" ]] || return 1+ enabled=$(read_freebsd_agent_removal_enablement) || return 1+ inventory=$(read_legacy_agent_removal_processes) || return 1+ validate_legacy_agent_removal_pidfiles "$inventory" /var/run/pulse_agent.pid /var/run/pulse_agent.child.pid || return 1+ if [[ -e "$service_path" ]]; then+ [[ -f "$service_path" && -x "$service_path" ]] || return 1+ state=$(read_legacy_agent_removal_status "$service_path" FreeBSD) || return 1+ if [[ "$state" == stopped ]]; then legacy_agent_processes_absent "$inventory" || return 1+ else+ legacy_agent_processes_absent "$inventory" && return 1+ LC_ALL=C timeout -k 1 15 "$service_path" onestop >/dev/null 2>&1 || return 1+ fi+ else legacy_agent_processes_absent "$inventory" || return 1; fi+ if [[ "$enabled" != disabled ]]; then+ LC_ALL=C timeout -k 1 5 sysrc pulse_agent_enable=NO >/dev/null 2>&1 || return 1fi+ enabled=$(read_freebsd_agent_removal_enablement) || return 1+ [[ "$enabled" == disabled ]] || return 1+ if [[ -e "$service_path" ]]; then+ state=$(read_legacy_agent_removal_status "$service_path" FreeBSD) || return 1+ [[ "$state" == stopped ]] || return 1+ fi+ inventory=$(read_legacy_agent_removal_processes) || return 1+ legacy_agent_processes_absent "$inventory"+}+teardown_freebsd_agent_service() {+ local service_path="${1:-/usr/local/etc/rc.d/${AGENT_NAME}}"+ quiesce_freebsd_agent_for_removal "$service_path" ||+ fail "FreeBSD removal could not confirm rc.d stopped, boot activation disabled and both supervisor and child absent; recovery files were retained. Linked/appliance bootstrap installations need their owning boot task reconciled first. No automatic restart was attempted." "$EXIT_GENERAL"rm -f "$service_path"rm -f /usr/local/etc/rc.d/pulse_agent.shrm -f /var/run/pulse_agent.pid /var/run/pulse_agent.child.pid}+# Read every standard/custom rc*.d directory in both common SysV layouts.+# Only exact service links resolving to this init script are owned. Do not+# remove another script, a similarly named service or a malformed link.+read_sysv_agent_removal_links() {+ local init_path="$1" directory="" link="" name=""+ for directory in /etc/rc*.d /etc/rc.d/rc*.d; do+ [[ -e "$directory" || -L "$directory" ]] || continue+ [[ -d "$directory" && ! -L "$directory" && -r "$directory" && -x "$directory" ]] || return 1+ for link in "$directory"/*; do+ name="${link##*/}"+ case "$name" in+ [SK]*"$AGENT_NAME")+ [[ "$name" =~ ^[SK][0-9][0-9]pulse-agent$ && -L "$link" && "$link" -ef "$init_path" ]] || return 1+ printf '%s\n' "$link" ;;+ esac+ done+ done+ printf '%s\n' '__pulse_sysv_links_complete__'+}++quiesce_sysv_agent_for_removal() {+ local init_path="${1:-/etc/init.d/${AGENT_NAME}}" inventory="" state="" links="" link=""+ [[ ! -L "$init_path" ]] || return 1+ links=$(read_sysv_agent_removal_links "$init_path") || return 1+ inventory=$(read_legacy_agent_removal_processes) || return 1+ validate_legacy_agent_removal_pidfiles "$inventory" "/var/run/${AGENT_NAME}.pid" || return 1+ if [[ -e "$init_path" ]]; then+ [[ -f "$init_path" && -x "$init_path" ]] || return 1+ state=$(read_legacy_agent_removal_status "$init_path" SysV) || return 1+ if [[ "$state" == stopped ]]; then legacy_agent_processes_absent "$inventory" || return 1+ else+ legacy_agent_processes_absent "$inventory" && return 1+ LC_ALL=C timeout -k 1 10 "$init_path" stop >/dev/null 2>&1 || return 1+ fi+ else+ [[ "$links" == __pulse_sysv_links_complete__ ]] || return 1+ legacy_agent_processes_absent "$inventory" || return 1+ return 0+ fi+ if [[ "$links" != __pulse_sysv_links_complete__ ]]; then+ if command -v update-rc.d >/dev/null 2>&1; then+ LC_ALL=C timeout -k 1 5 update-rc.d -f "${AGENT_NAME}" remove >/dev/null 2>&1 || return 1+ elif command -v chkconfig >/dev/null 2>&1; then+ LC_ALL=C timeout -k 1 5 chkconfig "${AGENT_NAME}" off >/dev/null 2>&1 || return 1+ LC_ALL=C timeout -k 1 5 chkconfig --del "${AGENT_NAME}" >/dev/null 2>&1 || return 1+ else+ while IFS= read -r link; do+ [[ "$link" != __pulse_sysv_links_complete__ ]] || continue+ rm -f "$link" || return 1+ done <<< "$links"+ fi+ fi+ links=$(read_sysv_agent_removal_links "$init_path") || return 1+ [[ "$links" == __pulse_sysv_links_complete__ ]] || return 1+ state=$(read_legacy_agent_removal_status "$init_path" SysV) || return 1+ [[ "$state" == stopped ]] || return 1+ inventory=$(read_legacy_agent_removal_processes) || return 1+ legacy_agent_processes_absent "$inventory"+}+teardown_sysv_agent_service() {local init_path="${1:-/etc/init.d/${AGENT_NAME}}"- "$init_path" stop 2>/dev/null || true- if command -v update-rc.d >/dev/null 2>&1; then- update-rc.d -f "${AGENT_NAME}" remove >/dev/null 2>&1 || true- elif command -v chkconfig >/dev/null 2>&1; then- chkconfig "${AGENT_NAME}" off >/dev/null 2>&1 || true- chkconfig --del "${AGENT_NAME}" >/dev/null 2>&1 || true- fi- for RL in 0 1 2 3 4 5 6; do- rm -f "/etc/rc${RL}.d/S99${AGENT_NAME}" 2>/dev/null || true- rm -f "/etc/rc${RL}.d/K01${AGENT_NAME}" 2>/dev/null || true- done+ quiesce_sysv_agent_for_removal "$init_path" ||+ fail "SysV removal could not confirm a stopped process and no runlevel activation; recovery files were retained. Reconcile service state before retrying; no automatic restart was attempted." "$EXIT_GENERAL"rm -f "$init_path"rm -f "/var/run/${AGENT_NAME}.pid"}@@ -2916,6 +3082,15 @@ pulse_agent_start()fi}+pulse_agent_wait_stopped()+{+ for attempt in 1 2 3 4 5; do+ if ! kill -0 "\$1" 2>/dev/null; then return 0; fi+ sleep 1+ done+ ! kill -0 "\$1" 2>/dev/null+}+pulse_agent_stop(){supervisor_pid=""@@ -2943,21 +3118,23 @@ pulse_agent_stop()if [ -n "\${supervisor_pid}" ] && kill -0 "\${supervisor_pid}" 2>/dev/null; thenecho "Stopping \${name} supervisor."- kill "\${supervisor_pid}" 2>/dev/null || true+ kill "\${supervisor_pid}" 2>/dev/null || return 1sleep 1if kill -0 "\${supervisor_pid}" 2>/dev/null; then- kill -KILL "\${supervisor_pid}" 2>/dev/null || true+ kill -KILL "\${supervisor_pid}" 2>/dev/null || return 1fi+ pulse_agent_wait_stopped "\${supervisor_pid}" || return 1stopped=1fiif [ -n "\${child_pid}" ] && kill -0 "\${child_pid}" 2>/dev/null; thenecho "Stopping \${name} child."- kill "\${child_pid}" 2>/dev/null || true+ kill "\${child_pid}" 2>/dev/null || return 1sleep 1if kill -0 "\${child_pid}" 2>/dev/null; then- kill -KILL "\${child_pid}" 2>/dev/null || true+ kill -KILL "\${child_pid}" 2>/dev/null || return 1fi+ pulse_agent_wait_stopped "\${child_pid}" || return 1stopped=1fi@@ -5688,6 +5865,7 @@ if [[ "$UNINSTALL" == "true" ]]; thenlog_info "Uninstalling ${AGENT_NAME} and cleaning up legacy agents..."local qnap_state_dir=""local uninstall_has_credential="false"+ local uninstall_legacy_manager=""# Validate saved connection availability before stopping a working install.# Stop every systemd activation source before remote removal, process kills@@ -5708,6 +5886,16 @@ if [[ "$UNINSTALL" == "true" ]]; thenfail "Agent removal could not confirm OpenRC stopped with no runlevel activation; local credentials and files were retained. A preceding stop or disable may have succeeded: reconcile service state before retrying; no automatic restart was attempted." "$EXIT_GENERAL"fi+ if [[ "$(uname -s)" == FreeBSD ]]; then+ uninstall_legacy_manager=FreeBSD+ quiesce_freebsd_agent_for_removal ||+ fail "FreeBSD removal could not confirm stopped rc.d, disabled boot activation and absent supervisor/child; local recovery files were retained. Reconcile linked/appliance boot tasks first when present; no automatic restart was attempted." "$EXIT_GENERAL"+ elif ! command -v systemctl >/dev/null 2>&1 && ! command -v rc-service >/dev/null 2>&1 && [[ -d /etc/init.d ]]; then+ uninstall_legacy_manager=SysV+ quiesce_sysv_agent_for_removal ||+ fail "SysV removal could not confirm stopped process and disabled runlevels; local recovery files were retained. A preceding stop or disable may have succeeded; no automatic restart was attempted." "$EXIT_GENERAL"+ fi+# A credential-bearing install must durably remove its exact server record# through the same CA/fingerprint/no-proxy transport used by lifecycle# migration before any local credential or service state is deleted.@@ -5727,6 +5915,14 @@ if [[ "$UNINSTALL" == "true" ]]; thenteardown_openrc_agent_servicefi+ # Re-read the selected legacy manager after remote removal, before any+ # service/PID/credential deletion. Never restart a partially stopped install.+ if [[ "$uninstall_legacy_manager" == FreeBSD ]]; then+ teardown_freebsd_agent_service "/usr/local/etc/rc.d/${AGENT_NAME}"+ elif [[ "$uninstall_legacy_manager" == SysV ]]; then+ teardown_sysv_agent_service "/etc/init.d/${AGENT_NAME}"+ fi+# Kill wrapper scripts first: they are watchdogs, so stopping the agent# while its wrapper still loops only races the respawn. No leading path# separator here, unlike the install paths, so a wrapper invoked by a@@ -5850,7 +6046,7 @@ if [[ "$UNINSTALL" == "true" ]]; thenteardown_systemd_agent_serviceelif [[ "$(uname -s)" == "FreeBSD" ]]; thenlog_info "Removing TrueNAS CORE installation..."- teardown_freebsd_agent_service "/usr/local/etc/rc.d/${AGENT_NAME}"+ # rc.d teardown was confirmed before remote/local recovery erasure.fi# Remove Init/Shutdown taskif command -v midclt >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1; then@@ -5863,18 +6059,6 @@ if [[ "$UNINSTALL" == "true" ]]; thenrm -rf "$TRUENAS_STATE_DIR"fi- # Vanilla FreeBSD, OPNsense, and pfSense all use the rc.d service rendered- # by this installer. This must run even when no TrueNAS marker is present.- if [[ "$(uname -s)" == "FreeBSD" ]]; then- log_info "Removing FreeBSD rc.d installation..."- teardown_freebsd_agent_service "/usr/local/etc/rc.d/${AGENT_NAME}"- fi-- # SysV init (legacy systems like Asustor, older Debian/RHEL, etc.)- if [[ -f "/etc/init.d/${AGENT_NAME}" ]]; then- teardown_sysv_agent_service "/etc/init.d/${AGENT_NAME}"- fi-rm -f "${INSTALL_DIR}/${BINARY_NAME}"log_info "Uninstallation complete."exit 0@@ -7430,7 +7614,7 @@ do_stop() {return 0fiecho "Stopping $NAME..."- kill "$PID"+ kill "$PID" || return 1# Wait for process to stopfor i in 1 2 3 4 5; doif ! kill -0 "$PID" 2>/dev/null; then@@ -7441,7 +7625,15 @@ do_stop() {# Force kill if still runningif kill -0 "$PID" 2>/dev/null; thenecho "Force killing $NAME..."- kill -9 "$PID" 2>/dev/null || true+ kill -9 "$PID" 2>/dev/null || return 1+ fi+ for i in 1 2 3; do+ if ! kill -0 "$PID" 2>/dev/null; then break; fi+ sleep 1+ done+ if kill -0 "$PID" 2>/dev/null; then+ echo "Could not confirm $NAME stopped; PID file retained." >&2+ return 1firm -f "$PIDFILE"echo "$NAME stopped."diff --git a/scripts/installtests/agent_legacy_teardown.py b/scripts/installtests/agent_legacy_teardown.pynew file mode 100644index 0000000000..48cf708bc6--- /dev/null+++ b/scripts/installtests/agent_legacy_teardown.py@@ -0,0 +1,439 @@+#!/usr/bin/env python3+"""Production FreeBSD/SysV removal, confined to ordinary-user private fixtures.++Manager/process observations are closed models. The real uninstall admission,+post-remote teardown and rendered stop functions execute; no host service,+credential, signal, system file, network or native installation is exercised.+"""+import hashlib+import json+import os+from pathlib import Path+import shlex+import stat+import subprocess+import tempfile+import unittest++ROOT = Path(__file__).resolve().parents[2]+SOURCE = Path(os.environ.get("PULSE_AGENT_LEGACY_SOURCE", ROOT / "scripts/install.sh"))+FUNCTIONS = ("read_legacy_agent_removal_processes", "legacy_agent_processes_absent",+ "validate_legacy_agent_removal_pidfiles", "read_legacy_agent_removal_status",+ "read_freebsd_agent_removal_enablement", "quiesce_freebsd_agent_for_removal",+ "teardown_freebsd_agent_service", "read_sysv_agent_removal_links",+ "quiesce_sysv_agent_for_removal", "teardown_sysv_agent_service")+++def functions(source, names=FUNCTIONS):+ result = []+ for name in names:+ marker = name + "() {"+ if marker not in source: # Exact previous-source adverse controls.+ continue+ if source.count(marker) != 1:+ raise ValueError("ambiguous production function " + name)+ result.append(marker + source.split(marker, 1)[1].split("\n}\n", 1)[0] + "\n}\n")+ return "\n".join(result)+++MODEL = r'''#!/usr/bin/python3+import json, os, pathlib, sys+root = pathlib.Path(os.environ['FIXTURE'])+path = root / 'model.json'+v = json.loads(path.read_text())+role, a = pathlib.Path(sys.argv[0]).name, sys.argv[1:]+fault = v['fault']+remote = (root / 'events').exists() and 'remote:remove' in (root / 'events').read_text()+def save(): path.write_text(json.dumps(v))+def event(s):+ with (root / 'events').open('a') as f: f.write(s + '\n')+if role == 'ps':+ assert a == ['-ax', '-o', 'pid=', '-o', 'ppid=', '-o', 'comm=', '-o', 'args='], a+ event('process:read'); v['process_reads'] += 1; save()+ if fault == 'timeout-process':+ (root / 'timed-pid').write_text(str(os.getpid()))+ os.execl('/bin/sleep', 'sleep', '30')+ if fault == 'failed-process' or (fault == 'failed-final-process' and v['process_reads'] > 1): sys.exit(2)+ if fault == 'empty-process': sys.exit(0)+ print('1 0 init /sbin/init')+ if fault == 'duplicate-process': print('1 0 init /sbin/init')+ if v['state'] == 'started':+ if v['platform'] == 'FreeBSD':+ print('100 1 daemon daemon: /usr/local/bin/pulse-agent[101] (daemon)')+ print('101 100 pulse-agent /usr/local/bin/pulse-agent --token-file /private/synthetic')+ else: print('101 1 pulse-agent /usr/local/bin/pulse-agent --token-file /private/synthetic')+ if fault == 'orphan-supervisor' and v['state'] == 'stopped':+ print('100 1 daemon daemon: /usr/local/bin/pulse-agent[101] (daemon)')+ if fault == 'pid-reused': print('101 1 unrelated unrelated')+ if fault == 'diagnostic-process': print('read refused', file=sys.stderr)+ if fault == 'blank-process': print()+ sys.exit(0)+elif role == 'init':+ assert a in (['status'], ['onestatus'], ['stop'], ['onestop']), a+ if a[0] in ('stop', 'onestop'):+ event('service:stop')+ if fault == 'refused-stop' or (fault == 'refused-stop-after-remote' and remote): sys.exit(1)+ if fault != 'ignored-stop': v['state'] = 'stopped'+ save(); sys.exit(0)+ event('status:read'); v['status_reads'] += 1; save()+ if fault == 'failed-status' or (fault == 'failed-status-after-remote' and remote): sys.exit(2)+ state = v['state']+ if fault == 'false-stopped-status': state = 'stopped'+ code = 0 if state == 'started' else (1 if v['platform'] == 'FreeBSD' else 3)+ if fault == 'empty-status': sys.exit(code)+ if v['platform'] == 'FreeBSD':+ print('pulse_agent is running as supervisor pid 100 with child pid 101.' if state == 'started' else 'pulse_agent is not running.')+ else: print('pulse-agent is running (PID 101).' if state == 'started' else 'pulse-agent is not running.')+ if fault == 'diagnostic-status': print('read refused', file=sys.stderr)+ if fault == 'blank-status': print()+ if fault == 'wrong-status-exit': code = 3 if state == 'started' else 0+ sys.exit(code)+elif role == 'sysrc':+ if a == ['-n', 'pulse_agent_enable']:+ event('enable:read'); v['enable_reads'] += 1; save()+ if fault == 'failed-enable' or (fault == 'failed-final-enable' and v['enable_reads'] > 1): sys.exit(2)+ if fault == 'empty-enable': sys.exit(0)+ print('MAYBE' if fault == 'unknown-enable' else v['enabled'])+ if fault == 'diagnostic-enable': print('read refused', file=sys.stderr)+ if fault == 'blank-enable': print()+ sys.exit(0)+ assert a in (['pulse_agent_enable=NO'], ['-x', 'pulse_agent_enable']), a+ event('enable:disable')+ if fault == 'refused-disable': sys.exit(1)+ if fault != 'ignored-disable': v['enabled'] = 'NO'+ if fault == 'reactivation': v['state'] = 'started'+ save(); sys.exit(0)+elif role in ('update-rc.d', 'chkconfig'):+ assert a in (['-f', 'pulse-agent', 'remove'], ['pulse-agent', 'off'], ['--del', 'pulse-agent']), a+ event('links:disable:' + role)+ if fault == 'refused-disable': sys.exit(1)+ if fault != 'ignored-disable':+ for p in (root / 'etc').rglob('*pulse-agent'):+ if p.is_symlink(): p.unlink()+ if fault == 'reactivation': v['state'] = 'started'+ save(); sys.exit(0)+else: raise ValueError('operation outside private fixture')+'''+++class AgentLegacyTeardown(unittest.TestCase):+ source = SOURCE.read_text()++ def exercise(self, platform, *, fault="", flow="teardown", state="started", enabled="YES",+ manager="update-rc.d", path="regular", pid="normal", links="normal", reply="confirmed", repeat=False):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ tools = root / "tools"; tools.mkdir()+ for name in ("ps", "sysrc", "update-rc.d", "chkconfig"):+ p = tools / name; p.write_text(MODEL); p.chmod(0o700)+ init = root / "init"+ unrelated = root / "unrelated"; unrelated.write_text("retain unrelated file\n")+ if path == "linked": init.symlink_to(unrelated)+ elif path == "directory": init.mkdir()+ elif path != "missing":+ init.write_text(MODEL); init.chmod(0o600 if path == "not-executable" else 0o700)+ for name in ("state", "helper", "profile"):+ p = root / name; p.mkdir(); (p / "token").write_text("synthetic recovery only\n")+ (root / "wrapper").write_text("owned boot wrapper\n")+ for name in ("primary.pid", "child.pid", "sysv.pid"):+ (root / name).write_text(("100" if name == "primary.pid" else "101") + "\n")+ if pid == "malformed": (root / "child.pid" if platform == "FreeBSD" else root / "sysv.pid").write_text("101\n42\n")+ if pid == "linked":+ p = root / "child.pid" if platform == "FreeBSD" else root / "sysv.pid"+ p.unlink(); p.symlink_to(unrelated)+ if path == "bootstrap": (root / "bootstrap").write_text("appliance re-enables service\n")+ for name in ("rc3.d", "rcCustom.d", "rc.d/rc5.d"):+ d = root / "etc" / name; d.mkdir(parents=True)+ if platform == "SysV" and links != "none":+ (d / "S20pulse-agent").symlink_to(init if links != "foreign" else unrelated)+ (d / "K01pulse-agent").symlink_to(init)+ (d / "S99pulse-agent-other").symlink_to(unrelated)+ if links == "malformed": (root / "etc/rc3.d/Sbadpulse-agent").symlink_to(init)+ if links == "linked-directory":+ d = root / "etc/rc3.d"; d.rename(root / "hidden-runlevel"); d.symlink_to(root / "hidden-runlevel")+ (root / "model.json").write_text(json.dumps(dict(platform=platform, fault=fault, state=state,+ enabled=enabled, process_reads=0, status_reads=0, enable_reads=0)))+ before = self.snapshot(root)+ replacements = {'/usr/local/etc/rc.d/${AGENT_NAME}': str(init), '/usr/local/etc/rc.d/pulse_agent.sh': str(root / "wrapper"),+ '/var/run/pulse_agent.child.pid': str(root / "child.pid"), '/var/run/pulse_agent.pid': str(root / "primary.pid"),+ '/var/run/${AGENT_NAME}.pid': str(root / "sysv.pid"), '/etc/init.d/${AGENT_NAME}': str(init),+ '/etc/rc.d/rc*.d': str(root / "etc/rc.d") + '/rc*.d', '/etc/rc*.d': str(root / "etc") + '/rc*.d',+ '[[ -d /etc/init.d ]]': '[[ -d ' + shlex.quote(str(root / "etc")) + ' ]]'}+ def redirect(s):+ for key, value in replacements.items(): s = s.replace(key, value)+ return s+ values = dict(INIT_PATH=init, STATE_DIR=root / "state", PRIVILEGED_HELPER_STATE_DIR=root / "helper",+ SAFE_PROFILE_STATE_DIR=root / "profile", EVENTS=root / "events", REPLY=reply,+ TRUENAS_BOOTSTRAP_SCRIPT=root / "bootstrap", FIXTURE=root, PLATFORM=platform, MANAGER=manager)+ prefix = "\n".join(k + "=" + shlex.quote(str(v)) for k, v in values.items()) + "\n"+ shell = r'''+set -euo pipefail+AGENT_NAME=pulse-agent BINARY_NAME=pulse-agent UNINSTALL=true EXIT_GENERAL=1 EXIT_MISSING_ARGS=16+PULSE_URL=https://same-instance.example.invalid AGENT_ID=synthetic+ACTION_RUNNER_NAME=pulse-agent-runner PRIVILEGED_HELPER_NAME=pulse-agent-helper+log_info() { :; }; log_warn() { :; }+fail() { printf '%s\n' "$1" >&2; exit "${2:-1}"; }+uname() { [[ "$PLATFORM" == FreeBSD ]] && printf 'FreeBSD\n' || printf 'Linux\n'; }+command() {+ case "$*" in+ '-v systemctl'|'-v rc-service') return 1 ;;+ '-v update-rc.d') [[ "$MANAGER" == update-rc.d ]] || return 1 ;;+ '-v chkconfig') [[ "$MANAGER" == chkconfig ]] || return 1 ;;+ esac+ builtin command "$@"+}+collector_credential_state_present() { return 0; }+uninstall_collector_registration() {+ printf 'remote:remove\n' >> "$EVENTS"+ python3 - <<'END'+import json, os, pathlib+p = pathlib.Path(os.environ['FIXTURE']) / 'model.json'; v = json.loads(p.read_text())+if v['fault'] == 'refused-stop-after-remote': v['state'] = 'started'; p.write_text(json.dumps(v))+END+ [[ "$REPLY" == confirmed ]]+}+pkill() { printf 'process:stop\n' >> "$EVENTS"; }+sleep() { :; }+rm() {+ local arg+ for arg in "$@"; do+ [[ "$arg" == -* || "$arg" == "$FIXTURE/"* ]] || return 97+ done+ [[ "$*" != *"$INIT_PATH"* ]] || printf 'init:remove\n' >> "$EVENTS"+ builtin command rm "$@"+}+remove_agent_state_dir() { printf 'state:remove\n' >> "$EVENTS"; builtin command rm -r -- "$STATE_DIR"; }+remove_privileged_helper_state_dir() { builtin command rm -r -- "$PRIVILEGED_HELPER_STATE_DIR"; }+remove_safe_profile_state_dir() { builtin command rm -r -- "$SAFE_PROFILE_STATE_DIR"; }+'''+ if flow == "caller":+ entry = self.source.split("# --- Uninstall Logic ---\n", 1)[1].split(" # Remove least-privilege helper artifacts.", 1)[0] + "fi\n"+ invoke = "main() {\n" + redirect(entry) + "}\nmain\n"+ elif flow == "process": invoke = "read_legacy_agent_removal_processes\n"+ else:+ helper = "teardown_freebsd_agent_service" if platform == "FreeBSD" else "teardown_sysv_agent_service"+ invoke = (helper + ' "$INIT_PATH"\n') * (2 if repeat else 1)+ env = dict(os.environ, PATH=str(tools) + ":" + os.environ["PATH"], FIXTURE=str(root))+ result = subprocess.run(["bash", "-c", prefix + shell + redirect(functions(self.source)) + invoke],+ cwd=root, env=env, text=True, capture_output=True, timeout=12)+ events = (root / "events").read_text().splitlines() if (root / "events").exists() else []+ model = json.loads((root / "model.json").read_text())+ if (root / "timed-pid").exists():+ try: os.kill(int((root / "timed-pid").read_text()), 0); model["timed_child_absent"] = False+ except ProcessLookupError: model["timed_child_absent"] = True+ return result, events, before, self.snapshot(root), model++ @staticmethod+ def snapshot(root):+ result = {}+ for p in root.rglob("*"):+ if p.name in ("model.json", "events", "timed-pid") or "tools" in p.parts: continue+ info = p.lstat()+ data = os.readlink(p) if stat.S_ISLNK(info.st_mode) else (p.read_bytes() if stat.S_ISREG(info.st_mode) else None)+ result[str(p.relative_to(root))] = (info.st_mode, info.st_ino, data)+ return result++ def test_stop_refusal_retains_all_local_recovery(self):+ for platform in ("FreeBSD", "SysV"):+ with self.subTest(platform=platform):+ r, events, before, after, _ = self.exercise(platform, fault="refused-stop")+ self.assertNotEqual(r.returncode, 0, r.stderr)+ self.assertEqual(after, before)+ self.assertNotIn("init:remove", events)++ def test_manager_refusal_precedes_remote_and_state_erasure(self):+ for platform in ("FreeBSD", "SysV"):+ with self.subTest(platform=platform):+ r, events, before, after, _ = self.exercise(platform, fault="refused-stop", flow="caller")+ self.assertNotEqual(r.returncode, 0, r.stderr)+ self.assertEqual(after, before)+ self.assertNotIn("remote:remove", events)+ self.assertNotIn("state:remove", events)++ def test_ignored_stop_disable_and_reactivation_are_not_success(self):+ for platform in ("FreeBSD", "SysV"):+ for fault in ("ignored-stop", "refused-disable", "ignored-disable", "reactivation"):+ with self.subTest(platform=platform, fault=fault):+ r, events, before, after, _ = self.exercise(platform, fault=fault)+ self.assertNotEqual(r.returncode, 0, r.stderr)+ self.assertEqual(after, before)+ self.assertNotIn("init:remove", events)++ def test_failed_empty_diagnostic_or_duplicate_reads_are_not_absence(self):+ for platform in ("FreeBSD", "SysV"):+ for fault in ("failed-process", "empty-process", "duplicate-process", "diagnostic-process", "blank-process",+ "failed-status", "empty-status", "diagnostic-status", "blank-status", "wrong-status-exit", "false-stopped-status"):+ with self.subTest(platform=platform, fault=fault):+ r, events, before, after, model = self.exercise(platform, fault=fault)+ self.assertNotEqual(r.returncode, 0, r.stderr)+ self.assertEqual(after, before)+ self.assertNotIn("service:stop", events)+ self.assertLessEqual(model["process_reads"], 1)++ def test_enablement_refusals_and_unknown_values_retain_recovery(self):+ for fault in ("failed-enable", "empty-enable", "unknown-enable", "diagnostic-enable", "blank-enable", "failed-final-enable"):+ with self.subTest(fault=fault):+ r, events, before, after, _ = self.exercise("FreeBSD", fault=fault)+ self.assertNotEqual(r.returncode, 0, r.stderr)+ self.assertEqual(after, before)+ self.assertNotIn("init:remove", events)++ def test_final_process_read_and_orphan_supervisor_are_required(self):+ for platform, fault in (("SysV", "failed-final-process"), ("FreeBSD", "failed-final-process"), ("FreeBSD", "orphan-supervisor")):+ with self.subTest(platform=platform, fault=fault):+ r, events, before, after, _ = self.exercise(platform, fault=fault)+ self.assertNotEqual(r.returncode, 0, r.stderr)+ self.assertEqual(after, before)+ self.assertIn("service:stop", events)++ def test_pid_ownership_and_unexpected_paths_refuse_before_signals(self):+ for platform in ("FreeBSD", "SysV"):+ for args in (dict(fault="pid-reused"), dict(pid="malformed"), dict(pid="linked"), dict(path="linked"),+ dict(path="directory"), dict(path="not-executable")):+ with self.subTest(platform=platform, args=args):+ r, events, before, after, _ = self.exercise(platform, **args)+ self.assertNotEqual(r.returncode, 0, r.stderr)+ self.assertEqual(after, before)+ self.assertNotIn("service:stop", events)+ r, events, before, after, _ = self.exercise("FreeBSD", path="bootstrap", flow="caller")+ self.assertNotEqual(r.returncode, 0)+ self.assertEqual(after, before)+ self.assertNotIn("remote:remove", events)++ def test_every_owned_runlevel_link_and_both_layouts_are_removed(self):+ for manager in ("update-rc.d", "chkconfig", "manual"):+ with self.subTest(manager=manager):+ r, events, before, after, _ = self.exercise("SysV", manager=manager)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertFalse(any(k.endswith("S20pulse-agent") or k.endswith("K01pulse-agent") for k in after))+ for k, value in before.items():+ if k.endswith("pulse-agent-other") or k.startswith(("state", "helper", "profile", "unrelated")):+ self.assertEqual(after[k], value)++ def test_foreign_malformed_or_unobservable_runlevels_are_not_deleted(self):+ for links in ("foreign", "malformed", "linked-directory"):+ with self.subTest(links=links):+ r, events, before, after, _ = self.exercise("SysV", links=links)+ self.assertNotEqual(r.returncode, 0, r.stderr)+ self.assertEqual(after, before)+ self.assertNotIn("service:stop", events)++ def test_confirmed_manager_then_server_then_recheck_then_erasure(self):+ for platform in ("FreeBSD", "SysV"):+ with self.subTest(platform=platform):+ r, events, before, after, model = self.exercise(platform, flow="caller")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertLess(events.index("service:stop"), events.index("remote:remove"))+ self.assertLess(events.index("remote:remove"), events.index("init:remove"))+ self.assertLess(events.index("init:remove"), events.index("process:stop"))+ self.assertLess(events.index("init:remove"), events.index("state:remove"))+ self.assertGreaterEqual(model["process_reads"], 4)+ self.assertNotIn("state/token", after)+ self.assertEqual(after["unrelated"], before["unrelated"])++ def test_remote_refusal_keeps_stopped_install_and_all_recovery_files(self):+ for platform in ("FreeBSD", "SysV"):+ with self.subTest(platform=platform):+ r, events, before, after, model = self.exercise(platform, flow="caller", reply="refused")+ self.assertNotEqual(r.returncode, 0, r.stderr)+ for k in ("init", "state/token", "helper/token", "profile/token", "primary.pid", "child.pid", "sysv.pid"):+ self.assertEqual(after[k], before[k])+ self.assertEqual(model["state"], "stopped")+ self.assertNotIn("init:remove", events)+ self.assertNotIn("service:start", events)++ def test_late_refusal_keeps_local_recovery_after_remote_confirmation(self):+ for platform in ("FreeBSD", "SysV"):+ for fault in ("refused-stop-after-remote", "failed-status-after-remote"):+ with self.subTest(platform=platform, fault=fault):+ r, events, before, after, _ = self.exercise(platform, flow="caller", fault=fault)+ self.assertNotEqual(r.returncode, 0, r.stderr)+ for k in ("init", "state/token", "helper/token", "profile/token"):+ self.assertEqual(after[k], before[k])+ self.assertIn("remote:remove", events)+ self.assertNotIn("state:remove", events)+ self.assertNotIn("service:start", events)++ def test_known_stopped_missing_and_repeated_removal_are_safe(self):+ for platform in ("FreeBSD", "SysV"):+ for path, repeat in (("regular", False), ("missing", False), ("regular", True)):+ with self.subTest(platform=platform, path=path, repeat=repeat):+ r, events, before, after, _ = self.exercise(platform, state="stopped", enabled="NO", links="none", path=path, repeat=repeat)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertNotIn("service:stop", events)+ for k in ("state/token", "helper/token", "profile/token", "unrelated"):+ self.assertEqual(after[k], before[k])++ def test_process_inventory_does_not_return_arguments_or_secrets(self):+ r, _, _, _, _ = self.exercise("FreeBSD", flow="process")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("100 1 supervisor\n", r.stdout)+ self.assertIn("101 100 agent\n", r.stdout)+ self.assertNotIn("synthetic", r.stdout)+ self.assertNotIn("token", r.stdout)++ def test_real_process_timeout_stops_owned_child_without_erasure(self):+ r, events, before, after, model = self.exercise("FreeBSD", fault="timeout-process")+ self.assertNotEqual(r.returncode, 0, r.stderr)+ self.assertEqual(after, before)+ self.assertTrue(model["timed_child_absent"])+ self.assertNotIn("service:stop", events)++ def test_rendered_stop_retains_pidfiles_on_refused_or_ignored_signals(self):+ for platform in ("FreeBSD", "SysV"):+ for fault in ("refused", "ignored", ""):+ with self.subTest(platform=platform, fault=fault):+ self.rendered_stop(platform, fault)++ def rendered_stop(self, platform, fault):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ primary, child = root / "primary.pid", root / "child.pid"+ primary.write_text("100\n"); child.write_text("101\n")+ if platform == "FreeBSD":+ render = functions(self.source, ("render_freebsd_rc_agent_script",))+ rendered = root / "rendered"+ r = subprocess.run(["bash", "-c", 'SHELL_EXPORT_LINES=""\n' + render + '\nrender_freebsd_rc_agent_script "$1" /synthetic/pulse-agent ""', "proof", str(rendered)], text=True, capture_output=True)+ self.assertEqual(r.returncode, 0, r.stderr)+ source = rendered.read_text()+ names = ("pulse_agent_pid_command", "pulse_agent_supervisor_pid", "pulse_agent_wait_stopped", "pulse_agent_stop")+ bodies = []+ for name in names:+ marker = name + "()\n{"+ if marker in source: bodies.append(marker + source.split(marker, 1)[1].split("\n}\n", 1)[0] + "\n}\n")+ code = "\n".join(bodies); invocation = "pulse_agent_stop"+ else:+ source = self.source.split("# Pulse Unified Agent SysV init script", 1)[1].split("\nINITEOF", 1)[0]+ marker = "do_stop() {"+ code = marker + source.split(marker, 1)[1].split("\n}\n", 1)[0] + "\n}\n"+ invocation = "do_stop"+ values = dict(pidfile=primary, child_pidfile=child, PIDFILE=primary, EVENTS=root / "events", FAULT=fault)+ prefix = "\n".join(k + "=" + shlex.quote(str(v)) for k, v in values.items()) + "\n"+ shell = r'''+name=pulse_agent NAME=pulse-agent alive100=true alive101=true+sleep() { :; }+ps() { [[ "$*" == *ppid* ]] && printf '1\n' || printf 'daemon: /synthetic/pulse-agent[101]\n'; }+kill() {+ local pid="${@: -1}" flag="alive${@: -1}"+ [[ "$pid" == 100 || "$pid" == 101 ]] || return 90+ if [[ "$1" == -0 ]]; then [[ "${!flag}" == true ]]; return; fi+ printf 'signal:%s\n' "$pid" >> "$EVENTS"+ [[ "$FAULT" != refused ]] || return 1+ [[ "$FAULT" == ignored ]] || printf -v "$flag" false+}+'''+ before = (primary.read_bytes(), child.read_bytes())+ r = subprocess.run(["bash", "-c", prefix + shell + code + "\n" + invocation], text=True, capture_output=True, timeout=5)+ if fault:+ self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr)+ self.assertEqual((primary.read_bytes(), child.read_bytes()), before)+ else:+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertFalse(primary.exists())+ if platform == "FreeBSD":+ self.assertFalse(child.exists())+ self.assertEqual((root / "events").read_text().splitlines(), ["signal:100", "signal:101"])+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.goindex 1539f7e75e..a5b3b7235b 100644--- a/scripts/installtests/install_sh_test.go+++ b/scripts/installtests/install_sh_test.go@@ -2813,11 +2813,12 @@ func TestInstallSHUsesCanonicalFreeBSDAgentTeardown(t *testing.T) {script := string(content)required := []string{`teardown_freebsd_agent_service() {`,- `"$service_path" stop 2>/dev/null || true`,- `sysrc -x pulse_agent_enable >/dev/null 2>&1 || true`,+ `quiesce_freebsd_agent_for_removal "$service_path" ||`,+ `timeout -k 1 15 "$service_path" onestop >/dev/null 2>&1 || return 1`,+ `timeout -k 1 5 sysrc pulse_agent_enable=NO >/dev/null 2>&1 || return 1`,`rm -f /usr/local/etc/rc.d/pulse_agent.sh`,`rm -f /var/run/pulse_agent.pid /var/run/pulse_agent.child.pid`,- `log_info "Removing FreeBSD rc.d installation..."`,+ `uninstall_legacy_manager=FreeBSD`,`teardown_freebsd_agent_service "/usr/local/etc/rc.d/${AGENT_NAME}"`,}for _, needle := range required {@@ -8409,3 +8410,42 @@ func TestInstallSHOpenRCTeardownRequiresObservedQuiescence(t *testing.T) {}t.Logf("%s", output)}++func TestInstallSHLegacyTeardownRequiresObservedQuiescence(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("Unix rc.d/SysV controls; Windows has its own native SCM gate")+ }+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)+ defer cancel()+ cmd := exec.CommandContext(ctx, "python3", repoFile("scripts", "installtests", "agent_legacy_teardown.py"))+ output, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("legacy manager removal controls: %v\n%s", err, output)+ }+ for _, name := range []string{+ "test_stop_refusal_retains_all_local_recovery",+ "test_manager_refusal_precedes_remote_and_state_erasure",+ "test_ignored_stop_disable_and_reactivation_are_not_success",+ "test_failed_empty_diagnostic_or_duplicate_reads_are_not_absence",+ "test_enablement_refusals_and_unknown_values_retain_recovery",+ "test_final_process_read_and_orphan_supervisor_are_required",+ "test_pid_ownership_and_unexpected_paths_refuse_before_signals",+ "test_every_owned_runlevel_link_and_both_layouts_are_removed",+ "test_foreign_malformed_or_unobservable_runlevels_are_not_deleted",+ "test_confirmed_manager_then_server_then_recheck_then_erasure",+ "test_remote_refusal_keeps_stopped_install_and_all_recovery_files",+ "test_late_refusal_keeps_local_recovery_after_remote_confirmation",+ "test_known_stopped_missing_and_repeated_removal_are_safe",+ "test_process_inventory_does_not_return_arguments_or_secrets",+ "test_real_process_timeout_stops_owned_child_without_erasure",+ "test_rendered_stop_retains_pidfiles_on_refused_or_ignored_signals",+ } {+ if !strings.Contains(string(output), name+" (__main__.AgentLegacyTeardown."+name+") ... ok") {+ t.Fatalf("legacy manager control %s did not pass:\n%s", name, output)+ }+ }+ if !strings.Contains(string(output), "\nRan 16 tests in ") || !strings.Contains(string(output), "\nOK\n") {+ t.Fatalf("incomplete legacy manager verdict:\n%s", output)+ }+ t.Logf("%s", output)+}