Keep optional updater setup failures from claiming enablement

Check timer enable/start results and publish complete staged update preferences before starting the timer. Preserve saved configuration on write failure, report partial setup without claiming a running timer, and continue the existing monitoring restart path after optional updater errors. Exercise the real setup/main consumer for default and custom instances, direct and conditional callers, successful configuration and each failed phase.

Contract-Neutral: Restore the existing truthful installer completion, saved-preference preservation and optional-updater failure contracts; no change to timer consent, schedule, service identity or installation authority.
Change-source: pulse-maintainer
This commit is contained in:
pulse-triage[bot]
2026-11-09 11:10:11 +00:00
parent 08da324cb4
commit e76a03e8fa
3 changed files with 239 additions and 36 deletions

View File

@@ -5174,42 +5174,65 @@ setup_auto_updates() {
return 0
fi
# Enable timer but don't start it yet
safe_systemctl enable "$update_timer_unit" || true
# Update system.json to enable auto-updates
if [[ -f "$config_dir/system.json" ]]; then
# Update existing file
local temp_file="/tmp/system_$$.json"
if command -v jq &> /dev/null; then
jq --arg channel "$desired_channel" '.autoUpdateEnabled = true | .updateChannel = $channel' "$config_dir/system.json" > "$temp_file" && mv "$temp_file" "$config_dir/system.json"
else
# Fallback to sed if jq not available
# First check if autoUpdateEnabled already exists in the file
if grep -q '"autoUpdateEnabled"' "$config_dir/system.json"; then
# Field exists, update its value
sed -i 's/"autoUpdateEnabled":[^,}]*/"autoUpdateEnabled":true/' "$config_dir/system.json"
else
# Field doesn't exist, add it after the opening brace
sed -i 's/^{/{\"autoUpdateEnabled\":true,/' "$config_dir/system.json"
fi
if grep -q '"updateChannel"' "$config_dir/system.json"; then
sed -i "s/\"updateChannel\":[^,}]*/\"updateChannel\":\"$desired_channel\"/" "$config_dir/system.json"
else
sed -i "s/^{/{\"updateChannel\":\"$desired_channel\",/" "$config_dir/system.json"
fi
fi
else
# Create new file with auto-updates enabled
printf '{"autoUpdateEnabled":true,"updateChannel":"%s","pollingInterval":5}\n' "$desired_channel" > "$config_dir/system.json"
# Updater setup is optional: a failure must not prevent the main flow from
# restarting monitoring. But a failed command is not successful enablement.
if ! safe_systemctl enable "$update_timer_unit"; then
print_warn "Automatic update setup is incomplete: could not enable $update_timer_unit. Saved update preferences were not changed."
print_info "Inspect the timer before retrying: systemctl status $update_timer_unit"
ENABLE_AUTO_UPDATES=false
return 0
fi
chown pulse:pulse "$config_dir/system.json" 2>/dev/null || true
# Start the timer
safe_systemctl start "$update_timer_unit" || true
print_success "Automatic updates enabled (daily check between 02:00 and 06:00)"
# Stage the entire preference change beside the destination. A failed jq,
# sed or rename must preserve the old configuration, not start the timer
# against partially written preferences or report setup as complete.
local staged_config="" config_saved=false
if staged_config=$(mktemp "$config_dir/.system.json.XXXXXX"); then
if [[ -f "$config_dir/system.json" ]]; then
if command -v jq &> /dev/null; then
if jq --arg channel "$desired_channel" '.autoUpdateEnabled = true | .updateChannel = $channel' "$config_dir/system.json" > "$staged_config"; then
config_saved=true
fi
elif cp "$config_dir/system.json" "$staged_config"; then
# Keep the existing no-jq fallback, but apply both edits only
# to the staged copy and require each edit to succeed.
local enable_edit='s/^{/{"autoUpdateEnabled":true,/'
local channel_edit="s/^{/{\"updateChannel\":\"$desired_channel\",/"
if grep -q '"autoUpdateEnabled"' "$staged_config"; then
enable_edit='s/"autoUpdateEnabled":[^,}]*/"autoUpdateEnabled":true/'
fi
if grep -q '"updateChannel"' "$staged_config"; then
channel_edit="s/\"updateChannel\":[^,}]*/\"updateChannel\":\"$desired_channel\"/"
fi
if sed -i "$enable_edit" "$staged_config" && sed -i "$channel_edit" "$staged_config"; then
config_saved=true
fi
fi
elif printf '{"autoUpdateEnabled":true,"updateChannel":"%s","pollingInterval":5}\n' "$desired_channel" > "$staged_config"; then
config_saved=true
fi
fi
if [[ "$config_saved" != true ]] || ! mv "$staged_config" "$config_dir/system.json"; then
[[ -z "$staged_config" ]] || rm -f "$staged_config"
print_warn "Automatic update setup is incomplete: could not save update preferences. The previous configuration was preserved; the timer may already be enabled, but no start was requested."
print_info "Inspect the timer before retrying: systemctl status $update_timer_unit"
ENABLE_AUTO_UPDATES=false
return 0
fi
chown pulse:pulse "$config_dir/system.json" 2>/dev/null || true
if ! safe_systemctl start "$update_timer_unit"; then
print_warn "Automatic update setup is incomplete: preferences were saved, but $update_timer_unit could not be started."
print_info "Inspect the timer before retrying: systemctl status $update_timer_unit"
ENABLE_AUTO_UPDATES=false
return 0
fi
# Command success is not an observed running timer. The completion section
# separately reads its actual boot setting and active state.
print_success "Automatic update preferences saved; timer enable/start commands completed. Check the timer state in the completion summary."
}
# Updates and reinstalls only run setup_auto_updates when the user opts in,

View File

@@ -1,11 +1,16 @@
package installtests
import (
"context"
"encoding/json"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
"time"
)
// Run the real rewriter in the conditional context used by its installer
@@ -158,3 +163,178 @@ safe_systemctl() { echo UNEXPECTED_SYSTEMCTL; }
t.Errorf("failed containing caller left staging files: %v", entries)
}
}
// Execute the real setup and its real main consumer with bounded systemctl
// doubles and private saved configuration. Optional updater failure must not
// strand monitoring; failed configuration publication must preserve all bytes.
func TestRootAutoUpdateSetupCompletion(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix server installer fixture")
}
source := repoFile("install.sh")
if override := os.Getenv("PULSE_AUTO_UPDATE_SETUP_SOURCE"); override != "" {
source = override
}
content, err := os.ReadFile(source)
if err != nil {
t.Fatal(err)
}
extract := func(name string) string {
t.Helper()
pattern := regexp.MustCompile(`(?ms)^` + regexp.QuoteMeta(name) + `\(\) \{\n.*?^\}`)
body := pattern.Find(content)
if body == nil {
t.Fatalf("missing installer function %s", name)
}
return string(body)
}
for _, service := range []string{"pulse", "pulse-blue"} {
for _, fault := range []string{"none", "new", "no-jq", "no-jq-missing-fields", "assets", "enable", "enable-timeout", "allocation", "jq", "copy", "sed-first", "sed-second", "rename", "write", "start", "start-timeout"} {
for _, conditional := range []bool{false, true} {
caller := "main"
if conditional {
caller = "conditional-main"
}
t.Run(service+"/"+fault+"/"+caller, func(t *testing.T) {
dir := t.TempDir()
config := filepath.Join(dir, "system.json")
original := `{"autoUpdateEnabled":false,"updateChannel":"rc","pollingInterval":17,"marker":"preserved"}` + "\n"
if fault == "no-jq-missing-fields" {
original = `{"pollingInterval":17,"marker":"preserved"}` + "\n"
}
newConfig := fault == "new" || fault == "write"
if !newConfig {
if err := os.WriteFile(config, []byte(original), 0640); err != nil {
t.Fatal(err)
}
}
bin := filepath.Join(dir, "bin")
if err := os.Mkdir(bin, 0700); err != nil {
t.Fatal(err)
}
// timeout executes this ordinary child, never host systemctl.
if err := os.WriteFile(filepath.Join(bin, "systemctl"), []byte(`#!/bin/bash
printf '%s\n' "$*" >> "$FIXTURE/actions"
if [[ "$1" == enable && "$FAULT" == enable || "$1" == start && "$FAULT" == start ]]; then exit 17; fi
if [[ "$1" == enable && "$FAULT" == enable-timeout || "$1" == start && "$FAULT" == start-timeout ]]; then exit 124; fi
`), 0700); err != nil {
t.Fatal(err)
}
body := `set -euo pipefail
SERVICE_NAME="$FIXTURE_SERVICE"
SERVICE_NAME_EXPLICIT=true
DEFAULT_SERVICE_NAME=pulse
CONFIG_DIR="$FIXTURE"
UPDATE_TIMER_UNIT="${SERVICE_NAME}-update.timer"
UPDATE_TIMER_PATH="$FIXTURE/${UPDATE_TIMER_UNIT}"
IN_CONTAINER=true
BUILD_FROM_SOURCE=false
FORCE_VERSION=v6.6.0
ENABLE_AUTO_UPDATES=true
print_info() { printf 'INFO %s\n' "$*"; }
print_warn() { printf 'WARN %s\n' "$*"; }
print_success() { printf 'SUCCESS %s\n' "$*"; }
for fn in print_header check_root detect_os check_docker_environment offer_existing_auto_updates run_upgrade_readiness_preflight backup_existing create_user download_pulse setup_directories setup_update_command ensure_systemd_service_installed create_marker_file; do
eval "$fn() { :; }"
done
check_existing_installation() { CURRENT_VERSION=v6.5.0; return 0; }
compare_versions() { return 1; }
detect_service_name() { printf '%s\n' "$SERVICE_NAME"; }
selected_update_channel() { echo stable; }
install_auto_update_assets() {
printf 'assets\n' >> "$FIXTURE/actions"
[[ "$FAULT" != assets ]]
}
start_pulse() { printf 'monitoring-start\n' >> "$FIXTURE/actions"; }
print_completion() { printf 'INSTALL_COMPLETED flag=%s\n' "$ENABLE_AUTO_UPDATES"; }
chown() { :; }
command() {
if [[ "$1" == -v && "$2" == jq ]]; then
case "$FAULT" in no-jq|no-jq-missing-fields|copy|sed-first|sed-second) return 1 ;; esac
fi
builtin command "$@"
}
jq() {
[[ "$FAULT" != jq ]] || return 17
python3 - "$@" <<'PYJSON'
import json,sys
with open(sys.argv[-1]) as f: value=json.load(f)
value.update(autoUpdateEnabled=True,updateChannel=sys.argv[3])
print(json.dumps(value))
PYJSON
}
mktemp() { [[ "$FAULT" != allocation ]] || return 17; command mktemp "$@"; }
cp() { [[ "$FAULT" != copy ]] || return 17; command cp "$@"; }
SED_CALLS=0
sed() {
SED_CALLS=$((SED_CALLS + 1))
if [[ "$FAULT" == sed-first && "$SED_CALLS" == 1 || "$FAULT" == sed-second && "$SED_CALLS" == 2 ]]; then return 17; fi
command sed "$@"
}
mv() { [[ "$FAULT" != rename ]] || return 17; command mv "$@"; }
printf() {
if [[ "$FAULT" == write && "$1" == '{"autoUpdateEnabled":true'* ]]; then return 17; fi
builtin printf "$@"
}
` + extract("safe_systemctl") + "\n" + extract("setup_auto_updates") + "\n" + extract("main") + "\n"
if conditional {
body += "if main; then :; else exit 81; fi\n"
} else {
body += "main\n"
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "bash", "-c", body)
cmd.Env = append(os.Environ(), "FIXTURE="+dir, "FIXTURE_SERVICE="+service, "FAULT="+fault, "PATH="+bin+string(os.PathListSeparator)+os.Getenv("PATH"))
out, runErr := cmd.CombinedOutput()
if runErr != nil || ctx.Err() != nil || !strings.Contains(string(out), "INSTALL_COMPLETED") {
t.Fatalf("optional updater setup prevented monitoring completion: %v, %v\n%s", runErr, ctx.Err(), out)
}
calls, err := os.ReadFile(filepath.Join(dir, "actions"))
if err != nil {
t.Fatal(err)
}
wantCalls := "assets\n"
if fault != "assets" {
wantCalls += "enable " + service + "-update.timer\n"
}
saved := fault == "none" || fault == "new" || fault == "no-jq" || fault == "no-jq-missing-fields" || fault == "start" || fault == "start-timeout"
complete := saved && fault != "start" && fault != "start-timeout"
if saved {
wantCalls += "start " + service + "-update.timer\n"
}
wantCalls += "monitoring-start\n"
if string(calls) != wantCalls {
t.Fatalf("wrong or repeated timer/monitoring operations: got %q, want %q\n%s", calls, wantCalls, out)
}
if strings.Contains(string(out), "Automatic updates enabled") || strings.Contains(string(out), "timer enable/start commands completed") != complete || strings.Contains(string(out), "flag=true") != complete {
t.Fatalf("unconfirmed timer success or missing partial-setup result:\n%s", out)
}
if !complete && fault != "assets" && (!strings.Contains(string(out), "setup is incomplete") || !strings.Contains(string(out), "systemctl status "+service+"-update.timer")) {
t.Fatalf("missing instance-scoped partial-setup inspection guidance:\n%s", out)
}
after, readErr := os.ReadFile(config)
if saved {
var value map[string]any
if readErr != nil || json.Unmarshal(after, &value) != nil || value["autoUpdateEnabled"] != true || value["updateChannel"] != "stable" {
t.Fatalf("preferences not completely persisted: %v %s", readErr, after)
}
if !newConfig && (value["marker"] != "preserved" || value["pollingInterval"] != float64(17)) {
t.Fatalf("unrelated saved configuration changed: %s", after)
}
} else if newConfig {
if !os.IsNotExist(readErr) {
t.Fatalf("failed setup published new preferences: %v %s", readErr, after)
}
} else if readErr != nil || string(after) != original {
t.Fatalf("failed setup changed saved configuration: %v %s", readErr, after)
}
staged, err := filepath.Glob(filepath.Join(dir, ".system.json.*"))
if err != nil || len(staged) != 0 {
t.Fatalf("setup left owned staging files: %v %v", err, staged)
}
})
}
}
}
}

View File

@@ -1035,8 +1035,8 @@ func TestRootInstallScriptSupportsInstanceScopedServerInstalls(t *testing.T) {
`if [[ "$SERVICE_NAME_EXPLICIT" == "true" ]]; then`,
`install_binary_symlink "$INSTALL_DIR/bin/pulse" "$BINARY_LINK_PATH"`,
`ln -sf "$target" "$link_path"`,
`safe_systemctl enable "$update_timer_unit" || true`,
`safe_systemctl start "$update_timer_unit" || true`,
`if ! safe_systemctl enable "$update_timer_unit"; then`,
`if ! safe_systemctl start "$update_timer_unit"; then`,
`Environment="PULSE_SERVICE_NAME=$service_name"`,
`Environment="PULSE_INSTALL_DIR=$install_dir"`,
`Environment="PULSE_CONFIG_DIR=$config_dir"`,