ソースを参照

fix(reinstall): finish the setup and start the agent even when a step fails (#1855) (#1856)

Nacho 1 ヶ月 前
親
コミット
4a897cca7f

+ 1 - 0
CHANGELOG.md

@@ -42,6 +42,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- A reinstall that cannot finish its setup now says so and still brings the agent back. After the binary was swapped the service was still stopped, and any failing step of the remaining setup (writing the environment file, installing the init script, clearing the old watchdog, enabling the service) aborted the script with `set -e`, leaving the new binary installed and nothing running. Those steps now report on stderr and carry on, the environment file and the init script are written to a temporary file and moved into place so a failure cannot truncate the one in use, and the restart is attempted even when a step fails, exiting with a distinct code if the agent does not come up (#1855).
 - A reinstall that fails no longer leaves the agent down. The installer stopped the service before it had anything to install, so a download that could not reach the server or a binary whose digest did not match exited with the previous agent already stopped and nothing to start it again. The download and the digest check now happen first, the service stops only to swap the binary, and a failed swap restarts the previous agent and says so. The three diagnostics that still went to stdout (unknown architecture, endianness, digest mismatch) now go to stderr, which is what the server reads to explain a failed reinstall (#1853).
 - A reinstall that cannot download the agent binary or install the package now says so on stderr, instead of dying silently on the first failing command (#1737).
 - An SSH reinstall that fails now reports the last line the router printed on stderr, not just "Process exited with status 1", so the reason (a failing curl, a full filesystem, a missing command) reaches the operator (#1737).

+ 38 - 13
server-go/internal/reinstall/reinstall.go

@@ -123,14 +123,20 @@ chmod 644 ` + caPath + `
 // beacons (#1557); la vista de canales pide el scan bajo demanda (#1561). Un
 // valor que ya esté en el env gana, para no pisar un override manual (#851).
 func envRewriteBlock(targets WanTargets) string {
-	return `USER_VARS=""
+	return `# #1853: escribir la config no puede abortar el reinstall. El env se
+# compone en un temporal y solo se pone en su sitio si salio entero, asi que un
+# /etc lleno o de solo lectura conserva el anterior en vez de dejarlo a medias.
+warn() { echo "netpulse-agent: $*" >&2; }
+USER_VARS=""
 SCAN_VALUE="0"
 if [ -f "$ENV_FILE" ]; then
 	prev_scan=$(grep -E '^NETPULSE_SCAN_INTERVAL=' "$ENV_FILE" | tail -n 1) || prev_scan=""
 	if [ -n "$prev_scan" ]; then SCAN_VALUE=${prev_scan#NETPULSE_SCAN_INTERVAL=}; fi
 	USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE" | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|WAN_TARGET|GW_TARGET|SCAN_INTERVAL)=') || true
 fi
-cat > "$ENV_FILE" <<EOF
+ENV_TMP="$ENV_FILE.new.$$"
+write_env() {
+	cat > "$ENV_TMP" <<EOF
 # netpulse-agent — config (generado por reinstall)
 NETPULSE_SERVER=$SERVER
 NETPULSE_SLUG=$SLUG
@@ -156,12 +162,18 @@ EOF
 # #851: con server https el agente exige el SPKI pin; vacío = http plano o
 # el server no pudo derivarlo (se comporta como antes).
 if [ -n "$SERVER_FP" ]; then
-	echo "NETPULSE_SERVER_FP=$SERVER_FP" >> "$ENV_FILE"
+	echo "NETPULSE_SERVER_FP=$SERVER_FP" >> "$ENV_TMP" || return 1
 fi
 if [ -n "$USER_VARS" ]; then
-	printf '%s\n' "$USER_VARS" >> "$ENV_FILE"
+	printf '%s\n' "$USER_VARS" >> "$ENV_TMP" || return 1
+fi
+chmod 600 "$ENV_TMP" || return 1
+mv -f "$ENV_TMP" "$ENV_FILE" || return 1
+}
+if ! write_env; then
+	rm -f "$ENV_TMP"
+	warn "no pude escribir $ENV_FILE; se queda el anterior"
 fi
-chmod 600 "$ENV_FILE"
 `
 }
 
@@ -221,8 +233,8 @@ fi
 const preserveOnSysupgrade = `
 # Preservar el agente en sysupgrade (#1476): mismo gesto que el flujo owut.
 P=/etc/sysupgrade.conf
-touch "$P"
-ensure_sysupgrade() { grep -qxF "$1" "$P" 2>/dev/null || echo "$1" >> "$P"; }
+touch "$P" 2>/dev/null || true
+ensure_sysupgrade() { grep -qxF "$1" "$P" 2>/dev/null || echo "$1" >> "$P" 2>/dev/null || true; }
 ensure_sysupgrade /usr/sbin/netpulse-agent
 ensure_sysupgrade /etc/netpulse-agent.env
 ensure_sysupgrade /etc/init.d/netpulse-agent
@@ -386,7 +398,10 @@ if [ "$PKG_OK" != "1" ]; then
 # sueltos, así que el binario, el init y el env se añaden a
 # /etc/sysupgrade.conf (#1476); si aun así falta el binario al arrancar se
 # descarga del server con este env.
-cat > "$INIT" <<'INITEOF'
+INIT_TMP="/tmp/netpulse-agent.init.$$"
+# #1853: el init se escribe en un temporal y se mueve solo si salio entero, para
+# no dejar /etc/init.d a medias si el disco esta lleno.
+if cat > "$INIT_TMP" <<'INITEOF'
 #!/bin/sh /etc/rc.common
 # netpulse-agent — agente nativo NetPulse para OpenWrt, con self-heal.
 # Config en /etc/netpulse-agent.env (chmod 600); procd reinicia si cambia.
@@ -480,20 +495,30 @@ selfheal_binary() {
 	procd_close_instance
 }
 INITEOF
-chmod 0755 "$INIT"
+then
+	chmod 0755 "$INIT_TMP" && mv -f "$INIT_TMP" "$INIT" || { rm -f "$INIT_TMP"; warn "no pude instalar $INIT"; }
+else
+	rm -f "$INIT_TMP"
+	warn "no pude preparar $INIT"
+fi
 fi
 
 # #851: el watchdog cron YA NO se instala (un reinicio a ciegas de un crash
 # loop no arregla nada y ensucia el log; la detección es el dead-man del
 # servidor). Si el router viene de una instalación que sí lo tenía, limpiarlo.
-rm -f /usr/sbin/netpulse-watchdog
+rm -f /usr/sbin/netpulse-watchdog || warn "no pude borrar /usr/sbin/netpulse-watchdog"
 if [ -f /etc/crontabs/root ]; then
-	sed -i '/netpulse-watchdog/d' /etc/crontabs/root
+	sed -i '/netpulse-watchdog/d' /etc/crontabs/root || warn "no pude limpiar el cron del watchdog"
 fi
 
-"$INIT" enable
+# #1853: de aqui al final nada puede abortar en silencio: el binario nuevo ya
+# esta en su sitio y el servicio sigue parado, asi que se avisa y se arranca.
+"$INIT" enable >/dev/null 2>&1 || warn "no pude habilitar $INIT"
 ` + preserveOnSysupgrade + `
-"$INIT" restart
+if ! "$INIT" restart >/dev/null 2>&1; then
+	warn "el agente no arranco tras el reinstall; revisa $INIT"
+	exit 24
+fi
 `
 }
 

+ 5 - 4
server-go/internal/reinstall/scan_default_test.go

@@ -18,15 +18,16 @@ import (
 func envBlockForTest(t *testing.T) string {
 	t.Helper()
 	s := scriptForTest()
-	start := strings.Index(s, `USER_VARS=""`)
+	start := strings.Index(s, `warn() { echo "netpulse-agent: $*" >&2; }`)
 	if start < 0 {
 		t.Fatal("no encuentro el bloque de env en el script")
 	}
-	end := strings.Index(s[start:], `chmod 600 "$ENV_FILE"`)
+	marker := "warn \"no pude escribir $ENV_FILE; se queda el anterior\"\nfi"
+	end := strings.Index(s[start:], marker)
 	if end < 0 {
-		t.Fatal("el bloque de env no termina con chmod")
+		t.Fatal("el bloque de env no termina con el guard de write_env")
 	}
-	return s[start : start+end+len(`chmod 600 "$ENV_FILE"`)]
+	return s[start : start+end+len(marker)]
 }
 
 func runEnvBlock(t *testing.T, prev string) string {

+ 11 - 9
server-go/internal/reinstall/script_test.go

@@ -36,7 +36,7 @@ func TestScriptConfig(t *testing.T) {
 		`NETPULSE_SERVER=$SERVER`,
 		`NETPULSE_SLUG=$SLUG`,
 		`NETPULSE_TOKEN=$TOKEN`,
-		"chmod 600 \"$ENV_FILE\"",
+		"chmod 600 \"$ENV_TMP\"",
 	} {
 		if !strings.Contains(s, want) {
 			t.Errorf("script sin %q", want)
@@ -95,7 +95,7 @@ func TestScriptPreservesUserVars(t *testing.T) {
 	for _, want := range []string{
 		`USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE"`,
 		`grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|WAN_TARGET|GW_TARGET|SCAN_INTERVAL)='`,
-		`printf '%s\n' "$USER_VARS" >> "$ENV_FILE"`,
+		`printf '%s\n' "$USER_VARS" >> "$ENV_TMP"`,
 	} {
 		if !strings.Contains(s, want) {
 			t.Errorf("script sin preservación de vars de usuario: falta %q", want)
@@ -204,11 +204,13 @@ func TestScriptFinishesWithStart(t *testing.T) {
 	s := scriptForTest()
 	// #1476: entre enable y restart va la preservación en sysupgrade.conf, así
 	// que el final ya no es la pareja literal; lo que importa es que el último
-	// gesto sea arrancar el servicio y que el enable vaya antes.
-	if !strings.HasSuffix(strings.TrimSpace(s), "\"$INIT\" restart") {
-		t.Error("el script debe terminar con el restart del servicio")
+	// gesto sea arrancar el servicio y que el enable vaya antes. #1855: el
+	// restart va dentro de un guard que avisa y sale 24 si el agente no arranca.
+	restart := strings.LastIndex(s, `"$INIT" restart`)
+	if restart < 0 || !strings.Contains(s[restart:], "exit 24") {
+		t.Error("el script debe terminar arrancando el servicio y avisar si no arranca")
 	}
-	if strings.Index(s, `"$INIT" enable`) > strings.LastIndex(s, `"$INIT" restart`) {
+	if strings.Index(s, `"$INIT" enable`) > restart {
 		t.Error("el script debe habilitar el servicio antes de reiniciarlo")
 	}
 }
@@ -312,7 +314,7 @@ func TestScriptIncludesServerFP(t *testing.T) {
 	for _, want := range []string{
 		`SERVER="https://np.example.org:3443"`,
 		`SERVER_FP="` + fp + `"`,
-		`echo "NETPULSE_SERVER_FP=$SERVER_FP" >> "$ENV_FILE"`,
+		`echo "NETPULSE_SERVER_FP=$SERVER_FP" >> "$ENV_TMP"`,
 	} {
 		if !strings.Contains(s, want) {
 			t.Errorf("script con FP sin %q", want)
@@ -411,7 +413,7 @@ func TestEnvScriptIsLightweight(t *testing.T) {
 		`SERVER="http://192.168.1.226:3000"`,
 		"NETPULSE_SERVER=$SERVER",
 		"NETPULSE_TOKEN=$TOKEN",
-		`chmod 600 "$ENV_FILE"`,
+		`chmod 600 "$ENV_TMP"`,
 		// conserva las NETPULSE_* del usuario (#851)
 		`USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+='`,
 		// restart para que el agente relea el env
@@ -469,7 +471,7 @@ func TestScriptPreservesOnSysupgrade(t *testing.T) {
 	s := scriptForTest()
 	for _, want := range []string{
 		"P=/etc/sysupgrade.conf",
-		`ensure_sysupgrade() { grep -qxF "$1" "$P" 2>/dev/null || echo "$1" >> "$P"; }`,
+		`ensure_sysupgrade() { grep -qxF "$1" "$P" 2>/dev/null || echo "$1" >> "$P" 2>/dev/null || true; }`,
 		"ensure_sysupgrade /usr/sbin/netpulse-agent",
 		"ensure_sysupgrade /etc/netpulse-agent.env",
 		"ensure_sysupgrade /etc/init.d/netpulse-agent",

+ 48 - 0
server-go/internal/reinstall/tail_1855_test.go

@@ -0,0 +1,48 @@
+package reinstall_test
+
+import (
+	"os/exec"
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
+)
+
+// #1855: despues del swap el binario nuevo ya esta instalado y el servicio
+// sigue parado, asi que ningun paso de configuracion puede abortar el script:
+// cada uno avisa por stderr y el restart del final se ejecuta igualmente.
+func TestScriptSurvivesAFailedConfigStep(t *testing.T) {
+	token := strings.Repeat("a1", 32)
+	s := reinstall.ScriptWithTargets(
+		"test-router", token, "https://192.168.1.226:3000", "sha256//AAAA",
+		map[string]string{"arm64": "cafebabe"},
+		reinstall.WanTargets{},
+	)
+
+	for _, want := range []string{
+		`ENV_TMP="$ENV_FILE.new.$$"`,
+		`mv -f "$ENV_TMP" "$ENV_FILE" || return 1`,
+		`warn "no pude escribir $ENV_FILE; se queda el anterior"`,
+		`INIT_TMP="/tmp/netpulse-agent.init.$$"`,
+		`warn "no pude instalar $INIT"`,
+		`rm -f /usr/sbin/netpulse-watchdog || warn`,
+		`"$INIT" enable >/dev/null 2>&1 || warn "no pude habilitar $INIT"`,
+		`if ! "$INIT" restart >/dev/null 2>&1; then`,
+		`exit 24`,
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("el script no contiene %q", want)
+		}
+	}
+
+	swap := strings.Index(s, `mv -f /tmp/netpulse-agent.new "$BIN"`)
+	enable := strings.Index(s, `"$INIT" enable`)
+	restart := strings.Index(s, `if ! "$INIT" restart`)
+	if swap < 0 || enable < 0 || restart < 0 || !(swap < enable && enable < restart) {
+		t.Fatalf("orden inesperado: swap=%d enable=%d restart=%d", swap, enable, restart)
+	}
+
+	if err := exec.Command("sh", "-n", "-c", s).Run(); err != nil {
+		t.Fatalf("script invalido: %v", err)
+	}
+}