autosched.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // autosched.go - auto-actualización programada del propio server (#759).
  2. //
  3. // Off por defecto (opt-in explícito del admin). Patrón de backups (#741),
  4. // speedtest (#744) y firmware (#761): ajustes en kv, vencimiento derivado
  5. // del last_run PERSISTIDO (reinicios y el propio update no resetean el
  6. // reloj) y single-flight. El disparo: Check y, solo si hay novedad fresca y
  7. // el layout puede aplicar, ApplyBy("scheduled"): binario únicamente, con la
  8. // verificación de salud y el rollback del helper root de #480. El last_run
  9. // se persiste ANTES de actuar: el apply reinicia el proceso y el arranque
  10. // posterior no debe volver a disparar el mismo slot.
  11. package updater
  12. import (
  13. "context"
  14. "database/sql"
  15. "fmt"
  16. "log"
  17. "strconv"
  18. "sync/atomic"
  19. "time"
  20. "github.com/gnacho/netpulse/server-go/internal/alerts"
  21. )
  22. // Kinds de programación del auto-update.
  23. const (
  24. AutoDaily = "daily"
  25. AutoWeekly = "weekly"
  26. AutoMonthly = "monthly"
  27. )
  28. // AutoUpdateSettings persistidas en kv (claves settings.autoupdate.*).
  29. type AutoUpdateSettings struct {
  30. Enabled bool `json:"enabled"`
  31. Kind string `json:"kind"` // daily | weekly | monthly
  32. Time string `json:"time"` // "HH:MM" hora local
  33. // DayOfWeek 0=domingo..6 (weekly); DayOfMonth 1..31 con clamp (monthly).
  34. DayOfWeek *int `json:"dayOfWeek,omitempty"`
  35. DayOfMonth *int `json:"dayOfMonth,omitempty"`
  36. }
  37. // LastRunMs / LastResult viajan aparte (no los escribe el PUT).
  38. type autoRunState struct {
  39. LastRunMs int64 `json:"lastRunMs,omitempty"`
  40. LastResult string `json:"lastResult,omitempty"` // "" | applied | up-to-date | check-failed | cannot-apply
  41. }
  42. // CheckerApplier es lo que el scheduler necesita del updater (lo satisface
  43. // *Updater; fakes en tests).
  44. type CheckerApplier interface {
  45. Check(ctx context.Context) Status
  46. CanApply() bool
  47. ApplyBy(initiatedBy string) bool
  48. }
  49. // AlertEmitter lo cumple *alerts.Engine (nil = sin alertas, p. ej. tests).
  50. type AlertEmitter interface {
  51. Emit(ev alerts.AlertEvent) bool
  52. }
  53. // Scheduler ejecuta el auto-update programado.
  54. type Scheduler struct {
  55. db *sql.DB
  56. ua CheckerApplier
  57. emit AlertEmitter
  58. now func() time.Time
  59. logf func(format string, args ...any)
  60. running atomic.Bool
  61. }
  62. // NewScheduler construye el scheduler (Start lo arranca como daemon).
  63. func NewScheduler(db *sql.DB, ua CheckerApplier) *Scheduler {
  64. return &Scheduler{
  65. db: db,
  66. ua: ua,
  67. now: time.Now,
  68. logf: func(f string, a ...any) {
  69. log.Printf("[netpulse:autoupdate] "+f, a...)
  70. },
  71. }
  72. }
  73. // SetAlertEmitter fija el motor de alertas (llamado tras construir el
  74. // adapter live en main).
  75. func (s *Scheduler) SetAlertEmitter(e AlertEmitter) { s.emit = e }
  76. // Start lanza el bucle periódico (daemon; no retorna).
  77. func (s *Scheduler) Start() {
  78. ticker := time.NewTicker(time.Minute)
  79. defer ticker.Stop()
  80. for range ticker.C {
  81. s.tick()
  82. }
  83. }
  84. func (s *Scheduler) tick() {
  85. if s.db == nil || s.ua == nil {
  86. return
  87. }
  88. st := LoadAutoUpdateSettings(s.db)
  89. state := loadAutoRunState(s.db)
  90. if !AutoUpdateDue(st, state.LastRunMs, s.now()) {
  91. return
  92. }
  93. if !s.running.CompareAndSwap(false, true) {
  94. return
  95. }
  96. go func() {
  97. defer s.running.Store(false)
  98. s.shot(st, state)
  99. }()
  100. }
  101. // shot ejecuta un disparo vencido: marca el slot, comprueba y aplica si
  102. // procede. El resultado queda en kv (UI) y en el historial del updater.
  103. func (s *Scheduler) shot(st AutoUpdateSettings, prev autoRunState) {
  104. nowMs := s.now().UnixMilli()
  105. setAutoKv(s.db, "last_run", strconv.FormatInt(nowMs, 10))
  106. status := s.ua.Check(context.Background())
  107. switch {
  108. case status.CheckFailed:
  109. saveAutoResult(s.db, "check-failed")
  110. s.alert(false, "check-failed", fmt.Sprintf("Update check failed (reason: %s); it will retry on the next scheduled run", status.CheckErr), map[string]string{"reason": status.CheckErr})
  111. case !status.UpdateAvailable:
  112. saveAutoResult(s.db, "up-to-date")
  113. case !status.CanApply:
  114. // Readiness o layout sin apply: se avisa (hay novedad esperando y no
  115. // se podrá aplicar hasta que el admin lo resuelva).
  116. saveAutoResult(s.db, "cannot-apply")
  117. s.alert(false, "cannot-apply", "An update is available but this install cannot apply it now (check readiness in Settings)", nil)
  118. default:
  119. saveAutoResult(s.db, "applied")
  120. if s.ua.ApplyBy("scheduled") {
  121. s.alert(true, "applied", fmt.Sprintf("Scheduled update started: %s (binary only, with health verification and automatic rollback)", statusLatestDeref(status)), map[string]string{"version": statusLatestDeref(status)})
  122. } else {
  123. s.alert(false, "apply-busy", "The scheduled update could not start (another update in progress?)", nil)
  124. }
  125. }
  126. }
  127. // alert emite la notificación del disparo (info en éxito, warn en aviso).
  128. // result es el código estable que el frontend usa para elegir la traducción
  129. // (alerts.types.autoupdate.results.<result>); desc is the English
  130. // literal, fallback when no catalog covers the type (#796, #1014).
  131. func (s *Scheduler) alert(ok bool, result, desc string, extra map[string]string) {
  132. s.logf("%s", desc)
  133. if s.emit == nil {
  134. return
  135. }
  136. sev := "warn"
  137. if ok {
  138. sev = "info"
  139. }
  140. vars := map[string]string{"result": result, "detail": desc}
  141. for k, v := range extra {
  142. vars[k] = v
  143. }
  144. s.emit.Emit(alerts.AlertEvent{
  145. ID: fmt.Sprintf("alert-autoupdate-%d", s.now().UnixMilli()),
  146. Category: alerts.CatSystem,
  147. Urgent: true,
  148. Severity: sev,
  149. Title: "Scheduled auto-update",
  150. Description: desc,
  151. Time: "just now",
  152. Ts: s.now().Unix(),
  153. Type: "autoupdate",
  154. Vars: vars,
  155. })
  156. }
  157. // --- Validación y due (funciones puras) ---
  158. // ValidateAutoUpdate comprueba la coherencia kind/campos.
  159. func ValidateAutoUpdate(st AutoUpdateSettings) error {
  160. switch st.Kind {
  161. case AutoDaily:
  162. if !validAutoTime(st.Time) {
  163. return fmt.Errorf("daily exige time HH:MM")
  164. }
  165. case AutoWeekly:
  166. if st.DayOfWeek == nil || *st.DayOfWeek < 0 || *st.DayOfWeek > 6 {
  167. return fmt.Errorf("weekly requires dayOfWeek 0-6 (0 = Sunday)")
  168. }
  169. if !validAutoTime(st.Time) {
  170. return fmt.Errorf("weekly requires time HH:MM")
  171. }
  172. case AutoMonthly:
  173. if st.DayOfMonth == nil || *st.DayOfMonth < 1 || *st.DayOfMonth > 31 {
  174. return fmt.Errorf("monthly requires dayOfMonth 1-31")
  175. }
  176. if !validAutoTime(st.Time) {
  177. return fmt.Errorf("monthly requires time HH:MM")
  178. }
  179. default:
  180. return fmt.Errorf("kind must be daily, weekly or monthly")
  181. }
  182. return nil
  183. }
  184. // AutoUpdateDue decide si toca disparar (función pura, patrón #761).
  185. func AutoUpdateDue(st AutoUpdateSettings, lastRunMs int64, now time.Time) bool {
  186. if !st.Enabled {
  187. return false
  188. }
  189. switch st.Kind {
  190. case AutoDaily:
  191. slot := autoTodaySlot(st.Time, now)
  192. return !now.Before(slot) && lastRunMs < slot.UnixMilli()
  193. case AutoWeekly:
  194. dow := 0
  195. if st.DayOfWeek != nil {
  196. dow = *st.DayOfWeek
  197. }
  198. if int(now.Weekday()) != dow {
  199. return false
  200. }
  201. slot := autoTodaySlot(st.Time, now)
  202. return !now.Before(slot) && lastRunMs < slot.UnixMilli()
  203. case AutoMonthly:
  204. dom := 1
  205. if st.DayOfMonth != nil {
  206. dom = *st.DayOfMonth
  207. }
  208. h, m := autoParseTime(st.Time)
  209. slot := time.Date(now.Year(), now.Month(), autoClampDay(dom, now), h, m, 0, 0, now.Location())
  210. return !now.Before(slot) && lastRunMs < slot.UnixMilli()
  211. }
  212. return false
  213. }
  214. // NextAutoUpdateAt calcula el próximo disparo para la UI.
  215. func NextAutoUpdateAt(st AutoUpdateSettings, lastRunMs int64, now time.Time) time.Time {
  216. h, m := autoParseTime(st.Time)
  217. switch st.Kind {
  218. case AutoDaily:
  219. slot := autoTodaySlot(st.Time, now)
  220. if now.Before(slot) || lastRunMs < slot.UnixMilli() {
  221. return slot
  222. }
  223. return slot.AddDate(0, 0, 1)
  224. case AutoWeekly:
  225. dow := 0
  226. if st.DayOfWeek != nil {
  227. dow = *st.DayOfWeek
  228. }
  229. today := autoTodaySlot(st.Time, now)
  230. if int(now.Weekday()) == dow && (now.Before(today) || lastRunMs < today.UnixMilli()) {
  231. return today
  232. }
  233. days := (dow - int(now.Weekday()) + 7) % 7
  234. if days == 0 {
  235. days = 7
  236. }
  237. d := now.AddDate(0, 0, days)
  238. return time.Date(d.Year(), d.Month(), d.Day(), h, m, 0, 0, now.Location())
  239. case AutoMonthly:
  240. dom := 1
  241. if st.DayOfMonth != nil {
  242. dom = *st.DayOfMonth
  243. }
  244. slot := time.Date(now.Year(), now.Month(), autoClampDay(dom, now), h, m, 0, 0, now.Location())
  245. if now.Before(slot) || lastRunMs < slot.UnixMilli() {
  246. return slot
  247. }
  248. next := now.AddDate(0, 1, 0)
  249. return time.Date(next.Year(), next.Month(), autoClampDay(dom, next), h, m, 0, 0, now.Location())
  250. }
  251. return time.Time{}
  252. }
  253. // --- Persistencia kv ---
  254. const autoKvPrefix = "settings.autoupdate."
  255. // LoadAutoUpdateSettings lee los ajustes (defaults sanos).
  256. func LoadAutoUpdateSettings(db *sql.DB) AutoUpdateSettings {
  257. st := AutoUpdateSettings{}
  258. if db == nil {
  259. return st
  260. }
  261. st.Enabled = autoKVGet(db, "enabled") == "1"
  262. if k := autoKVGet(db, "kind"); validAutoKind(k) {
  263. st.Kind = k
  264. }
  265. st.Time = autoKVGet(db, "time")
  266. if v, ok := autoKVIntPtr(db, "dow"); ok {
  267. st.DayOfWeek = v
  268. }
  269. if v, ok := autoKVIntPtr(db, "dom"); ok {
  270. st.DayOfMonth = v
  271. }
  272. return st
  273. }
  274. // SaveAutoUpdateSettings valida y persiste los ajustes (sin tocar last_run).
  275. func SaveAutoUpdateSettings(db *sql.DB, st AutoUpdateSettings) error {
  276. if db == nil {
  277. return fmt.Errorf("autoupdate: no database")
  278. }
  279. if err := ValidateAutoUpdate(st); err != nil {
  280. return err
  281. }
  282. setAutoKv(db, "enabled", autoBoolStr(st.Enabled))
  283. setAutoKv(db, "kind", st.Kind)
  284. setAutoKv(db, "time", st.Time)
  285. dow, dom := "", ""
  286. if st.DayOfWeek != nil {
  287. dow = strconv.Itoa(*st.DayOfWeek)
  288. }
  289. if st.DayOfMonth != nil {
  290. dom = strconv.Itoa(*st.DayOfMonth)
  291. }
  292. setAutoKv(db, "dow", dow)
  293. setAutoKv(db, "dom", dom)
  294. return nil
  295. }
  296. func loadAutoRunState(db *sql.DB) autoRunState {
  297. return autoRunState{
  298. LastRunMs: autoKVParseInt(db, "last_run"),
  299. LastResult: autoKVGet(db, "last_result"),
  300. }
  301. }
  302. // AutoRunState expone el estado del último disparo (para la UI).
  303. func AutoRunState(db *sql.DB) (int64, string) {
  304. st := loadAutoRunState(db)
  305. return st.LastRunMs, st.LastResult
  306. }
  307. func saveAutoResult(db *sql.DB, result string) {
  308. setAutoKv(db, "last_result", result)
  309. }
  310. // --- helpers locales (patrón speedtest/firmware) ---
  311. func validAutoKind(v string) bool {
  312. return v == AutoDaily || v == AutoWeekly || v == AutoMonthly
  313. }
  314. func validAutoTime(v string) bool {
  315. if v == "" {
  316. return false
  317. }
  318. _, err := time.Parse("15:04", v)
  319. return err == nil
  320. }
  321. func autoParseTime(v string) (int, int) {
  322. t, err := time.Parse("15:04", v)
  323. if err != nil {
  324. return 0, 0
  325. }
  326. return t.Hour(), t.Minute()
  327. }
  328. func autoTodaySlot(v string, now time.Time) time.Time {
  329. h, m := autoParseTime(v)
  330. return time.Date(now.Year(), now.Month(), now.Day(), h, m, 0, 0, now.Location())
  331. }
  332. func autoDaysInMonth(t time.Time) int {
  333. return time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, t.Location()).Day()
  334. }
  335. func autoClampDay(dom int, t time.Time) int {
  336. if dom < 1 {
  337. dom = 1
  338. }
  339. if max := autoDaysInMonth(t); dom > max {
  340. dom = max
  341. }
  342. return dom
  343. }
  344. func autoBoolStr(b bool) string {
  345. if b {
  346. return "1"
  347. }
  348. return "0"
  349. }
  350. func autoKVGet(db *sql.DB, key string) string {
  351. var v string
  352. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", autoKvPrefix+key).Scan(&v); err != nil {
  353. return ""
  354. }
  355. return v
  356. }
  357. func autoKVParseInt(db *sql.DB, key string) int64 {
  358. n, _ := strconv.ParseInt(autoKVGet(db, key), 10, 64)
  359. return n
  360. }
  361. func autoKVIntPtr(db *sql.DB, key string) (*int, bool) {
  362. raw := autoKVGet(db, key)
  363. if raw == "" {
  364. return nil, false
  365. }
  366. n, err := strconv.Atoi(raw)
  367. if err != nil {
  368. return nil, false
  369. }
  370. return &n, true
  371. }
  372. func setAutoKv(db *sql.DB, key, val string) {
  373. if _, err := db.Exec(
  374. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  375. autoKvPrefix+key, val); err != nil {
  376. log.Printf("[netpulse:autoupdate] kv set %s: %v", key, err)
  377. }
  378. }
  379. // LatestDeref devuelve status.Latest sin nil-panic (para mensajes).
  380. func statusLatestDeref(s Status) string {
  381. if s.Latest != nil {
  382. return *s.Latest
  383. }
  384. return "?"
  385. }