firmware_owut.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. // firmware_owut.go - ciclo owut completo y recurrencia de firmware (#761).
  2. //
  3. // Endpoints: lista de versiones (dropdown), instalación del paquete owut,
  4. // upgrade desatendido (máquina de estados running -> rebooting -> done) y
  5. // programación recurrente (once/weekly/monthly, idempotente). El resultado
  6. // de cada intento (éxito o fallo) se emite como alerta urgent, que llega al
  7. // feed, push, webhook y Telegram con la configuración existente.
  8. package httpapi
  9. import (
  10. "context"
  11. "errors"
  12. "fmt"
  13. "log"
  14. "net/http"
  15. "strings"
  16. "time"
  17. "github.com/gnacho/netpulse/server-go/internal/adapters"
  18. "github.com/gnacho/netpulse/server-go/internal/alerts"
  19. "github.com/gnacho/netpulse/server-go/internal/auth"
  20. "github.com/gnacho/netpulse/server-go/internal/firmware"
  21. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  22. )
  23. // Cinturones de plataforma (#761): firmware de fabricante fuera, y sin owut
  24. // instalado no se lanza nada.
  25. var (
  26. errVendorFirmware = errors.New("firmware de fabricante (GL.iNet) sin soporte")
  27. ErrOwutNotInstalled = errors.New("owut no está instalado en el router")
  28. )
  29. // alertEmitter lo cumple *alerts.Engine (mismo patrón que speedtest).
  30. type alertEmitter interface {
  31. Emit(ev alerts.AlertEvent) bool
  32. }
  33. // platformCacheEntry cachea la plataforma (owut + vendor) por router (1 h):
  34. // el loop de recurrencia y los endpoints la consultan y sondear por SSH en
  35. // cada operación sería ruido innecesario.
  36. type platformCacheEntry struct {
  37. p firmware.Platform
  38. at time.Time
  39. }
  40. const (
  41. owutDetectCacheTTL = time.Hour
  42. // owutRebootGrace: margen para que el router reinicie, vuelva el sondeo
  43. // y el board info reporte la versión nueva.
  44. owutRebootGrace = 15 * time.Minute
  45. // owutSSHMinRun: si la sesión SSH muere antes de este umbral, no fue el
  46. // reinicio del sysupgrade: el comando ni arrancó.
  47. owutSSHMinRun = 30 * time.Second
  48. recTickEvery = time.Minute
  49. )
  50. func (s *server) registerFirmwareOwutRoutes(mux *http.ServeMux) {
  51. if s.firmware == nil {
  52. return
  53. }
  54. // GET versions: candidatos del dropdown (requiere owut en el router).
  55. mux.Handle("GET /api/firmware-upgrades/{routerId}/owut-versions", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  56. id := r.PathValue("routerId")
  57. host := s.hostOfRouter(id)
  58. if host == "" {
  59. writeError(w, http.StatusNotFound, "not_found")
  60. return
  61. }
  62. if s.pool == nil {
  63. writeError(w, http.StatusServiceUnavailable, "no_ssh_pool")
  64. return
  65. }
  66. resp := struct {
  67. Current string `json:"current"`
  68. OwutAvailable bool `json:"owutAvailable"`
  69. VendorFirmware string `json:"vendorFirmware,omitempty"`
  70. Versions []firmware.OwutVersion `json:"versions"`
  71. Error string `json:"error,omitempty"`
  72. }{Current: s.detectedFirmwareVersion(id)}
  73. plat := s.platform(id, host)
  74. if plat.Vendor != "" {
  75. // Firmware de fabricante: sus updates los gestiona el vendor.
  76. resp.VendorFirmware = plat.Vendor
  77. resp.Versions = []firmware.OwutVersion{}
  78. writeJSON(w, http.StatusOK, resp)
  79. return
  80. }
  81. if !plat.Owut {
  82. resp.Versions = []firmware.OwutVersion{}
  83. writeJSON(w, http.StatusOK, resp)
  84. return
  85. }
  86. resp.OwutAvailable = true
  87. versions, err := firmware.ListOwutVersions(s.pool, host, resp.Current)
  88. if err != nil {
  89. resp.Error = err.Error()
  90. resp.Versions = []firmware.OwutVersion{}
  91. } else {
  92. resp.Versions = versions
  93. }
  94. writeJSON(w, http.StatusOK, resp)
  95. })))
  96. // POST owut-install: instala el paquete owut con apk u opkg.
  97. mux.Handle("POST /api/firmware-upgrades/{routerId}/owut-install", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  98. id := r.PathValue("routerId")
  99. host := s.hostOfRouter(id)
  100. if host == "" {
  101. writeError(w, http.StatusNotFound, "not_found")
  102. return
  103. }
  104. if s.pool == nil {
  105. writeError(w, http.StatusServiceUnavailable, "no_ssh_pool")
  106. return
  107. }
  108. if s.platform(id, host).Vendor != "" {
  109. writeError(w, http.StatusUnprocessableEntity, "vendor_firmware",
  110. "El router lleva firmware del fabricante (GL.iNet): NetPulse no gestiona sus actualizaciones, usa su propio panel.")
  111. return
  112. }
  113. output, err := firmware.InstallOwut(s.pool, host)
  114. if err != nil {
  115. writeError(w, http.StatusInternalServerError, "owut_install_failed", err.Error())
  116. return
  117. }
  118. s.invalidatePlatformCache(id)
  119. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "output": output})
  120. })))
  121. // POST owut-upgrade: lanza el attended upgrade desatendido (ASU).
  122. mux.Handle("POST /api/firmware-upgrades/{routerId}/owut-upgrade", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  123. id := r.PathValue("routerId")
  124. var body struct {
  125. TargetVersion string `json:"targetVersion"`
  126. RemovePkgs []string `json:"removePackages"`
  127. }
  128. if st := readJSONBody(w, r, &body); st != 0 {
  129. return
  130. }
  131. if body.TargetVersion == "" {
  132. writeError(w, http.StatusBadRequest, "invalid_body", "targetVersion es requerido")
  133. return
  134. }
  135. if !firmware.ValidOpenWrtVersion(body.TargetVersion) {
  136. writeError(w, http.StatusBadRequest, "invalid_target_version",
  137. "targetVersion debe ser una versión OpenWrt (p. ej. 25.12.5), no un texto libre")
  138. return
  139. }
  140. if host := s.hostOfRouter(id); host != "" && s.platform(id, host).Vendor != "" {
  141. writeError(w, http.StatusUnprocessableEntity, "vendor_firmware",
  142. "El router lleva firmware del fabricante (GL.iNet): NetPulse no gestiona sus actualizaciones, usa su propio panel.")
  143. return
  144. }
  145. upgradeID, err := s.startOwutUpgrade(id, body.TargetVersion, "manual", body.RemovePkgs)
  146. switch {
  147. case errors.Is(err, firmware.ErrUpgradeInProgress):
  148. writeError(w, http.StatusConflict, "upgrade_in_progress", "Ya hay un upgrade en curso")
  149. case errors.Is(err, errVendorFirmware):
  150. writeError(w, http.StatusUnprocessableEntity, "vendor_firmware",
  151. "El router lleva firmware del fabricante (GL.iNet): NetPulse no gestiona sus actualizaciones, usa su propio panel.")
  152. case errors.Is(err, ErrOwutNotInstalled):
  153. writeError(w, http.StatusPreconditionFailed, "owut_not_installed",
  154. "owut no está instalado en el router: instálalo primero con el botón Instalar owut.")
  155. case errors.Is(err, errRouterNotFound):
  156. writeError(w, http.StatusNotFound, "not_found")
  157. case err != nil:
  158. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  159. default:
  160. writeJSON(w, http.StatusAccepted, map[string]any{"upgradeId": upgradeID, "engine": "owut"})
  161. }
  162. })))
  163. // POST owut-download: construye y descarga la imagen en el router SIN
  164. // flashear (paso intermedio del flujo por pasos, #1414). Síncrono: la
  165. // salida completa es la revisión del admin antes de instalar.
  166. mux.Handle("POST /api/firmware-upgrades/{routerId}/owut-download", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  167. id := r.PathValue("routerId")
  168. host := s.hostOfRouter(id)
  169. if host == "" {
  170. writeError(w, http.StatusNotFound, "not_found")
  171. return
  172. }
  173. if s.pool == nil {
  174. writeError(w, http.StatusServiceUnavailable, "no_ssh_pool")
  175. return
  176. }
  177. plat := s.platform(id, host)
  178. if plat.Vendor != "" {
  179. writeError(w, http.StatusUnprocessableEntity, "vendor_firmware",
  180. "El router lleva firmware del fabricante (GL.iNet): NetPulse no gestiona sus actualizaciones, usa su propio panel.")
  181. return
  182. }
  183. if !plat.Owut {
  184. writeError(w, http.StatusPreconditionFailed, "owut_not_installed",
  185. "owut no está instalado en el router: instálalo primero con el botón Instalar owut.")
  186. return
  187. }
  188. var body struct {
  189. TargetVersion string `json:"targetVersion"`
  190. }
  191. if st := readJSONBody(w, r, &body); st != 0 {
  192. return
  193. }
  194. cmd := firmware.OwutDownloadCmd(body.TargetVersion, s.detectedFirmwareVersion(id))
  195. exit, out, err := firmware.RunOwutDownload(s.pool, host, cmd)
  196. if err != nil || exit != 0 {
  197. msg := owutTail(out, err)
  198. if msg == "" {
  199. msg = fmt.Sprintf("owut download falló (exit %d)", exit)
  200. }
  201. writeError(w, http.StatusBadGateway, "owut_download_failed", msg)
  202. return
  203. }
  204. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "output": out})
  205. })))
  206. // POST owut-install-image: flashea la imagen que owut-download dejó en el
  207. // router (#1414, paso final del flujo por pasos). Igual que owut-upgrade:
  208. // 202 inmediata, la máquina de estados confirma tras el reboot.
  209. mux.Handle("POST /api/firmware-upgrades/{routerId}/owut-install-image", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  210. id := r.PathValue("routerId")
  211. host := s.hostOfRouter(id)
  212. if host == "" {
  213. writeError(w, http.StatusNotFound, "not_found")
  214. return
  215. }
  216. if s.pool == nil {
  217. writeError(w, http.StatusServiceUnavailable, "no_ssh_pool")
  218. return
  219. }
  220. plat := s.platform(id, host)
  221. if plat.Vendor != "" {
  222. writeError(w, http.StatusUnprocessableEntity, "vendor_firmware",
  223. "El router lleva firmware del fabricante (GL.iNet): NetPulse no gestiona sus actualizaciones, usa su propio panel.")
  224. return
  225. }
  226. if !plat.Owut {
  227. writeError(w, http.StatusPreconditionFailed, "owut_not_installed",
  228. "owut no está instalado en el router: instálalo primero con el botón Instalar owut.")
  229. return
  230. }
  231. target := ""
  232. if t, _ := s.firmware.GetTarget(id); t != nil {
  233. target = t.TargetVersion
  234. }
  235. uid, err := s.firmware.BeginUpgradeIfIdle(id, target, "", "")
  236. if err != nil {
  237. if errors.Is(err, firmware.ErrUpgradeInProgress) {
  238. writeError(w, http.StatusConflict, "upgrade_in_progress", "Ya hay un upgrade en curso")
  239. } else {
  240. writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
  241. }
  242. return
  243. }
  244. _ = s.firmware.SetEngine(uid, "owut")
  245. go s.runOwutInstallImage(uid, id, host, target)
  246. writeJSON(w, http.StatusAccepted, map[string]any{"upgradeId": uid, "engine": "owut"})
  247. })))
  248. // GET/PUT/DELETE recurrence: programación once/weekly/monthly.
  249. mux.Handle("GET /api/firmware-upgrades/{routerId}/recurrence", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  250. id := r.PathValue("routerId")
  251. rc := firmware.LoadRecurrence(s.db.DB, id)
  252. out := map[string]any{"recurrence": rc}
  253. if rc.Enabled {
  254. next := firmware.NextRecurrenceAt(rc, time.Now())
  255. if !next.IsZero() {
  256. out["nextRunMs"] = next.UnixMilli()
  257. }
  258. }
  259. writeJSON(w, http.StatusOK, out)
  260. })))
  261. mux.Handle("PUT /api/firmware-upgrades/{routerId}/recurrence", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  262. id := r.PathValue("routerId")
  263. var body firmware.Recurrence
  264. if st := readJSONBody(w, r, &body); st != 0 {
  265. return
  266. }
  267. prev := firmware.LoadRecurrence(s.db.DB, id)
  268. body.LastRunMs = prev.LastRunMs
  269. if err := firmware.SaveRecurrence(s.db.DB, id, body); err != nil {
  270. writeError(w, http.StatusBadRequest, "invalid_body", err.Error())
  271. return
  272. }
  273. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  274. })))
  275. mux.Handle("DELETE /api/firmware-upgrades/{routerId}/recurrence", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  276. id := r.PathValue("routerId")
  277. firmware.DisableRecurrence(s.db.DB, id)
  278. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  279. })))
  280. }
  281. // startOwutUpgrade crea la fila del upgrade y lanza la goroutine que lo
  282. // ejecuta por SSH. El POST responde 202 inmediatamente; el progreso se sigue
  283. // por GET /api/firmware-upgrades (item.upgrade).
  284. func (s *server) startOwutUpgrade(routerID, targetVersion, origin string, removePkgs []string) (int64, error) {
  285. host := s.hostOfRouter(routerID)
  286. if host == "" {
  287. return 0, errRouterNotFound
  288. }
  289. if s.pool == nil {
  290. return 0, errors.New("sin pool SSH")
  291. }
  292. // Cinturones de platform (#761): firmware de fabricante fuera, y sin
  293. // owut instalado no se lanza nada (el comando moriría en 127).
  294. if plat := s.platform(routerID, host); plat.Vendor != "" {
  295. return 0, errVendorFirmware
  296. } else if !plat.Owut {
  297. return 0, ErrOwutNotInstalled
  298. }
  299. id, err := s.firmware.BeginUpgradeIfIdle(routerID, targetVersion, "", "")
  300. if err != nil {
  301. return 0, err
  302. }
  303. _ = s.firmware.SetEngine(id, "owut")
  304. go s.runOwutUpgrade(id, routerID, host, targetVersion, origin, removePkgs)
  305. return id, nil
  306. }
  307. // runOwutUpgrade ejecuta `owut upgrade` y decide la transición. La muerte de
  308. // la sesión SSH tras >owutSSHMinRun es el final NORMAL del flash (el sysupgrade
  309. // reinicia el router); el resultado se confirma mirando el board info.
  310. func (s *server) runOwutUpgrade(id int64, routerID, host, target, origin string, removePkgs []string) {
  311. from := ""
  312. if s.boardVersionFn != nil {
  313. from = s.boardVersionFn(routerID)
  314. }
  315. cmd := firmware.OwutUpgradeCmd(target, from, removePkgs)
  316. _ = s.firmware.SetStatus(id, "running", "", "")
  317. // #761: antes de flashear, asegurar que el stack presente (netgrip /
  318. // agente) sobrevive al update (ASU no puede empaquetarlos: sin feed).
  319. if err := firmware.EnsureStackPreserved(s.pool, host); err != nil {
  320. log.Printf("[firmware] preserve-stack %s falló (continuo): %v", routerID, err)
  321. }
  322. start := time.Now()
  323. exit, out, err := firmware.RunOwutUpgrade(s.pool, host, cmd)
  324. dur := time.Since(start)
  325. switch {
  326. case err == nil && exit == 0 && strings.Contains(out, "no changes"):
  327. _ = s.firmware.SetStatus(id, "done", "sin cambios: ya estaba al día", "")
  328. case (err == nil && exit == 0) || (err != nil && dur >= owutSSHMinRun):
  329. s.awaitReboot(id, routerID, target, origin, from)
  330. default:
  331. msg := owutTail(out, err)
  332. if strings.TrimSpace(msg) == "" {
  333. msg = fmt.Sprintf("owut terminó sin salida (exit %d)", exit)
  334. }
  335. log.Printf("[firmware] owut upgrade %s falló (exit %d): %s", routerID, exit, msg)
  336. _ = s.firmware.SetStatus(id, "failed", msg, "")
  337. s.emitFirmwareResult(routerID, from, target, origin, false, msg)
  338. }
  339. }
  340. // runOwutInstallImage ejecuta `owut install` (flash de la imagen ya
  341. // descargada por owut-download, paso final de #1414). Igual semántica que
  342. // runOwutUpgrade: la muerte de la sesión SSH tras >owutSSHMinRun es el final
  343. // NORMAL del flash; el resultado se confirma mirando el board info.
  344. func (s *server) runOwutInstallImage(id int64, routerID, host, target string) {
  345. from := ""
  346. if s.boardVersionFn != nil {
  347. from = s.boardVersionFn(routerID)
  348. }
  349. _ = s.firmware.SetStatus(id, "running", "", "")
  350. if err := firmware.EnsureStackPreserved(s.pool, host); err != nil {
  351. log.Printf("[firmware] preserve-stack %s falló (continuo): %v", routerID, err)
  352. }
  353. start := time.Now()
  354. exit, out, err := firmware.RunOwutUpgrade(s.pool, host, firmware.OwutInstallCmd())
  355. dur := time.Since(start)
  356. switch {
  357. case err == nil && exit == 0:
  358. // owut install puede terminar sin reiniciar si no había imagen
  359. // descargada: no es un éxito, es un no-op que hay que decir.
  360. msg := strings.TrimSpace(out)
  361. if msg == "" {
  362. msg = "owut install terminó sin flashear (¿sin imagen descargada con owut download?)"
  363. }
  364. _ = s.firmware.SetStatus(id, "failed", msg, "")
  365. s.emitFirmwareResult(routerID, from, target, "manual", false, msg)
  366. case err != nil && dur >= owutSSHMinRun:
  367. s.awaitReboot(id, routerID, target, "manual", from)
  368. default:
  369. msg := owutTail(out, err)
  370. if strings.TrimSpace(msg) == "" {
  371. msg = fmt.Sprintf("owut install falló (exit %d)", exit)
  372. }
  373. log.Printf("[firmware] owut install %s falló (exit %d): %s", routerID, exit, msg)
  374. _ = s.firmware.SetStatus(id, "failed", msg, "")
  375. s.emitFirmwareResult(routerID, from, target, "manual", false, msg)
  376. }
  377. }
  378. // awaitReboot espera a que el router vuelva del sysupgrade y su board info
  379. // reporte la versión objetivo. Deadline: owutRebootGrace.
  380. func (s *server) awaitReboot(id int64, routerID, target, origin, from string) {
  381. _ = s.firmware.SetStatus(id, "rebooting", "", "")
  382. deadline := time.Now().Add(owutRebootGrace)
  383. for time.Now().Before(deadline) {
  384. time.Sleep(20 * time.Second)
  385. if v := s.detectedFirmwareVersion(routerID); v == target && target != "" {
  386. _ = s.firmware.SetStatus(id, "done", "", "")
  387. s.emitFirmwareResult(routerID, from, target, origin, true, "")
  388. return
  389. }
  390. }
  391. msg := "sin confirmación tras el reinicio (¿versión instalada distinta del objetivo?)"
  392. _ = s.firmware.SetStatus(id, "failed", msg, "")
  393. s.emitFirmwareResult(routerID, from, target, origin, false, msg)
  394. }
  395. // detectedFirmwareVersion: última versión reportada por el board info.
  396. func (s *server) detectedFirmwareVersion(routerID string) string {
  397. if s.adapter == nil {
  398. return ""
  399. }
  400. if bi := s.adapter.BoardInfoFor(routerID); bi != nil {
  401. return bi.Release.Version
  402. }
  403. return ""
  404. }
  405. // boardInfoFor expone el board info completo (tests y debug).
  406. func (s *server) boardInfoFor(routerID string) *adapters.BoardInfo {
  407. if s.adapter == nil {
  408. return nil
  409. }
  410. return s.adapter.BoardInfoFor(routerID)
  411. }
  412. // owutTail recorta la salida de owut para el campo error (últimas líneas).
  413. func owutTail(out string, err error) string {
  414. msg := strings.TrimSpace(out)
  415. if err != nil {
  416. if msg != "" {
  417. msg += "; "
  418. }
  419. msg += err.Error()
  420. }
  421. if len(msg) > 400 {
  422. msg = "..." + msg[len(msg)-400:]
  423. }
  424. return msg
  425. }
  426. // emitFirmwareResult notifica el resultado de un intento de upgrade (éxito o
  427. // fallo, manual o programado). Urgent para cruzar el Notifier (Telegram,
  428. // push, webhook); severity info/warn según resultado.
  429. func (s *server) emitFirmwareResult(routerID, from, to, origin string, ok bool, detail string) {
  430. if s.alertEmitter == nil {
  431. return
  432. }
  433. name := routerID
  434. if rt := s.routerName(routerID); rt != "" {
  435. name = rt
  436. }
  437. originTxt := "manual"
  438. if origin == "scheduled" {
  439. originTxt = "programado"
  440. }
  441. ev := alerts.AlertEvent{
  442. ID: fmt.Sprintf("alert-firmware-upgrade-%s-%d", routerID, time.Now().UnixMilli()),
  443. Category: alerts.CatSystem,
  444. Urgent: true,
  445. RouterID: routerID,
  446. Time: "just now",
  447. Ts: time.Now().Unix(),
  448. Vars: map[string]string{"router": name, "from": from, "to": to, "origin": originTxt},
  449. }
  450. if ok {
  451. ev.Severity = "info"
  452. ev.Type = "firmware-upgrade-done"
  453. ev.Title = "Firmware actualizado"
  454. ev.Description = fmt.Sprintf("%s: %s -> %s (owut, %s)", name, from, to, originTxt)
  455. } else {
  456. ev.Severity = "warn"
  457. ev.Type = "firmware-upgrade-failed"
  458. ev.Title = "Actualización de firmware fallida"
  459. ev.Description = fmt.Sprintf("%s: objetivo %s (owut, %s): %s", name, to, originTxt, detail)
  460. ev.Vars["detail"] = detail
  461. }
  462. s.alertEmitter.Emit(ev)
  463. }
  464. // emitFirmwareConfigAlert avisa de una recurrencia desactivada por config
  465. // inválida (sin target guardado, sin motor disponible).
  466. func (s *server) emitFirmwareConfigAlert(routerID, reason string) {
  467. if s.alertEmitter == nil {
  468. return
  469. }
  470. name := routerID
  471. if rt := s.routerName(routerID); rt != "" {
  472. name = rt
  473. }
  474. s.alertEmitter.Emit(alerts.AlertEvent{
  475. ID: fmt.Sprintf("alert-firmware-recurrence-%s-%d", routerID, time.Now().UnixMilli()),
  476. Category: alerts.CatSystem,
  477. Urgent: true,
  478. Severity: "warn",
  479. RouterID: routerID,
  480. Title: "Firmware schedule disabled",
  481. Description: fmt.Sprintf("%s: %s", name, reason),
  482. Time: "just now",
  483. Ts: time.Now().Unix(),
  484. })
  485. }
  486. // routerName resuelve el nombre visible del router (fallback: su ID).
  487. func (s *server) routerName(routerID string) string {
  488. if s.db == nil {
  489. return ""
  490. }
  491. for _, rt := range routerstore.ListRouters(s.db.DB) {
  492. if rt.ID == routerID {
  493. return rt.Name
  494. }
  495. }
  496. return ""
  497. }
  498. // --- Detección owut cacheada ---
  499. func (s *server) platform(routerID, host string) firmware.Platform {
  500. s.owutMu.Lock()
  501. defer s.owutMu.Unlock()
  502. if s.owutCache == nil {
  503. s.owutCache = map[string]platformCacheEntry{}
  504. }
  505. if e, ok := s.owutCache[routerID]; ok && time.Since(e.at) < owutDetectCacheTTL {
  506. return e.p
  507. }
  508. p := firmware.DetectPlatform(s.pool, host)
  509. s.owutCache[routerID] = platformCacheEntry{p: p, at: time.Now()}
  510. return p
  511. }
  512. func (s *server) invalidatePlatformCache(routerID string) {
  513. s.owutMu.Lock()
  514. defer s.owutMu.Unlock()
  515. delete(s.owutCache, routerID)
  516. }
  517. // --- Loop de recurrencia (#761) ---
  518. // firmwareRecurrenceLoop: tick corto; el vencimiento se deriva del last_run
  519. // persistido (reboot-safe). Solo en live (en demo no hay datos que actualizar).
  520. func (s *server) firmwareRecurrenceLoop(ctx context.Context, tickEvery time.Duration) {
  521. ticker := time.NewTicker(tickEvery)
  522. defer ticker.Stop()
  523. for {
  524. select {
  525. case <-ctx.Done():
  526. return
  527. case <-ticker.C:
  528. s.recurrenceTick()
  529. }
  530. }
  531. }
  532. func (s *server) recurrenceTick() {
  533. if s.db == nil || s.firmware == nil {
  534. return
  535. }
  536. now := time.Now()
  537. for _, rt := range routerstore.ListRouters(s.db.DB) {
  538. if !agentUpgradeable(rt.Type) {
  539. continue
  540. }
  541. rc := firmware.LoadRecurrence(s.db.DB, rt.ID)
  542. if !firmware.RecurrenceDue(rc, now) {
  543. continue
  544. }
  545. s.recMu.Lock()
  546. if s.recInFlight[rt.ID] {
  547. s.recMu.Unlock()
  548. continue
  549. }
  550. if s.recInFlight == nil {
  551. s.recInFlight = map[string]bool{}
  552. }
  553. s.recInFlight[rt.ID] = true
  554. s.recMu.Unlock()
  555. go func(id string) {
  556. defer func() {
  557. s.recMu.Lock()
  558. delete(s.recInFlight, id)
  559. s.recMu.Unlock()
  560. }()
  561. s.runRecurrenceShot(id)
  562. }(rt.ID)
  563. }
  564. }
  565. // runRecurrenceShot ejecuta un disparo vencido. Idempotente por contrato: si
  566. // la versión instalada ya coincide con el target, no-op silencioso; el
  567. // resultado real (éxito/fallo) se notifica desde la máquina de estados owut.
  568. func (s *server) runRecurrenceShot(routerID string) {
  569. target, err := s.firmware.GetTarget(routerID)
  570. if err != nil || target == nil || target.TargetVersion == "" {
  571. firmware.DisableRecurrence(s.db.DB, routerID)
  572. s.emitFirmwareConfigAlert(routerID, "no firmware target saved")
  573. return
  574. }
  575. current := ""
  576. if s.boardVersionFn != nil {
  577. current = s.boardVersionFn(routerID)
  578. }
  579. if current != "" && current == target.TargetVersion {
  580. // Al día: el disparo consume el slot sin flashear nada (#761).
  581. firmware.SetRecurrenceLastRun(s.db.DB, routerID, time.Now().UnixMilli())
  582. return
  583. }
  584. firmware.SetRecurrenceLastRun(s.db.DB, routerID, time.Now().UnixMilli())
  585. host := s.hostOfRouter(routerID)
  586. if host != "" && s.pool != nil {
  587. if plat := s.platform(routerID, host); plat.Vendor != "" {
  588. firmware.DisableRecurrence(s.db.DB, routerID)
  589. s.emitFirmwareConfigAlert(routerID, "router running vendor firmware (GL.iNet): its updates are managed by its own panel")
  590. return
  591. }
  592. }
  593. if host != "" && s.pool != nil && s.platform(routerID, host).Owut {
  594. if _, err := s.startOwutUpgrade(routerID, target.TargetVersion, "scheduled", nil); err != nil {
  595. s.emitFirmwareResult(routerID, current, target.TargetVersion, "scheduled", false, err.Error())
  596. }
  597. return
  598. }
  599. // Sin owut: motor clásico si hay imagen URL+checksum configurada.
  600. if target.TargetURL != "" && s.firmwareEngine != nil {
  601. if _, err := s.firmwareEngine.StartUpgrade(routerID); err != nil {
  602. s.emitFirmwareResult(routerID, current, target.TargetVersion, "scheduled", false, err.Error())
  603. }
  604. return
  605. }
  606. firmware.DisableRecurrence(s.db.DB, routerID)
  607. s.emitFirmwareConfigAlert(routerID, "router without owut and without an image URL for the classic engine")
  608. }