Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 150 additions & 3 deletions scripts/prepare-dgx-station-host.sh
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ DOCKER_CONTAINER_BASELINE=""
DOCKER_CONTAINER_BASELINE_TOTAL=0
DOCKER_QUERY_OUTPUT=""
DOCKER_QUERY_USES_SUDO=0
readonly PACKAGEKIT_UNIT="packagekit.service"
PACKAGEKIT_RUNTIME_MASK_OWNED=0
PACKAGEKIT_WAS_ACTIVE=0

readonly -a PACKAGE_SPECS=(
"dkms=${TARGET_DKMS_VERSION}"
Expand Down Expand Up @@ -825,8 +828,14 @@ package_manager_lock_inventory() {
}

check_package_managers_idle() {
local phase=${1:-Station preflight} active locks
active="$(ps -eo pid=,comm= | awk '$2 ~ /^(apt|apt-get|apt.systemd.dai|apt.systemd.daily|dpkg|packagekitd|unattended-upgr|unattended-upgrade)$/ {print}')"
local phase=${1:-Station preflight} active locks process_pattern
process_pattern='^(apt|apt-get|apt.systemd.dai|apt.systemd.daily|dpkg|unattended-upgr|unattended-upgrade)$'
# Ubuntu keeps packagekitd resident after APT refreshes. Generic apply mode
# quiesces it separately before the repository/package critical section.
if [[ "$STATION_HOST_PROFILE" != "generic-ubuntu" ]]; then
process_pattern='^(apt|apt-get|apt.systemd.dai|apt.systemd.daily|dpkg|packagekitd|unattended-upgr|unattended-upgrade)$'
fi
active="$(ps -eo pid=,comm= | awk -v pattern="$process_pattern" '$2 ~ pattern {print}')"
[[ -z "$active" ]] || fatal "A package-manager process is active during ${phase}: ${active}"
if [[ "$STATION_HOST_PROFILE" == "generic-ubuntu" ]]; then
locks="$(package_manager_lock_inventory)" \
Expand All @@ -836,6 +845,128 @@ check_package_managers_idle() {
info "package_manager=idle phase=${phase// /_}"
}

packagekit_unit_property() {
local property=$1
systemctl show "$PACKAGEKIT_UNIT" -p "$property" --value 2>/dev/null
}

restore_packagekit_after_transaction() {
local active_state restored=0
if ((PACKAGEKIT_RUNTIME_MASK_OWNED == 1)); then
if ! sudo systemctl unmask --runtime "$PACKAGEKIT_UNIT"; then
warn "Could not remove NemoClaw's runtime-only PackageKit mask"
return 1
fi
PACKAGEKIT_RUNTIME_MASK_OWNED=0
restored=1
fi

if ((PACKAGEKIT_WAS_ACTIVE == 1)); then
active_state="$(packagekit_unit_property ActiveState)" || {
warn "Could not inspect PackageKit while restoring its prior runtime state"
return 1
}
if [[ "$active_state" != "active" ]]; then
if ! sudo systemctl start "$PACKAGEKIT_UNIT"; then
warn "Could not restore the previously active PackageKit service"
return 1
fi
fi
PACKAGEKIT_WAS_ACTIVE=0
restored=1
fi
((restored == 0)) || info "packagekit=runtime_state_restored"
}

quiesce_packagekit_for_transaction() {
local load_state unit_file_state active_state transaction_output transaction_type transaction_count transaction_paths
local attempt

[[ "$STATION_HOST_PROFILE" == "generic-ubuntu" && "$MODE" == "--apply" ]] || return 0
((PACKAGEKIT_RUNTIME_MASK_OWNED == 0)) || fatal "PackageKit is already under NemoClaw transaction control"

load_state="$(packagekit_unit_property LoadState)" \
|| fatal "Unable to inspect the PackageKit service before Station package preparation"
if [[ "$load_state" == "not-found" ]]; then
info "packagekit=not_installed"
return 0
fi
[[ "$load_state" == "loaded" ]] \
|| fatal "PackageKit service has an unexpected load state: ${load_state}"

unit_file_state="$(packagekit_unit_property UnitFileState)" \
|| fatal "Unable to inspect the PackageKit unit-file state"
active_state="$(packagekit_unit_property ActiveState)" \
|| fatal "Unable to inspect the PackageKit runtime state"
case "$unit_file_state" in
masked | masked-runtime)
[[ "$active_state" == "inactive" ]] \
|| fatal "PackageKit is ${active_state} despite its ${unit_file_state} unit state"
info "packagekit=already_quiesced state=${unit_file_state}"
return 0
;;
esac

# A runtime-only mask prevents D-Bus from reactivating PackageKit after its
# idle daemon exits. It does not stop or cancel an existing transaction.
PACKAGEKIT_RUNTIME_MASK_OWNED=1
sudo systemctl mask --runtime "$PACKAGEKIT_UNIT" \
|| fatal "Could not establish the runtime-only PackageKit exclusion boundary"
unit_file_state="$(packagekit_unit_property UnitFileState)" \
|| fatal "Unable to verify the runtime-only PackageKit mask"
[[ "$unit_file_state" == "masked-runtime" ]] \
|| fatal "PackageKit runtime mask did not take effect: ${unit_file_state}"

active_state="$(packagekit_unit_property ActiveState)" \
|| fatal "Unable to inspect PackageKit after establishing its runtime mask"
case "$active_state" in
inactive) ;;
active)
PACKAGEKIT_WAS_ACTIVE=1
require_command busctl
if ! transaction_output="$(busctl --system call \
org.freedesktop.PackageKit /org/freedesktop/PackageKit \
org.freedesktop.PackageKit GetTransactionList 2>/dev/null)"; then
active_state="$(packagekit_unit_property ActiveState)" \
|| fatal "Unable to inspect PackageKit after its transaction query failed"
[[ "$active_state" == "inactive" ]] \
|| fatal "Unable to query active PackageKit transactions"
else
read -r transaction_type transaction_count transaction_paths <<<"$transaction_output"
[[ "$transaction_type" == "ao" && "$transaction_count" =~ ^[0-9]+$ ]] \
|| fatal "PackageKit returned malformed transaction state: ${transaction_output}"
((transaction_count == 0)) \
|| fatal "An active PackageKit transaction blocks Station package preparation: ${transaction_output}"
[[ -z "$transaction_paths" ]] \
|| fatal "PackageKit returned inconsistent empty transaction state: ${transaction_output}"

if ! busctl --system call \
org.freedesktop.PackageKit /org/freedesktop/PackageKit \
org.freedesktop.PackageKit SuggestDaemonQuit >/dev/null 2>&1; then
active_state="$(packagekit_unit_property ActiveState)" \
|| fatal "Unable to inspect PackageKit after its idle-quit request failed"
[[ "$active_state" == "inactive" ]] \
|| fatal "Could not ask the idle PackageKit daemon to exit"
fi
fi

for ((attempt = 0; attempt < 50; attempt++)); do
active_state="$(packagekit_unit_property ActiveState)" \
|| fatal "Unable to verify PackageKit quiescence"
[[ "$active_state" != "inactive" ]] || break
[[ "$active_state" == "active" || "$active_state" == "deactivating" ]] \
|| fatal "PackageKit entered an unexpected state while quiescing: ${active_state}"
sleep 0.1
done
[[ "$active_state" == "inactive" ]] \
|| fatal "PackageKit did not become inactive before the Station package critical section"
;;
*) fatal "PackageKit is not in a safe state for Station package preparation: ${active_state}" ;;
esac

info "packagekit=quiesced scope=station_package_transaction mask=runtime_only"
}

assert_package_transaction_ready() {
local phase=$1
check_package_managers_idle "$phase"
Expand Down Expand Up @@ -1544,6 +1675,19 @@ cleanup_apt_transaction_guard() {
|| warn "could not remove APT transaction guard directory: ${guard_dir}"
}

cleanup_station_prepare() {
local rc=$?
trap - EXIT
cleanup_apt_transaction_guard || true
if ! restore_packagekit_after_transaction; then
warn "PackageKit runtime state requires manual verification after interrupted Station preparation"
if ((rc == 0)); then
rc=1
fi
fi
exit "$rc"
}

create_apt_transaction_guard() {
local spec state name expected allowed_old native_arch targets="" hook_path targets_path
native_arch="$(sudo dpkg --print-architecture)"
Expand Down Expand Up @@ -1655,6 +1799,7 @@ simulate_install() {
}

install_packages() {
quiesce_packagekit_for_transaction
assert_package_transaction_ready "Station repository configuration"
configure_repositories
assert_package_transaction_ready "APT metadata refresh"
Expand All @@ -1680,6 +1825,8 @@ install_packages() {
for spec in "${PACKAGE_SPECS[@]}"; do
package_is_exact "$spec" || fatal "Installed package does not match ${spec}"
done
restore_packagekit_after_transaction \
|| fatal "Could not restore PackageKit after Station package preparation"
info "pinned_packages=installed"
}

Expand Down Expand Up @@ -2226,7 +2373,7 @@ main() {
info "version=${SCRIPT_VERSION} mode=${MODE} log=disabled_read_only"
fi
trap 'on_error "$LINENO"' ERR
trap 'cleanup_apt_transaction_guard' EXIT
trap 'cleanup_station_prepare' EXIT
case "$MODE" in
--check) run_check ;;
--apply) run_apply ;;
Expand Down
155 changes: 154 additions & 1 deletion test/install-station-package-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,52 @@ run_apply
`);
}

function runPackageKitBoundary(body: string, extraEnv: Record<string, string> = {}) {
return runSourced(
`
CALLS="$HOME/packagekit-calls"
: >"$CALLS"
systemctl() {
printf 'systemctl %s\n' "$*" >>"$CALLS"
case "$*" in
'show packagekit.service -p LoadState --value') printf 'loaded\n' ;;
'show packagekit.service -p UnitFileState --value')
if [[ -e "$HOME/packagekit-mask" ]]; then printf 'masked-runtime\n'; else printf 'static\n'; fi
;;
'show packagekit.service -p ActiveState --value')
if [[ -e "$HOME/packagekit-inactive" ]]; then printf 'inactive\n'; else printf 'active\n'; fi
;;
'mask --runtime packagekit.service') : >"$HOME/packagekit-mask" ;;
'unmask --runtime packagekit.service') rm -f "$HOME/packagekit-mask" ;;
'start packagekit.service') rm -f "$HOME/packagekit-inactive" ;;
*) return 1 ;;
esac
}
busctl() {
printf 'busctl %s\n' "$*" >>"$CALLS"
case "$*" in
*GetTransactionList) printf '%s\n' "$PACKAGEKIT_TRANSACTIONS" ;;
*SuggestDaemonQuit)
[[ "$PACKAGEKIT_QUIT_RESULT" == 'inactive' ]] && : >"$HOME/packagekit-inactive"
return 0
;;
*) return 1 ;;
esac
}
sudo() { if [[ "$1" == '-n' ]]; then shift; fi; "$@"; }
sleep() { :; }
STATION_HOST_PROFILE=generic-ubuntu
MODE='--apply'
${body}
`,
{
PACKAGEKIT_TRANSACTIONS: "ao 0",
PACKAGEKIT_QUIT_RESULT: "inactive",
...extraEnv,
},
);
}

describe("DGX Station package state", () => {
it.each([
{ label: "missing", queryStatus: "1", record: "", expected: "missing" },
Expand Down Expand Up @@ -185,7 +231,6 @@ assert_no_package_mismatches

it.each([
"unattended-upgr",
"packagekitd",
"apt.systemd.dai",
])("detects the Linux package-manager process name %s", (processName) => {
const { result, output } = runSourced(
Expand All @@ -203,6 +248,114 @@ check_package_managers_idle test
expect(output).toMatch(/package-manager process is active/);
});

it("allows an idle PackageKit daemon on generic Ubuntu", () => {
const { result, output } = runSourced(
`
STATION_HOST_PROFILE=generic-ubuntu
ps() { printf '4242 packagekitd\n'; }
lslocks() { :; }
check_package_managers_idle test
`,
);

expect(result.status, output).toBe(0);
expect(output).toContain("package_manager=idle phase=test");
});

it("holds an idle PackageKit daemon outside the complete package critical section", () => {
const { result, output } = runPackageKitBoundary(`
quiesce_packagekit_for_transaction
printf 'CRITICAL_SECTION\n' >>"$CALLS"
restore_packagekit_after_transaction
cat "$CALLS"
[[ ! -e "$HOME/packagekit-mask" ]]
[[ ! -e "$HOME/packagekit-inactive" ]]
`);

expect(result.status, output).toBe(0);
expect(output).toContain(
"packagekit=quiesced scope=station_package_transaction mask=runtime_only",
);
expect(output).toContain("packagekit=runtime_state_restored");
const mask = output.indexOf("systemctl mask --runtime packagekit.service");
const inspect = output.indexOf("GetTransactionList");
const quit = output.indexOf("SuggestDaemonQuit");
const critical = output.indexOf("CRITICAL_SECTION");
const unmask = output.indexOf("systemctl unmask --runtime packagekit.service");
const restart = output.indexOf("systemctl start packagekit.service");
expect(mask).toBeGreaterThanOrEqual(0);
expect(inspect).toBeGreaterThan(mask);
expect(quit).toBeGreaterThan(inspect);
expect(critical).toBeGreaterThan(quit);
expect(unmask).toBeGreaterThan(critical);
expect(restart).toBeGreaterThan(unmask);
});

it("rejects an active lock-free PackageKit transaction before package mutation", () => {
const { result, output } = runPackageKitBoundary(
`
trap 'restore_packagekit_after_transaction || true; cat "$CALLS"' EXIT
quiesce_packagekit_for_transaction
printf 'PACKAGE_MUTATION\n' >>"$CALLS"
`,
{ PACKAGEKIT_TRANSACTIONS: 'ao 1 "/42_deadbeef"' },
);

expect(result.status, output).not.toBe(0);
expect(output).toMatch(/active PackageKit transaction blocks Station package preparation/);
expect(output).toContain("GetTransactionList");
expect(output).toContain("systemctl unmask --runtime packagekit.service");
expect(output).not.toContain("SuggestDaemonQuit");
expect(output).not.toContain("PACKAGE_MUTATION");
});

it("rejects PackageKit activity that appears after the initial idle inspection", () => {
const { result, output } = runPackageKitBoundary(
`
ps() { printf '4242 packagekitd\n'; }
lslocks() { :; }
check_package_managers_idle 'initial Station package preflight'
trap 'restore_packagekit_after_transaction || true; cat "$CALLS"' EXIT
quiesce_packagekit_for_transaction
printf 'PACKAGE_MUTATION\n' >>"$CALLS"
`,
{ PACKAGEKIT_QUIT_RESULT: "active" },
);

expect(result.status, output).not.toBe(0);
expect(output).toContain("package_manager=idle phase=initial_Station_package_preflight");
expect(output).toMatch(/did not become inactive before the Station package critical section/);
expect(output).toContain("systemctl unmask --runtime packagekit.service");
expect(output).not.toContain("PACKAGE_MUTATION");
});

it("rejects PackageKit when it holds an APT lock", () => {
const { result, output } = runSourced(`
STATION_HOST_PROFILE=generic-ubuntu
MODE='--apply'
ps() { printf '4242 packagekitd\n'; }
lslocks() { printf '4242 packagekitd /var/lib/apt/lists/lock\n'; }
sudo() { if [[ "$1" == "-n" ]]; then shift; fi; "$@"; }
check_package_managers_idle test
`);

expect(result.status, output).not.toBe(0);
expect(output).toContain("4242 packagekitd /var/lib/apt/lists/lock");
expect(output).toMatch(/APT or dpkg lock is active/);
});

it("keeps PackageKit process detection fail-closed outside generic Ubuntu", () => {
const { result, output } = runSourced(`
STATION_HOST_PROFILE=colossus-baseos
ps() { printf '4242 packagekitd\n'; }
check_package_managers_idle test
`);

expect(result.status, output).not.toBe(0);
expect(output).toContain("4242 packagekitd");
expect(output).toMatch(/package-manager process is active/);
});

it.each([
"/var/lib/dpkg/lock-frontend",
"/var/lib/dpkg/lock",
Expand Down