Explorar o código

fix(firmware): keep owut download response alive

Closes #1978
Nacho hai 1 semana
pai
achega
8a19c336b6

+ 1 - 0
CHANGELOG.md

@@ -14,6 +14,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- `owut download` keeps the HTTP response open during remote ASU builds and returns the full command output on failure, shown in the unit card (#1978).
 - The early language choice now runs from the external `boot.js` instead of an inline script blocked by the production Content Security Policy (#2173).
 - The update history header no longer nests its download action inside another button. Expand/collapse and download are separate keyboard-accessible controls (#2168).
 - Devices named only by mDNS now use that hostname in the existing type rules, so a vacuum or console without a DHCP hostname no longer stays unknown (#2157).

+ 5 - 1
app/src/pages/FirmwareUpgrades.tsx

@@ -664,6 +664,7 @@ export default function FirmwareUpgrades() {
     const e = edits[id]
     setOwutDlBusy((prev) => ({ ...prev, [id]: true }))
     setOwutDlOk((prev) => ({ ...prev, [id]: false }))
+    setOwutDlOutput((prev) => ({ ...prev, [id]: '' }))
     setError('')
     try {
       const stored = (removePkgs[id] ?? '').trim()
@@ -674,7 +675,10 @@ export default function FirmwareUpgrades() {
         body: JSON.stringify({ targetVersion: targetOverride || e?.targetVersion || '', removePackages, force }),
       })
       const body = await res.json().catch(() => ({}))
-      if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `HTTP ${res.status}`)
+      if (!res.ok) {
+        setOwutDlOutput((prev) => ({ ...prev, [id]: String(body.output ?? body?.message ?? `HTTP ${res.status}`) }))
+        throw new Error(body?.message ?? `HTTP ${res.status}`)
+      }
       setOwutDlOutput((prev) => ({ ...prev, [id]: String(body.output ?? '') }))
       setOwutDlOk((prev) => ({ ...prev, [id]: true }))
     } catch (err) {

+ 4 - 0
server-go/internal/httpapi/device_actions_test.go

@@ -36,6 +36,7 @@ type sshRule struct {
 	contains string
 	out      string
 	err      error
+	delay    time.Duration
 }
 
 type scriptedSSH struct {
@@ -58,6 +59,9 @@ func (f *scriptedSSH) Run(host, cmd string, _ time.Duration) (string, error) {
 			continue
 		}
 		if strings.Contains(cmd, r.contains) {
+			if r.delay > 0 {
+				time.Sleep(r.delay)
+			}
 			return r.out, r.err
 		}
 	}

+ 5 - 1
server-go/internal/httpapi/firmware_owut.go

@@ -179,6 +179,7 @@ func (s *server) registerFirmwareOwutRoutes(mux *http.ServeMux) {
 	// flashear (paso intermedio del flujo por pasos, #1414). Síncrono: la
 	// salida completa es la revisión del admin antes de instalar.
 	mux.Handle("POST /api/firmware-upgrades/{routerId}/owut-download", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		setLongWriteDeadline(w, owutDownloadWriteCeiling)
 		id := r.PathValue("routerId")
 		host := s.hostOfRouter(id)
 		if host == "" {
@@ -221,7 +222,10 @@ func (s *server) registerFirmwareOwutRoutes(mux *http.ServeMux) {
 			if msg == "" {
 				msg = fmt.Sprintf("owut download falló (exit %d)", exit)
 			}
-			writeError(w, http.StatusBadGateway, "owut_download_failed", msg)
+			writeJSON(w, http.StatusBadGateway, map[string]any{
+				"error": "owut_download_failed", "message": msg,
+				"command": cmd, "output": owutEcho(cmd, out),
+			})
 			return
 		}
 		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "command": cmd, "output": owutEcho(cmd, out)})

+ 45 - 0
server-go/internal/httpapi/firmware_owut_test.go

@@ -245,6 +245,51 @@ func TestOwutDownloadEndpointPutsRemovePackagesInUCINotInFlag(t *testing.T) {
 	}
 }
 
+func TestOwutDownloadOutlivesWriteTimeout(t *testing.T) {
+	const sshDelay = time.Second
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "command -v owut", out: "__owut__\n"},
+		{contains: "owut download", delay: sshDelay, out: "Downloading image to /tmp/firmware.bin\n__owut_exit__=0\n"},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh, 500*time.Millisecond)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	started := time.Now()
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-download", `{"targetVersion":"25.12.6"}`, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 200 {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	if elapsed := time.Since(started); elapsed < sshDelay {
+		t.Fatalf("server responded before the simulated command finished: %s", elapsed)
+	}
+	if out, _ := body["output"].(string); !strings.Contains(out, "Downloading image") {
+		t.Fatalf("missing full command output: %v", body)
+	}
+}
+
+func TestOwutDownloadErrorIncludesFullOutput(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "command -v owut", out: "__owut__\n"},
+		{contains: "owut download", out: "Build request started\nASU build failed\n__owut_exit__=1\n"},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-download", `{"targetVersion":"25.12.6"}`, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != http.StatusBadGateway {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	out, _ := body["output"].(string)
+	if !strings.HasPrefix(out, "$ owut download") || !strings.Contains(out, "Build request started") || !strings.Contains(out, "ASU build failed") {
+		t.Fatalf("error response misses full output: %v", body)
+	}
+	if cmd, _ := body["command"].(string); !strings.Contains(cmd, "owut download") {
+		t.Fatalf("error response misses command: %v", body)
+	}
+}
+
 // #1978: sin config UCI donde escribir, el flag -r sigue siendo la única vía
 // de excluir paquetes. El fallback no puede perderse.
 func TestOwutDownloadEndpointFallsBackToRemoveFlag(t *testing.T) {

+ 2 - 0
server-go/internal/httpapi/longwrite.go

@@ -29,6 +29,8 @@ const (
 	configBackupWriteCeiling = 180 * time.Second
 	// 10 s de `uci show` + 20 s de commit + 20 s de restart + margen.
 	deviceActionWriteCeiling = 70 * time.Second
+	// 10 min del build remoto y la descarga owut + margen.
+	owutDownloadWriteCeiling = 11 * time.Minute
 	// Reemit recorre la flota entera, un SSH por agente.
 	reemitPerAgentCeiling = 150 * time.Second
 	reemitMaxCeiling      = time.Hour

+ 1 - 0
server-go/internal/httpapi/longwrite_test.go

@@ -69,6 +69,7 @@ func TestWriteCeilingsExceedTheGlobalTimeout(t *testing.T) {
 		"integration install": integrationWriteCeiling,
 		"config backup":       configBackupWriteCeiling,
 		"device action":       deviceActionWriteCeiling,
+		"owut download":       owutDownloadWriteCeiling,
 		"reemit (1 agente)":   reemitWriteCeiling(1),
 	}
 	for name, d := range ceilings {

+ 9 - 2
server-go/internal/httpapi/owut_test.go

@@ -29,7 +29,7 @@ __owut_exit__=0
 
 // makeOwutTestServer monta un servidor con el pool SSH fakeado y el store de
 // firmware activo, añade un router openwrt y devuelve servidor + router id.
-func makeOwutTestServer(t *testing.T, ssh *scriptedSSH) (*testServer, string) {
+func makeOwutTestServer(t *testing.T, ssh *scriptedSSH, writeTimeout ...time.Duration) (*testServer, string) {
 	t.Helper()
 	auth.SetTrustProxy(true)
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
@@ -69,7 +69,14 @@ func makeOwutTestServer(t *testing.T, ssh *scriptedSSH) (*testServer, string) {
 		Agents: agents, Pool: runner, Started: time.Now(),
 		Firmware: firmware.NewStore(d.DB),
 	})
-	srv := httptest.NewServer(handler)
+	var srv *httptest.Server
+	if len(writeTimeout) > 0 && writeTimeout[0] > 0 {
+		srv = httptest.NewUnstartedServer(handler)
+		srv.Config.WriteTimeout = writeTimeout[0]
+		srv.Start()
+	} else {
+		srv = httptest.NewServer(handler)
+	}
 	ts := &testServer{Server: srv, db: d, secret: secret}
 	t.Cleanup(func() {
 		srv.Close()