Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Require running executable proof for unattended update success

pulse-triage[bot]7eb12d0bf5ad
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index b31edf9c11..d4748a2b8c 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -133,6 +133,36 @@ restoration safeguards. These facts
cannot reconstruct exits or signals from an earlier interrupted attempt, or
identify who stopped a host.
+### Active service state cannot stand in for the running executable
+
+After installed-version and active-state verification, the unattended updater
+compares the selected executable with the actual Linux `/proc/MainPID/exe` bytes.
+Two complete, bounded observations of the exact unit's LoadState, ActiveState
+and positive MainPID must surround that comparison and retain the same active
+PID. Successful recovery of a previously active unit has the same requirement
+before releasing its rollback backup. Equivalent bytes at a custom or symlinked
+path are admitted; replacing an old process's on-disk path is not proof that
+that process uses the replacement. A broken primary executable never falls
+back to an unrelated legacy file.
+
+Missing, duplicated, extra, failed or timed-out observations, an unavailable or
+different executable, a zero/malformed PID, or an identity/activity change leave
+the backup retained and current service alone for manual reconciliation. They
+cannot claim update/restoration success and grant no additional start, stop,
+rollback, mask/permission change or retry. A previously inactive unit that
+remains inactive still needs only installed-file verification; if it becomes
+active, its actual running executable must be checked too.
+
+`TestAutoUpdateServiceStateFailsClosed` requires the production-path success and
+restore refusal controls. `TestAutoUpdateRunningExecutableIdentity` requires
+Linux owned-process byte/readback/deadline controls: they run a private
+executable, atomically replace its path and inspect its real `/proc` entry.
+They do not use a native manager or install Pulse. Existing signed/manager-double
+matrices keep that distinction explicit. The containing hosted systemd recipe
+supplies real-Pulse/source/native evidence; this source repair alone establishes
+neither that result nor #2785's stop cause, published historical upgrade, timer
+sandbox or authenticated browser recovery.
+
### Current-source unattended transactions have a native CI check
After the same checkout's production frontend, backend build and vet, ordinary
diff --git a/scripts/installtests/pulse_auto_update_test.go b/scripts/installtests/pulse_auto_update_test.go
index e45363efcf..8b6a77cf5d 100644
--- a/scripts/installtests/pulse_auto_update_test.go
+++ b/scripts/installtests/pulse_auto_update_test.go
@@ -131,7 +131,7 @@ func TestAutoUpdateServiceDiscoveryAndInstallerHandoff(t *testing.T) {
func TestAutoUpdateServiceStateFailsClosed(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
- cmd := exec.CommandContext(ctx, "python3", repoFile("scripts", "tests", "test_auto_update_service_state.py"), "-v")
+ cmd := exec.CommandContext(ctx, "python3", repoFile("scripts", "tests", "test_auto_update_service_state.py"), "-v", "UpdateServiceState")
cmd.Env = append(os.Environ(), "PULSE_AUTO_UPDATER_UNDER_TEST="+repoFile("scripts", "pulse-auto-update.sh"))
out, err := cmd.CombinedOutput()
if err != nil {
@@ -140,12 +140,15 @@ func TestAutoUpdateServiceStateFailsClosed(t *testing.T) {
// Keep the collector controls part of actual package acceptance, not just
// an optional Python check. A green fixture with these methods removed
// would otherwise silently lose early-failure and final-line coverage.
- for _, name := range []string{
+ required := []string{
+ "test_success_cannot_claim_unverified_running_executable",
+ "test_rollback_keeps_backup_until_restored_running_executable_matches",
"test_early_collector_failure_survives_later_success_and_drains_installer",
"test_unterminated_final_installer_line_is_collected_and_its_failure_retained",
"test_real_log_retains_each_sink_failure_in_conditional_calls",
"test_real_logger_failure_drains_installer_and_preserves_recovery",
- } {
+ }
+ for _, name := range required {
passed := false
for _, line := range strings.Split(string(out), "\n") {
if strings.HasPrefix(line, name+" (") && strings.HasSuffix(line, " ... ok") {
@@ -158,12 +161,48 @@ func TestAutoUpdateServiceStateFailsClosed(t *testing.T) {
}
}
+// A real owned process retains its old executable after its disk path changes.
+// This tests Linux process identity, not a native systemd/application journey.
+func TestAutoUpdateRunningExecutableIdentity(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("Linux /proc executable identity; portable transaction controls remain required")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, "python3", repoFile("scripts", "tests", "test_auto_update_service_state.py"), "-v", "RunningExecutable")
+ cmd.Env = append(os.Environ(), "PULSE_AUTO_UPDATER_UNDER_TEST="+repoFile("scripts", "pulse-auto-update.sh"))
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("running executable identity controls: %v\n%s", err, out)
+ }
+ for _, name := range []string{
+ "test_actual_process_not_replaced_disk_path_is_checked",
+ "test_complete_stable_main_pid_tuple_is_required",
+ "test_identity_read_timeout_is_bounded_and_owned_process_is_reaped",
+ } {
+ passed := false
+ for _, line := range strings.Split(string(out), "\n") {
+ if strings.HasPrefix(line, name+" (") && strings.HasSuffix(line, " ... ok") {
+ passed = true
+ }
+ }
+ if !passed {
+ t.Fatalf("required running executable control %s did not pass:\n%s", name, out)
+ }
+ }
+}
+
func extractAutoUpdateServiceFunctions(t *testing.T) string {
t.Helper()
var functions []string
for _, name := range []string{"read_update_service_state", "start_update_service_if_stopped", "stop_update_service_for_rollback", "wait_for_service_active", "ensure_service_restarted"} {
functions = append(functions, extractAutoUpdateFunction(t, name))
}
+ // These pure-shell controls have simulated service state and script
+ // executables, not a managed process. The registered Python controls
+ // exercise real owned /proc entries and fail-closed transaction wiring;
+ // containing source CI separately checks actual systemd/Pulse processes.
+ functions = append(functions, "verify_update_running_executable() { return 0; }")
return strings.Join(functions, "\n")
}
@@ -871,6 +910,9 @@ func runAutoUpdateTransactionScenario(t *testing.T, fault, outcome, layout, acti
script := `
set -euo pipefail
source "$UPDATER_UNDER_TEST"
+# This signed transaction matrix simulates the manager. Running-process
+# identity is exercised by the real owned-process Python controls, not here.
+verify_update_running_executable() { return 0; }
INSTALL_DIR="$FIXTURE_DIR/install"
CONFIG_DIR="$FIXTURE_DIR/config"
mkdir -p "$INSTALL_DIR/bin" "$CONFIG_DIR" "$FIXTURE_DIR/tmp" "$FIXTURE_DIR/original"
diff --git a/scripts/pulse-auto-update.sh b/scripts/pulse-auto-update.sh
index 667ed35ed0..3601a9fb62 100755
--- a/scripts/pulse-auto-update.sh
+++ b/scripts/pulse-auto-update.sh
@@ -406,6 +406,63 @@ read_update_service_state() {
esac
}
+# Active alone can describe an old executable left running after replacement.
+# Read one complete tuple so a missing/recycled process is not update evidence.
+read_update_service_main_pid() {
+ local service_name=$1 observation="" line="" load="" state="" pid=""
+ local seen_load=false seen_state=false seen_pid=false
+ if ! observation=$(LC_ALL=C timeout -k 1 5 systemctl show "$service_name" --no-pager --property=LoadState --property=ActiveState --property=MainPID 2>/dev/null); then
+ log error "Cannot read running Pulse identity ($service_name); reconcile service state before recovery" >&2
+ return 1
+ fi
+ while IFS= read -r line; do
+ case "$line" in
+ LoadState=*)
+ [[ "$seen_load" == false ]] || return 1
+ seen_load=true; load=${line#LoadState=} ;;
+ ActiveState=*)
+ [[ "$seen_state" == false ]] || return 1
+ seen_state=true; state=${line#ActiveState=} ;;
+ MainPID=*)
+ [[ "$seen_pid" == false ]] || return 1
+ seen_pid=true; pid=${line#MainPID=} ;;
+ *) return 1 ;;
+ esac
+ done <<< "$observation"
+ if [[ "$seen_load" != true || "$seen_state" != true || "$seen_pid" != true ||
+ ( "$load" != loaded && "$load" != masked ) || "$state" != active ||
+ ! "$pid" =~ ^[1-9][0-9]*$ ]]; then
+ log error "Incomplete running Pulse identity ($service_name); reconcile service state before recovery" >&2
+ return 1
+ fi
+ printf '%s\n' "$pid"
+}
+
+# Never restart/roll back merely because process readback is unavailable or
+# differs. Keep the backup and current service for explicit reconciliation.
+# Byte comparison admits an equivalent executable at a custom/symlinked path,
+# but not a VERSION sidecar or an old process whose on-disk path was replaced.
+verify_update_running_executable() {
+ local service_name=$1 binary="" before_pid="" after_pid=""
+ if [[ -e "$INSTALL_DIR/bin/pulse" || -L "$INSTALL_DIR/bin/pulse" ]]; then
+ binary="$INSTALL_DIR/bin/pulse"
+ else
+ binary="$INSTALL_DIR/pulse"
+ fi
+ before_pid=$(read_update_service_main_pid "$service_name") || return 2
+ if [[ ! -f "$binary" || ! -x "$binary" ]] ||
+ ! timeout -k 1 5 cmp -s -- "$binary" "/proc/$before_pid/exe"; then
+ log error "Cannot confirm running Pulse matches the installed executable ($service_name)" >&2
+ return 2
+ fi
+ after_pid=$(read_update_service_main_pid "$service_name") || return 2
+ if [[ "$before_pid" != "$after_pid" ]]; then
+ log error "Running Pulse identity changed during verification ($service_name)" >&2
+ return 2
+ fi
+ return 0
+}
+
# Only a fresh, settled observation permits an explicit start. Return 2 for
# uncertainty so callers do not turn an unavailable read into rollback consent.
start_update_service_if_stopped() {
@@ -639,6 +696,12 @@ perform_update() {
elif [[ "$service_result" != 0 ]]; then
log error "Pulse service did not come back up after update"
else
+ if ! verify_update_running_executable "$service_name"; then
+ retain_backup="true"
+ restart_allowed="false"
+ log error "Running Pulse executable is unverified; backup retained at $backup_dir; reconcile service state before recovery"
+ return 1
+ fi
update_accepted="true"
fi
else
@@ -646,7 +709,15 @@ perform_update() {
# not the obligation to observe the installed unit safely.
service_state=$(read_update_service_state "$service_name") || service_state="unknown"
case "$service_state" in
- active|inactive|failed) update_accepted="true" ;;
+ active)
+ if ! verify_update_running_executable "$service_name"; then
+ retain_backup="true"
+ restart_allowed="false"
+ log error "Running Pulse executable is unverified; backup retained at $backup_dir; reconcile service state before recovery"
+ return 1
+ fi
+ update_accepted="true" ;;
+ inactive|failed) update_accepted="true" ;;
*)
retain_backup="true"
restart_allowed="false"
@@ -713,6 +784,10 @@ perform_update() {
log error "Restored Pulse could not be started; backup retained at $backup_dir; manual recovery required"
return 1
fi
+ if ! verify_update_running_executable "$service_name"; then
+ log error "Restored running Pulse executable is unverified; backup retained at $backup_dir; manual recovery required"
+ return 1
+ fi
fi
retain_backup="false"
log info "Previous installation restored"
diff --git a/scripts/tests/test_auto_update_service_state.py b/scripts/tests/test_auto_update_service_state.py
index 46a0fa2d06..382e46b9d3 100644
--- a/scripts/tests/test_auto_update_service_state.py
+++ b/scripts/tests/test_auto_update_service_state.py
@@ -9,7 +9,9 @@ transaction tests separately exercise real local SSH signatures and metadata.
import json
import os
from pathlib import Path
+import shutil
import subprocess
+import sys
import tempfile
import time
import unittest
@@ -79,6 +81,12 @@ log() {
fi
}
fi
+# This transaction fixture has a simulated manager and shell-script binaries.
+# The separate process controls below exercise the production /proc comparison.
+verify_update_running_executable() {
+ printf '%s\n' "$(get_current_version)" >> "$FIXTURE/runtime-probes"
+ return "$RUNTIME_EXIT"
+}
detect_service_name() { printf '%s\n' "$SERVICE_NAME"; }
sleep() { :; } # Only the liveness wait; timeout/manager deadlines are real.
verify_release_signature() { :; }
@@ -138,7 +146,7 @@ sys.exit(0)
class UpdateServiceState(unittest.TestCase):
def run_fixture(self, *, mode="normal", state="active", load="loaded", success=False, flow="update",
installer_exit=None, collector_exit=0, installer_output=None, collector_failures=None,
- real_log=False):
+ real_log=False, runtime_exit=0, installer_state=None):
with tempfile.TemporaryDirectory(prefix="pulse-updater-state-") as directory:
f = Path(directory)
for name in ("tools", "tmp", "install/bin", "config"):
@@ -172,10 +180,10 @@ class UpdateServiceState(unittest.TestCase):
env.update(FIXTURE=str(f), UPDATER=str(UPDATER), MODE=mode, FLOW=flow,
PULSE_INSTALL_DIR=str(f / "install"), PULSE_CONFIG_DIR=str(f / "config"),
PULSE_SERVICE_NAME="pulse-custom@department", LOAD_STATE=load,
- INSTALLER_STATE="active" if mode in ("stop-noop", "stop-error", "stop-hang", "after-error", "readback-error", "readback-empty") else "inactive",
+ INSTALLER_STATE=installer_state if installer_state is not None else ("active" if mode in ("stop-noop", "stop-error", "stop-hang", "after-error", "readback-error", "readback-empty") else "inactive"),
INSTALLER_EXIT=str(installer_exit) if installer_exit is not None else ("0" if success else "23"),
COLLECTOR_EXIT=str(collector_exit),
- REAL_LOG="true" if real_log else "false",
+ REAL_LOG="true" if real_log else "false", RUNTIME_EXIT=str(runtime_exit),
PATH=str(f / "tools") + os.pathsep + os.environ["PATH"])
for line, status in (collector_failures or {}).items():
env[f"COLLECTOR_EXIT_{line}"] = str(status)
@@ -188,6 +196,8 @@ class UpdateServiceState(unittest.TestCase):
downloaded=(f / "downloads").exists(), temporary=(f / "temp-requests").exists(),
installed=(f / "installer-ran").exists(), stopped=(f / "stop-ran").exists(),
installer_finished=(f / "installer-finished").exists(),
+ runtime_probes=(f / "runtime-probes").read_text().splitlines()
+ if (f / "runtime-probes").exists() else [],
collected=int((f / "collector-count").read_text()) if (f / "collector-count").exists() else 0,
logger_calls=[json.loads(line) for line in (f / "logger-calls").read_text().splitlines()]
if (f / "logger-calls").exists() else [],
@@ -258,6 +268,35 @@ class UpdateServiceState(unittest.TestCase):
self.assertEqual(r["started"], state == "active")
self.assertEqual(r["backups"], [])
+ def test_success_cannot_claim_unverified_running_executable(self):
+ # A matching new disk version and an active manager are insufficient.
+ # Preserve the currently active service; uncertainty grants no stop,
+ # second start or rollback, including a previously inactive unit.
+ for prior_state in ("active", "inactive"):
+ with self.subTest(prior_state=prior_state):
+ r = self.run_fixture(state=prior_state, success=True,
+ installer_state="active", runtime_exit=2)
+ self.assertEqual(r["exit"], 1)
+ self.assertEqual(r["runtime_probes"], ["v6.6.0"])
+ self.assertFalse(r["started"] or r["stopped"])
+ self.assertEqual(r["state"], "active")
+ self.assertEqual(r["version"], "v6.6.0\n")
+ self.assertEqual(r["backups"], [b"#!/bin/sh\necho 'Pulse v6.5.0'\n"])
+ self.assertIn("Running Pulse executable is unverified; backup retained", r["output"])
+ self.assertNotIn("Update successfully installed and verified", r["output"])
+ self.assertNotIn("Restoring from backup", r["output"])
+
+ def test_rollback_keeps_backup_until_restored_running_executable_matches(self):
+ r = self.run_fixture(state="active", success=False, runtime_exit=2)
+ self.assertEqual(r["exit"], 1)
+ self.assertEqual(r["runtime_probes"], ["v6.5.0"])
+ self.assertTrue(r["started"])
+ self.assertEqual(r["state"], "active")
+ self.assertEqual(r["version"], "v6.5.0\n")
+ self.assertEqual(r["backups"], [b"#!/bin/sh\necho 'Pulse v6.5.0'\n"])
+ self.assertIn("Restored running Pulse executable is unverified; backup retained", r["output"])
+ self.assertNotIn("Previous installation restored", r["output"])
+
def test_unknown_initial_state_refuses_before_backup_download_or_installer(self):
cases = [(m, "active", "loaded") for m in
("initial-error", "initial-empty", "initial-duplicate", "initial-extra")]
@@ -411,5 +450,102 @@ class UpdateServiceState(unittest.TestCase):
self.assertFalse(r["started"] or r["stopped"] or r["installed"], r)
+
+PROCESS_MANAGER = r'''#!/usr/bin/env python3
+import os, sys, time
+from pathlib import Path
+f = Path(os.environ["FIXTURE"])
+args = sys.argv[1:]
+expected = ["show", "pulse-custom@department", "--no-pager", "--property=LoadState", "--property=ActiveState", "--property=MainPID"]
+if args != expected: sys.exit(97)
+count = int((f / "observations").read_text()) + 1 if (f / "observations").exists() else 1
+(f / "observations").write_text(str(count))
+mode = os.environ["IDENTITY_MODE"]
+if mode == "error": sys.exit(1)
+if mode == "hang": time.sleep(30)
+pid = os.environ["OWNED_PID"]
+if mode == "pid-zero": pid = "0"
+if mode == "pid-negative": pid = "-1"
+if mode == "pid-path": pid = "../self"
+if mode == "pid-missing-process": pid = "999999999999"
+if mode == "pid-moved" and count > 1: pid = os.environ["DIFFERENT_PID"]
+load = "not-found" if mode == "not-found" else ("masked" if mode == "masked" else "loaded")
+state = "inactive" if mode == "inactive" or (mode == "state-moved" and count > 1) else "active"
+# Deliberately reverse property order, as systemd does not promise an order.
+print("MainPID=" + pid)
+if mode != "missing": print("ActiveState=" + state)
+print("LoadState=" + load)
+if mode == "duplicate": print("MainPID=" + pid)
+if mode == "extra": print("Unknown=value")
+'''
+
+
[email protected](sys.platform.startswith("linux"), "Linux /proc executable identity; transaction controls remain portable")
+class RunningExecutable(unittest.TestCase):
+ def run_identity(self, mode="normal", binary_mode="same"):
+ with tempfile.TemporaryDirectory(prefix="pulse-owned-process-") as directory:
+ f = Path(directory); (f / "tools").mkdir(); (f / "install/bin").mkdir(parents=True)
+ installed = f / "install/bin/pulse"
+ shutil.copyfile(sys.executable, installed); installed.chmod(0o700)
+ tool = f / "tools/systemctl"; tool.write_text(PROCESS_MANAGER); tool.chmod(0o700)
+ # Run the copied executable, then replace its path: /proc/PID/exe
+ # still observes the actual old executable, not the new path bytes.
+ child = subprocess.Popen([str(installed), "-c", "import time; print('ready', flush=True); time.sleep(30)"],
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ try:
+ self.assertEqual(child.stdout.readline(), b"ready\n")
+ if binary_mode in ("different", "same-copy", "nonexecutable"):
+ replacement = f / "replacement"
+ shutil.copyfile("/bin/sleep" if binary_mode == "different" else sys.executable, replacement)
+ replacement.chmod(0o600 if binary_mode == "nonexecutable" else 0o700)
+ replacement.replace(installed)
+ elif binary_mode == "symlink":
+ installed.unlink(); installed.symlink_to(sys.executable)
+ elif binary_mode == "legacy":
+ installed.rename(f / "install/pulse")
+ elif binary_mode == "missing":
+ installed.unlink()
+ elif binary_mode == "broken-primary":
+ installed.unlink(); installed.symlink_to(f / "missing")
+ shutil.copyfile(sys.executable, f / "install/pulse")
+ env = dict(os.environ, FIXTURE=str(f), UPDATER=str(UPDATER),
+ PULSE_INSTALL_DIR=str(f / "install"), OWNED_PID=str(child.pid),
+ DIFFERENT_PID=str(os.getpid()), IDENTITY_MODE=mode,
+ PATH=str(f / "tools") + os.pathsep + os.environ["PATH"])
+ script = ('set -euo pipefail\nsource "$UPDATER"\nlog() { :; }\n'
+ 'status=0\nverify_update_running_executable pulse-custom@department || status=$?\n'
+ 'printf "IDENTITY_STATUS=%s\\n" "$status"\nexit "$status"\n')
+ started = time.monotonic()
+ r = subprocess.run(["bash", "-c", script], env=env, capture_output=True, timeout=10)
+ return r, time.monotonic() - started, int((f / "observations").read_text())
+ finally:
+ child.terminate()
+ child.communicate(timeout=5)
+ self.assertIsNotNone(child.returncode)
+
+ def test_actual_process_not_replaced_disk_path_is_checked(self):
+ for binary in ("same", "same-copy", "symlink", "legacy", "different", "nonexecutable", "missing", "broken-primary"):
+ with self.subTest(binary=binary):
+ r, _, observations = self.run_identity(binary_mode=binary)
+ accepted = binary in ("same", "same-copy", "symlink", "legacy")
+ self.assertEqual(r.returncode, 0 if accepted else 2, r.stderr)
+ self.assertIn(b"IDENTITY_STATUS=0" if accepted else b"IDENTITY_STATUS=2", r.stdout)
+ self.assertEqual(observations, 2 if accepted else 1)
+
+ def test_complete_stable_main_pid_tuple_is_required(self):
+ for mode in ("normal", "masked", "error", "missing", "duplicate", "extra", "inactive", "not-found",
+ "pid-zero", "pid-negative", "pid-path", "pid-missing-process", "pid-moved", "state-moved"):
+ with self.subTest(mode=mode):
+ r, _, observations = self.run_identity(mode=mode)
+ accepted = mode in ("normal", "masked")
+ self.assertEqual(r.returncode, 0 if accepted else 2, r.stderr)
+ self.assertEqual(observations, 2 if accepted or mode in ("pid-moved", "state-moved") else 1)
+
+ def test_identity_read_timeout_is_bounded_and_owned_process_is_reaped(self):
+ r, elapsed, observations = self.run_identity(mode="hang")
+ self.assertEqual(r.returncode, 2)
+ self.assertEqual(observations, 1)
+ self.assertLess(elapsed, 8)
+
if __name__ == "__main__":
unittest.main()
diff --git a/scripts/tests/test_auto_update_systemd.py b/scripts/tests/test_auto_update_systemd.py
index c568862690..a3c4b346e9 100644
--- a/scripts/tests/test_auto_update_systemd.py
+++ b/scripts/tests/test_auto_update_systemd.py
@@ -428,10 +428,12 @@ if name == "sudo":
@unittest.skipUnless(sys.platform.startswith("linux"), LINUX_ONLY_REASON)
def test_connected_signed_archive_and_recovery_controls_without_host_manager(self):
# Same orchestration and production shell functions, real signatures and
- # ELF staging. Only this test replaces the manager, account/chown and
- # unit output path. It is not native or real-Pulse runtime acceptance.
+ # ELF staging. This test replaces the manager, its process-byte readback,
+ # account/chown and unit path. /proc/123/exe maps only to the executable
+ # snapshot made by that simulated manager's start. Real owned /proc
+ # checks run separately; this is not native/real-Pulse acceptance.
manager = r'''#!/usr/bin/python3
-import os, pathlib, sys
+import os, pathlib, shutil, sys
root = pathlib.Path(os.environ["PULSE_NATIVE_ROOT"])
# Tool startup must have an existing owned home, not create the lab before
# NativeLab has admitted and claimed its scratch root (as on macOS).
@@ -450,6 +452,9 @@ if args[0] == "show":
elif args[0] in ("start", "stop"):
if args[0] == "start" and load != "loaded": sys.exit(1)
statefile.write_text("active" if args[0] == "start" else "inactive")
+ process_bytes = root / "mock-managed-executable"
+ if args[0] == "start": shutil.copyfile(root / "install/bin/pulse", process_bytes)
+ else: process_bytes.unlink(missing_ok=True)
if args[0] == "start" and not (root / "data/.encryption.key").exists():
(root / "data/.encryption.key").write_text("synthetic persistence marker, not a key\n")
elif args[0] == "mask": unit.symlink_to("/dev/null")
@@ -482,7 +487,11 @@ elif args[0] not in ("daemon-reload", "reset-failed"): sys.exit(97)
import json, os, pathlib, sys
with pathlib.Path({str(tool_trace)!r}).open('a') as receipt:
receipt.write(json.dumps({name!r}) + '\\n')
-os.execv({executable!r}, [{executable!r}, *sys.argv[1:]])
+arguments = sys.argv[1:]
+if {name!r} == 'cmp' and '/proc/123/exe' in arguments:
+ arguments = [str(pathlib.Path(os.environ['PULSE_NATIVE_ROOT']) / 'mock-managed-executable')
+ if arg == '/proc/123/exe' else arg for arg in arguments]
+os.execv({executable!r}, [{executable!r}, *arguments])
''')
tool.chmod(0o700)
path = tools / "systemctl"; path.write_text(manager); path.chmod(0o755)