Ver Fonte

fix(reinstall): do not start the agent when the self-heal cannot find it (#1857) (#1858)

Nacho há 1 mês atrás
pai
commit
9a45e170a4

+ 1 - 0
CHANGELOG.md

@@ -42,6 +42,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- The init written by the installer no longer registers a service whose binary is missing. After a sysupgrade, when the self-heal could not fetch the agent (no environment file, unreachable server, digest mismatch), the init still handed procd a path it could not execute: the service reported as started, procd retried and gave up, and the agent never ran. It now says why and leaves the service alone, so the failure shows instead of hiding behind a started unit (#1857).
 - 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).

+ 93 - 0
server-go/internal/reinstall/init_selfheal_1857_test.go

@@ -0,0 +1,93 @@
+package reinstall_test
+
+import (
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
+)
+
+// #1857: el init procd solo debe registrar la instancia cuando hay binario.
+// Si el self-heal no lo consigue, procd arrancaria una ruta inexistente,
+// reintentaria y se rendiria: el servicio queda como arrancado y el agente
+// muerto sin mas rastro que una linea en el log.
+func initHeredocBody(t *testing.T, script string) string {
+	t.Helper()
+	const marker = "<<'INITEOF'\n"
+	start := strings.Index(script, marker)
+	if start < 0 {
+		t.Fatalf("el instalador no tiene heredoc INITEOF")
+	}
+	start += len(marker)
+	end := strings.Index(script[start:], "\nINITEOF\n")
+	if end < 0 {
+		t.Fatalf("el heredoc INITEOF no esta cerrado")
+	}
+	return script[start : start+end+1]
+}
+
+func runInit(t *testing.T, body, bin string) string {
+	t.Helper()
+	dir := t.TempDir()
+	path := filepath.Join(dir, "init.sh")
+	script := `logger() { echo "LOG: $*"; }
+procd_open_instance() { echo "OPEN $*"; }
+procd_set_param() { :; }
+procd_close_instance() { echo "CLOSE"; }
+crontab() { return 1; }
+` + body + `
+BIN="` + bin + `"
+ENV_FILE="` + filepath.Join(dir, "no-existe") + `"
+start_service
+`
+	if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
+		t.Fatalf("no pude escribir el init de prueba: %v", err)
+	}
+	out, err := exec.Command("sh", path).CombinedOutput()
+	if err != nil {
+		t.Fatalf("el init fallo: %v\n%s", err, out)
+	}
+	return string(out)
+}
+
+func TestInitPassesSyntaxCheck(t *testing.T) {
+	body := initHeredocBody(t, reinstall.ScriptWithTargets(
+		"test-router", strings.Repeat("a1", 32), "https://192.168.1.226:8443", "sha256//AAAA",
+		map[string]string{"arm64": "cafebabe"}, reinstall.WanTargets{},
+	))
+	if err := exec.Command("sh", "-n", "-c", body).Run(); err != nil {
+		t.Fatalf("el init generado no pasa sh -n: %v", err)
+	}
+}
+
+func TestInitSkipsStartWhenTheBinaryIsMissing(t *testing.T) {
+	out := runInit(t, initHeredocBody(t, reinstall.ScriptWithTargets(
+		"test-router", strings.Repeat("a1", 32), "https://192.168.1.226:8443", "sha256//AAAA",
+		map[string]string{"arm64": "cafebabe"}, reinstall.WanTargets{},
+	)), filepath.Join(t.TempDir(), "netpulse-agent"))
+
+	if strings.Contains(out, "OPEN") {
+		t.Errorf("registro la instancia sin binario:\n%s", out)
+	}
+	if !strings.Contains(out, "self-heal: no se pudo restaurar el binario; el servicio no arranca") {
+		t.Errorf("no dijo por que no arranca:\n%s", out)
+	}
+}
+
+func TestInitStartsWhenTheBinaryIsThere(t *testing.T) {
+	bin := filepath.Join(t.TempDir(), "netpulse-agent")
+	if err := os.WriteFile(bin, []byte("#!/bin/sh\n"), 0o755); err != nil {
+		t.Fatalf("no pude crear el binario de prueba: %v", err)
+	}
+	out := runInit(t, initHeredocBody(t, reinstall.ScriptWithTargets(
+		"test-router", strings.Repeat("a1", 32), "https://192.168.1.226:8443", "sha256//AAAA",
+		map[string]string{"arm64": "cafebabe"}, reinstall.WanTargets{},
+	)), bin)
+
+	if !strings.Contains(out, "OPEN netpulse-agent") {
+		t.Errorf("no registro la instancia con el binario presente:\n%s", out)
+	}
+}

+ 15 - 8
server-go/internal/reinstall/reinstall.go

@@ -473,19 +473,26 @@ selfheal_binary() {
 }
 
 
-	# (#879) self-heal: tras un sysupgrade /etc sobrevive pero el binario del
-	# watchdog no: si quedó la entrada de cron del antiguo watchdog, retirarla
-	# (cron loguearía un comando inexistente cada 2 min).
-	cleanup_stale_watchdog_cron() {
+# (#879) self-heal: tras un sysupgrade /etc sobrevive pero el binario del
+# watchdog no: si quedó la entrada de cron del antiguo watchdog, retirarla
+# (cron loguearía un comando inexistente cada 2 min).
+cleanup_stale_watchdog_cron() {
 	[ -f /usr/sbin/netpulse-watchdog ] && return 0
 	crontab -l 2>/dev/null | grep -q netpulse-watchdog || return 0
 	( crontab -l 2>/dev/null | grep -v netpulse-watchdog ) | crontab - 2>/dev/null || true
 	logger -t netpulse-agent "watchdog cron huérfano retirado (#879)"
-	}
-	
-	start_service() {
+}
+
+# #1857: si el binario no está y el self-heal no lo trae, no se registra la
+# instancia. procd arrancaría una ruta inexistente, reintentaría y se
+# rendiría, dejando el servicio como arrancado y el agente muerto sin más
+# rastro que una línea en el log.
+start_service() {
 	cleanup_stale_watchdog_cron
-	selfheal_binary || logger -t netpulse-agent "self-heal: no se pudo restaurar el binario"
+	if ! selfheal_binary; then
+		logger -t netpulse-agent "self-heal: no se pudo restaurar el binario; el servicio no arranca"
+		return 0
+	fi
 	procd_open_instance netpulse-agent
 	procd_set_param command "$BIN"
 	procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"

+ 1 - 1
server-go/internal/reinstall/script_test.go

@@ -147,7 +147,7 @@ func TestScriptSelfHealInit(t *testing.T) {
 		"selfheal_binary()",
 		`url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"`,
 		"logger -t netpulse-agent \"self-heal: binario restaurado\"",
-		"selfheal_binary || logger -t netpulse-agent \"self-heal: no se pudo restaurar el binario\"",
+		"self-heal: no se pudo restaurar el binario; el servicio no arranca",
 	} {
 		if !strings.Contains(s, want) {
 			t.Errorf("init sin self-heal: falta %q", want)