Просмотр исходного кода

fix(reinstall): stop the agent only once the binary can be installed (#1853) (#1854)

Nacho 1 месяц назад
Родитель
Сommit
8fb96edd59

+ 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 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).
 - Addresses that come and go within a minute are no longer clients (#1818). Randomised MACs, phones that probe once and mesh units that bounce an association all reached the device table, the counters and the new-client alert within a single poll. A MAC the database has never seen now has to stay online for a minute before it is stored, counted or alerted, and when it finally lands the row keeps the moment it was first seen instead of the moment it was promoted. The wait is kept in memory on purpose: it is a judgement about the current poll cycle, so a restart costs one extra minute at most, and a device that already exists in the table is never held back. Without a database the check steps aside and the old behaviour returns.

+ 16 - 9
server-go/internal/reinstall/reinstall.go

@@ -308,9 +308,9 @@ case "$ARCH" in
 		case "$(head -c 6 /bin/sh | tail -c 1 | tr '\001\002' '12')" in
 			1) GOARCH=mipsle; SHA256="` + digests["mipsle"] + `" ;;
 			2) GOARCH=mips;  SHA256="` + digests["mips"] + `" ;;
-			*) echo "no pude detectar el endianness de $ARCH"; exit 20 ;;
+			*) echo "no pude detectar el endianness de $ARCH" >&2; exit 20 ;;
 		esac ;;
-	*) echo "arch no soportado: $ARCH"; exit 20 ;;
+	*) echo "arch no soportado: $ARCH" >&2; exit 20 ;;
 esac
 
 # #1476: si el router habla opkg o apk, instala el paquete que sirve el propio
@@ -347,9 +347,6 @@ elif command -v apk >/dev/null 2>&1; then
 	rm -f /tmp/netpulse-agent.apk
 fi
 
-# Parar servicio previo si existe (el proceso vivo mantiene el binario abierto)
-[ -f "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
-
 if [ "$PKG_OK" != "1" ]; then
 # Descargar el binario del propio server (auth por token)
 # #1737: sin estos mensajes el fallo llega como "Process exited with status
@@ -364,10 +361,20 @@ fi
 # Verificación sha256 contra el digest embebido (#463); vacío = sin verificar
 if [ -n "$SHA256" ]; then
 	GOT=$(sha256sum /tmp/netpulse-agent.new | awk '{print $1}')
-	[ "$GOT" = "$SHA256" ] || { echo "sha256 no coincide (esperado $SHA256, obtenido $GOT)"; exit 21; }
+	[ "$GOT" = "$SHA256" ] || { echo "sha256 no coincide (esperado $SHA256, obtenido $GOT)" >&2; exit 21; }
 fi
 chmod 0755 /tmp/netpulse-agent.new
-mv -f /tmp/netpulse-agent.new "$BIN"
+# #1853: el servicio se para AQUI, con el binario ya descargado y verificado.
+# Pararlo antes dejaba el router sin agente si la descarga fallaba. Hay que
+# pararlo igualmente: /tmp es tmpfs y /usr es overlay, asi que mv escribe el
+# destino y un binario en ejecucion da ETXTBSY. Si el reemplazo falla, se
+# vuelve a arrancar el anterior en vez de dejarlo caido.
+[ -f "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
+if ! mv -f /tmp/netpulse-agent.new "$BIN"; then
+	echo "netpulse-agent: no pude reemplazar $BIN; vuelvo a arrancar el agente anterior" >&2
+	[ -f "$INIT" ] && "$INIT" start >/dev/null 2>&1 || true
+	exit 23
+fi
 fi
 
 # Config (chmod 600). El rewrite toca SOLO las vars gestionadas (SERVER,
@@ -502,7 +509,7 @@ set -e
 ENV_FILE=/etc/netpulse-agent.env
 INIT=/etc/init.d/netpulse-agent
 # El env debe existir: el router ya tenía el agente instalado.
-[ -f "$ENV_FILE" ] || { echo "netpulse-agent.env no existe; token no actualizado"; exit 30; }
+[ -f "$ENV_FILE" ] || { echo "netpulse-agent.env no existe; token no actualizado" >&2; exit 30; }
 # Conservar el server y el slug del env existente para no romper la config.
 SERVER=$(sed -n 's/^NETPULSE_SERVER=//p' "$ENV_FILE" | head -n1)
 SLUG=$(sed -n 's/^NETPULSE_SLUG=//p' "$ENV_FILE" | head -n1)
@@ -513,7 +520,7 @@ SLUG=$(sed -n 's/^NETPULSE_SLUG=//p' "$ENV_FILE" | head -n1)
 # aplica una vez emparejado.
 FP=$(sed -n 's/^NETPULSE_SERVER_FP=//p' "$ENV_FILE" | head -n1)
 USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE" | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN)=') || true
-[ -n "$SLUG" ] || { echo "netpulse-agent.env sin NETPULSE_SLUG"; exit 31; }
+[ -n "$SLUG" ] || { echo "netpulse-agent.env sin NETPULSE_SLUG" >&2; exit 31; }
 umask 077
 cat > "$ENV_FILE.tmp" <<EOF
 NETPULSE_SERVER=$SERVER

+ 56 - 0
server-go/internal/reinstall/robust_1853_test.go

@@ -0,0 +1,56 @@
+package reinstall_test
+
+import (
+	"os/exec"
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
+)
+
+// #1853: un reinstall que falla no debe dejar el agente parado. El servicio se
+// para solo cuando el binario ya esta descargado y verificado, y si el
+// reemplazo falla se vuelve a arrancar el anterior.
+func TestScriptStopsOnlyOnceItCanInstall(t *testing.T) {
+	s := reinstall.ScriptWithTargets(
+		"test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000",
+		"sha256//AAAA", map[string]string{"arm64": "cafebabe"},
+		reinstall.WanTargets{},
+	)
+
+	download := strings.Index(s, "/binary?arch=$GOARCH")
+	digest := strings.Index(s, "sha256 no coincide")
+	stop := strings.Index(s, `"$INIT" stop`)
+	replace := strings.Index(s, `mv -f /tmp/netpulse-agent.new "$BIN"`)
+	if download < 0 || digest < 0 || stop < 0 || replace < 0 {
+		t.Fatalf("falta un paso: download=%d digest=%d stop=%d replace=%d", download, digest, stop, replace)
+	}
+	if !(download < digest && digest < stop && stop < replace) {
+		t.Errorf("orden incorrecto: download=%d digest=%d stop=%d replace=%d", download, digest, stop, replace)
+	}
+
+	if !strings.Contains(s, "vuelvo a arrancar el agente anterior") {
+		t.Error("el fallo al reemplazar el binario debe avisar del rollback")
+	}
+	if !strings.Contains(s, `"$INIT" start`) {
+		t.Error("el fallo al reemplazar el binario debe volver a arrancar el agente")
+	}
+	if !strings.Contains(s, "exit 23") {
+		t.Error("falta el codigo de salida del reemplazo fallido")
+	}
+
+	// Los diagnosticos tienen que ir a stderr: el servidor solo captura stderr.
+	for _, want := range []string{
+		`sha256 no coincide (esperado $SHA256, obtenido $GOT)" >&2`,
+		`no pude detectar el endianness de $ARCH" >&2`,
+		`arch no soportado: $ARCH" >&2`,
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("mensaje sin stderr: %s", want)
+		}
+	}
+
+	if err := exec.Command("sh", "-n", "-c", s).Run(); err != nil {
+		t.Fatalf("script invalido: %v", err)
+	}
+}