Explorar o código

fix(firmware): classify a rebooting owut flash as in progress (#1775)

* fix(firmware): classify a fast rebooting owut flash as in progress (#1771)

* fix(firmware): treat a clean ssh close with the owut reboot line as in progress (#1771)
Nacho hai 1 mes
pai
achega
85f8e1eab2

+ 20 - 7
server-go/internal/httpapi/firmware_owut.go

@@ -43,15 +43,18 @@ type platformCacheEntry struct {
 	at time.Time
 }
 
-const (
+var (
 	owutDetectCacheTTL = time.Hour
 	// owutRebootGrace: margen para que el router reinicie, vuelva el sondeo
 	// y el board info reporte la versión nueva.
 	owutRebootGrace = 15 * time.Minute
 	// owutSSHMinRun: si la sesión SSH muere antes de este umbral, no fue el
-	// reinicio del sysupgrade: el comando ni arrancó.
+	// reinicio del sysupgrade: el comando ni arrancó. No es suficiente por
+	// sí solo (#1771): un flash rápido muere antes y caía a "failed".
 	owutSSHMinRun = 30 * time.Second
-	recTickEvery  = time.Minute
+	// owutRebootPoll: cadencia de sondeo dentro de awaitReboot.
+	owutRebootPoll = 20 * time.Second
+	recTickEvery   = time.Minute
 )
 
 func (s *server) registerFirmwareOwutRoutes(mux *http.ServeMux) {
@@ -350,7 +353,10 @@ func (s *server) runOwutUpgrade(id int64, routerID, host, target, origin string,
 	switch {
 	case err == nil && exit == 0 && strings.Contains(out, "no changes"):
 		_ = s.firmware.SetStatus(id, "done", "sin cambios: ya estaba al día", "")
-	case (err == nil && exit == 0) || (err != nil && dur >= owutSSHMinRun):
+	// #1771: la muerte de la sesión SSH es el final normal del flash aunque
+	// sea rápida; la línea "rebooting" de owut lo confirma.
+	case (err == nil && exit == 0) ||
+		(err != nil && (dur >= owutSSHMinRun || strings.Contains(out, "rebooting"))):
 		s.awaitReboot(id, routerID, target, origin, from)
 	default:
 		msg := owutTail(out, err)
@@ -380,6 +386,11 @@ func (s *server) runOwutInstallImage(id int64, routerID, host, target string) {
 	exit, out, err := firmware.RunOwutUpgrade(s.pool, host, firmware.OwutInstallCmd())
 	dur := time.Since(start)
 	switch {
+	case err == nil && exit == 0 && strings.Contains(out, "rebooting"):
+		// #1771: al reiniciar el router la sesión SSH puede cerrar limpia
+		// (sin error de transporte) y el marcador __owut_exit__ nunca se
+		// imprime (el shell muere): la línea de reboot confirma el flash.
+		s.awaitReboot(id, routerID, target, "manual", from)
 	case err == nil && exit == 0:
 		// owut install puede terminar sin reiniciar si no había imagen
 		// descargada: no es un éxito, es un no-op que hay que decir.
@@ -389,7 +400,9 @@ func (s *server) runOwutInstallImage(id int64, routerID, host, target string) {
 		}
 		_ = s.firmware.SetStatus(id, "failed", msg, "")
 		s.emitFirmwareResult(routerID, from, target, "manual", false, msg)
-	case err != nil && dur >= owutSSHMinRun:
+	case err != nil && (dur >= owutSSHMinRun || strings.Contains(out, "rebooting")):
+		// #1771: "Installing ... and rebooting..." con la sesión muerta es un
+		// flash en curso, no un fallo, aunque muera antes de owutSSHMinRun.
 		s.awaitReboot(id, routerID, target, "manual", from)
 	default:
 		msg := owutTail(out, err)
@@ -413,8 +426,8 @@ func (s *server) awaitReboot(id int64, routerID, target, origin, from string) {
 	_ = s.firmware.SetStatus(id, "rebooting", "", "")
 	deadline := time.Now().Add(owutRebootGrace)
 	for time.Now().Before(deadline) {
-		time.Sleep(20 * time.Second)
-		if v := s.detectedFirmwareVersion(routerID); v == target && target != "" {
+		time.Sleep(owutRebootPoll)
+		if v := s.detectedFirmwareVersion(routerID); (target != "" && v == target) || (target == "" && v != "" && v != from) {
 			_ = s.firmware.SetStatus(id, "done", "", "")
 			s.emitFirmwareResult(routerID, from, target, origin, true, "")
 			return

+ 218 - 0
server-go/internal/httpapi/firmware_owut_internal_test.go

@@ -4,11 +4,13 @@
 package httpapi
 
 import (
+	"errors"
 	"strings"
 	"sync"
 	"testing"
 	"time"
 
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/config"
 	"github.com/gnacho/netpulse/server-go/internal/db"
@@ -158,3 +160,219 @@ func TestRunRecurrenceShotLaunchesOwutWhenOutdated(t *testing.T) {
 	}
 	t.Fatalf("desfasado debe lanzar owut upgrade -V 25.12.7: %v", pool.cmds)
 }
+
+// rebootFakeSSH (#1771): variante del fake que simula el corte de sesión SSH
+// de un flash real: el comando muere con error dejando la salida de owut a
+// medias. El resto de comandos (detección, preserve-stack) responde vacío.
+type rebootFakeSSH struct {
+	recFakeSSH
+	installOut string
+	installErr error
+	upgradeOut string
+	upgradeErr error
+}
+
+func (f *rebootFakeSSH) Run(host, cmd string, _ time.Duration) (string, error) {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	f.cmds = append(f.cmds, cmd)
+	switch {
+	case strings.Contains(cmd, "owut install"):
+		return f.installOut, f.installErr
+	case strings.Contains(cmd, "owut upgrade"):
+		if f.upgradeOut != "" || f.upgradeErr != nil {
+			return f.upgradeOut, f.upgradeErr
+		}
+		return "There are no changes to upgrade\n__owut_exit__=0\n", nil
+	case strings.Contains(cmd, "command -v owut"):
+		return "__owut__\n", nil
+	}
+	return "", nil
+}
+
+// staticBoardAdapter: adapter mínimo que reporta siempre la misma versión de
+// board info (lo que haría el router tras completar el flash). El embedding
+// de Demo cubre el resto del interfaz Snapshotter: estos tests solo llegan a
+// BoardInfoFor vía detectedFirmwareVersion.
+type staticBoardAdapter struct {
+	*adapters.Demo
+	version string
+}
+
+func (a *staticBoardAdapter) BoardInfoFor(string) *adapters.BoardInfo {
+	return &adapters.BoardInfo{Release: struct {
+		Version     string `json:"version"`
+		Description string `json:"description"`
+		Target      string `json:"target"`
+	}{Version: a.version}}
+}
+
+// shortenOwutRebootTimers: gracia y sondeo cortos para no alargar los tests.
+func shortenOwutRebootTimers(t *testing.T) {
+	t.Helper()
+	oldGrace, oldPoll := owutRebootGrace, owutRebootPoll
+	owutRebootGrace = 2 * time.Second
+	owutRebootPoll = 50 * time.Millisecond
+	t.Cleanup(func() { owutRebootGrace, owutRebootPoll = oldGrace, oldPoll })
+}
+
+// waitUpgradeStatus sondea el store hasta que el upgrade llega a uno de los
+// estados pedidos (el flash corre en goroutine en el flujo real; aquí las
+// llamadas son directas, pero awaitReboot sondea con su timer).
+func waitUpgradeStatus(t *testing.T, s *server, id int64, want ...string) *firmware.Upgrade {
+	t.Helper()
+	deadline := time.Now().Add(5 * time.Second)
+	for time.Now().Before(deadline) {
+		if up, err := s.firmware.GetUpgradeByID(id); err == nil && up != nil {
+			for _, w := range want {
+				if up.Status == w {
+					return up
+				}
+			}
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	up, _ := s.firmware.GetUpgradeByID(id)
+	t.Fatalf("upgrade %d no llegó a %v: %+v", id, want, up)
+	return nil
+}
+
+// #1771: "Installing ... and rebooting..." con la sesión SSH muerta termina
+// en done, no en failed, aunque el flash muera antes de owutSSHMinRun
+// (install por pasos).
+func TestOwutInstallRebootLineGoesToDone(t *testing.T) {
+	shortenOwutRebootTimers(t)
+	s, rid, _ := makeRecServer(t, "25.12.5")
+	re := &rebootFakeSSH{
+		installOut: "Installing /tmp/firmware.bin and rebooting...\n",
+		installErr: errors.New("ssh: session closed"),
+	}
+	s.pool = re
+	s.adapter = &staticBoardAdapter{version: "25.12.6"}
+
+	id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
+	if err != nil {
+		t.Fatalf("begin: %v", err)
+	}
+	s.runOwutInstallImage(id, rid, "192.168.1.60", "25.12.6")
+
+	up := waitUpgradeStatus(t, s, id, "done")
+	if up.Status != "done" {
+		t.Fatalf("status = %q (%q), esperaba done", up.Status, up.Error)
+	}
+	if !re.saw("owut install") {
+		t.Fatalf("el fake no vio owut install: %v", re.cmds)
+	}
+}
+
+// #1771: mismo caso en el one-shot `owut upgrade`.
+func TestOwutUpgradeRebootLineGoesToDone(t *testing.T) {
+	shortenOwutRebootTimers(t)
+	s, rid, _ := makeRecServer(t, "25.12.5")
+	re := &rebootFakeSSH{
+		upgradeOut: "Installing /tmp/firmware.bin and rebooting...\n",
+		upgradeErr: errors.New("ssh: session closed"),
+	}
+	s.pool = re
+	s.adapter = &staticBoardAdapter{version: "25.12.6"}
+
+	id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
+	if err != nil {
+		t.Fatalf("begin: %v", err)
+	}
+	s.runOwutUpgrade(id, rid, "192.168.1.60", "25.12.6", "manual", nil)
+
+	waitUpgradeStatus(t, s, id, "done")
+}
+
+// #1771: al reiniciar, la sesión SSH puede cerrar LIMPIA (err nil) y sin el
+// marcador __owut_exit__ (el shell muere antes del printf): la línea de
+// reboot debe clasificar flash en curso, no "terminó sin flashear".
+func TestOwutInstallCleanCloseGoesToDone(t *testing.T) {
+	shortenOwutRebootTimers(t)
+	s, rid, _ := makeRecServer(t, "25.12.5")
+	re := &rebootFakeSSH{
+		installOut: "Installing /tmp/firmware.bin and rebooting...\n",
+	}
+	s.pool = re
+	s.adapter = &staticBoardAdapter{version: "25.12.6"}
+
+	id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
+	if err != nil {
+		t.Fatalf("begin: %v", err)
+	}
+	s.runOwutInstallImage(id, rid, "192.168.1.60", "25.12.6")
+
+	up := waitUpgradeStatus(t, s, id, "done")
+	if up.Status != "done" {
+		t.Fatalf("status = %q (%q), esperaba done", up.Status, up.Error)
+	}
+}
+
+// El caso opuesto (sesión limpia, sin línea de reboot) sigue siendo el
+// no-op "terminó sin flashear".
+func TestOwutInstallCleanCloseWithoutRebootStillNoOp(t *testing.T) {
+	shortenOwutRebootTimers(t)
+	s, rid, _ := makeRecServer(t, "25.12.5")
+	re := &rebootFakeSSH{
+		installOut: "Image verifier: /tmp/firmware.bin OK\n",
+	}
+	s.pool = re
+	s.adapter = &staticBoardAdapter{version: "25.12.5"}
+
+	id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
+	if err != nil {
+		t.Fatalf("begin: %v", err)
+	}
+	s.runOwutInstallImage(id, rid, "192.168.1.60", "25.12.6")
+
+	up := waitUpgradeStatus(t, s, id, "failed")
+	if !strings.Contains(up.Error, "Image verifier") {
+		t.Fatalf("error = %q, esperaba la salida cruda del no-op", up.Error)
+	}
+}
+
+// Un error real (sin línea de reboot) sigue clasificando failed, con el
+// texto accionable de #1769 cuando el motivo es la imagen ausente.
+func TestOwutInstallRealErrorStillFailed(t *testing.T) {
+	shortenOwutRebootTimers(t)
+	s, rid, _ := makeRecServer(t, "25.12.5")
+	re := &rebootFakeSSH{
+		installOut: "sysupgrade: ERROR: Image file '/tmp/firmware.bin' does not exist\n",
+		installErr: errors.New("exit status 1"),
+	}
+	s.pool = re
+	s.adapter = &staticBoardAdapter{version: "25.12.5"}
+
+	id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
+	if err != nil {
+		t.Fatalf("begin: %v", err)
+	}
+	s.runOwutInstallImage(id, rid, "192.168.1.60", "25.12.6")
+
+	up := waitUpgradeStatus(t, s, id, "failed")
+	if !strings.Contains(up.Error, "No hay imagen descargada") {
+		t.Fatalf("error = %q, esperaba el texto accionable de #1769", up.Error)
+	}
+}
+
+// #1771: sin target en memoria, el cambio de versión reportado por el board
+// info también confirma el flash (v != from).
+func TestOwutInstallNoTargetStillDoneWhenVersionChanges(t *testing.T) {
+	shortenOwutRebootTimers(t)
+	s, rid, _ := makeRecServer(t, "25.12.5")
+	re := &rebootFakeSSH{
+		installOut: "Installing /tmp/firmware.bin and rebooting...\n",
+		installErr: errors.New("ssh: session closed"),
+	}
+	s.pool = re
+	s.adapter = &staticBoardAdapter{version: "25.12.6"}
+
+	id, err := s.firmware.BeginUpgradeIfIdle(rid, "25.12.6", "", "")
+	if err != nil {
+		t.Fatalf("begin: %v", err)
+	}
+	s.runOwutInstallImage(id, rid, "192.168.1.60", "")
+
+	waitUpgradeStatus(t, s, id, "done")
+}