config_backup_schedule.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package httpapi
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "strconv"
  9. "time"
  10. "github.com/gnacho/netpulse/server-go/internal/adapters"
  11. "github.com/gnacho/netpulse/server-go/internal/auth"
  12. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  13. )
  14. // #1795: programación semanal del backup de configuración de los agentes.
  15. // El backup lo ejecuta cada agente al recibir config_backup y sube el
  16. // tar.gz resultante, así que el disparo solo alcanza agentes SSE conectados.
  17. const (
  18. configBackupScheduleTick = 30 * time.Second
  19. cfgBackupSchedulePrefix = "config_backup.schedule."
  20. )
  21. // ConfigBackupSchedule: día 0=domingo..6 y hora local HH:MM, igual que la
  22. // recurrencia de firmware.
  23. type ConfigBackupSchedule struct {
  24. Enabled bool `json:"enabled"`
  25. DayOfWeek int `json:"dayOfWeek"`
  26. Time string `json:"time"`
  27. LastRunMs int64 `json:"lastRunMs"`
  28. NextRunMs int64 `json:"nextRunMs,omitempty"`
  29. }
  30. func defaultConfigBackupSchedule() ConfigBackupSchedule {
  31. return ConfigBackupSchedule{DayOfWeek: 0, Time: "03:00"}
  32. }
  33. func (s *server) loadConfigBackupSchedule() ConfigBackupSchedule {
  34. sched := defaultConfigBackupSchedule()
  35. if s.db == nil {
  36. return sched
  37. }
  38. sched.Enabled = kvGetBool(s.db.DB, cfgBackupSchedulePrefix+"enabled")
  39. sched.DayOfWeek = kvGetInt(s.db.DB, cfgBackupSchedulePrefix+"day_of_week", 0)
  40. if v := kvGet(s.db.DB, cfgBackupSchedulePrefix+"time"); v != "" {
  41. sched.Time = v
  42. }
  43. if v := kvGet(s.db.DB, cfgBackupSchedulePrefix+"last_run_ms"); v != "" {
  44. sched.LastRunMs, _ = strconv.ParseInt(v, 10, 64)
  45. }
  46. if validateConfigBackupSchedule(sched) != nil {
  47. sched.Enabled = false
  48. sched.DayOfWeek = 0
  49. sched.Time = "03:00"
  50. }
  51. sched.NextRunMs = nextConfigBackupSchedule(sched.DayOfWeek, sched.Time, time.Now()).UnixMilli()
  52. return sched
  53. }
  54. func (s *server) saveConfigBackupSchedule(sched ConfigBackupSchedule) error {
  55. if s.db == nil {
  56. return fmt.Errorf("no_db")
  57. }
  58. if err := validateConfigBackupSchedule(sched); err != nil {
  59. return err
  60. }
  61. if err := kvSetBool(s.db.DB, cfgBackupSchedulePrefix+"enabled", sched.Enabled); err != nil {
  62. return err
  63. }
  64. if err := kvSetStr(s.db.DB, cfgBackupSchedulePrefix+"day_of_week", strconv.Itoa(sched.DayOfWeek)); err != nil {
  65. return err
  66. }
  67. if err := kvSetStr(s.db.DB, cfgBackupSchedulePrefix+"time", sched.Time); err != nil {
  68. return err
  69. }
  70. return kvSetStr(s.db.DB, cfgBackupSchedulePrefix+"last_run_ms", strconv.FormatInt(sched.LastRunMs, 10))
  71. }
  72. func validateConfigBackupSchedule(sched ConfigBackupSchedule) error {
  73. if sched.DayOfWeek < 0 || sched.DayOfWeek > 6 {
  74. return fmt.Errorf("dayOfWeek must be between 0 and 6")
  75. }
  76. parsed, err := time.Parse("15:04", sched.Time)
  77. if err != nil || parsed.Format("15:04") != sched.Time {
  78. return fmt.Errorf("time must be HH:MM")
  79. }
  80. return nil
  81. }
  82. // configBackupScheduleDue sigue el contrato de la recurrencia semanal de
  83. // firmware: solo el día elegido, con el slot ya alcanzado, y sin catch-up de
  84. // días perdidos.
  85. func configBackupScheduleDue(sched ConfigBackupSchedule, now time.Time) bool {
  86. if !sched.Enabled || int(now.Weekday()) != sched.DayOfWeek {
  87. return false
  88. }
  89. parsed, err := time.Parse("15:04", sched.Time)
  90. if err != nil {
  91. return false
  92. }
  93. slot := time.Date(now.Year(), now.Month(), now.Day(), parsed.Hour(), parsed.Minute(), 0, 0, now.Location())
  94. return !now.Before(slot) && sched.LastRunMs < slot.UnixMilli()
  95. }
  96. func nextConfigBackupSchedule(day int, clock string, now time.Time) time.Time {
  97. parsed, err := time.Parse("15:04", clock)
  98. if err != nil {
  99. parsed = time.Date(0, 1, 1, 3, 0, 0, 0, time.UTC)
  100. }
  101. days := (day - int(now.Weekday()) + 7) % 7
  102. next := time.Date(now.Year(), now.Month(), now.Day()+days, parsed.Hour(), parsed.Minute(), 0, 0, now.Location())
  103. if !next.After(now) {
  104. next = next.AddDate(0, 0, 7)
  105. }
  106. return next
  107. }
  108. func (s *server) registerConfigBackupScheduleRoutes(mux *http.ServeMux) {
  109. mux.Handle("GET /api/settings/config-backup-schedule", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  110. writeJSON(w, http.StatusOK, s.loadConfigBackupSchedule())
  111. })))
  112. mux.Handle("PUT /api/settings/config-backup-schedule", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  113. if s.db == nil {
  114. writeError(w, http.StatusServiceUnavailable, "no_db")
  115. return
  116. }
  117. var req ConfigBackupSchedule
  118. dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes))
  119. if err := dec.Decode(&req); err != nil {
  120. writeError(w, http.StatusBadRequest, "bad_request", "JSON inválido")
  121. return
  122. }
  123. if err := validateConfigBackupSchedule(req); err != nil {
  124. writeError(w, http.StatusBadRequest, "invalid_schedule", err.Error())
  125. return
  126. }
  127. prev := s.loadConfigBackupSchedule()
  128. req.LastRunMs = prev.LastRunMs
  129. // Al activar, el slot ya pasado no se ejecuta de inmediato. Si hoy
  130. // aún no ha llegado, last_run=ahora sigue siendo anterior al slot.
  131. if req.Enabled && !prev.Enabled {
  132. req.LastRunMs = time.Now().UnixMilli()
  133. }
  134. if err := s.saveConfigBackupSchedule(req); err != nil {
  135. writeError(w, http.StatusInternalServerError, "save_failed", err.Error())
  136. return
  137. }
  138. req.NextRunMs = nextConfigBackupSchedule(req.DayOfWeek, req.Time, time.Now()).UnixMilli()
  139. writeJSON(w, http.StatusOK, req)
  140. })))
  141. }
  142. func (s *server) configBackupScheduleLoop(ctx context.Context, tick time.Duration) {
  143. t := time.NewTicker(tick)
  144. defer t.Stop()
  145. for {
  146. select {
  147. case <-ctx.Done():
  148. return
  149. case <-t.C:
  150. s.configBackupScheduleTick()
  151. }
  152. }
  153. }
  154. func (s *server) configBackupScheduleTick() {
  155. s.configBackupScheduleTickAt(time.Now())
  156. }
  157. func (s *server) configBackupScheduleTickAt(now time.Time) {
  158. sched := s.loadConfigBackupSchedule()
  159. if !configBackupScheduleDue(sched, now) {
  160. return
  161. }
  162. servedByAgent := map[string]bool{}
  163. sent := 0
  164. if s.agentHub != nil {
  165. for _, slug := range s.agentHub.ConnectedSlugs() {
  166. if err := s.agentHub.SendPrivileged(slug, "config_backup", map[string]any{}); err != nil {
  167. log.Printf("[netpulse] scheduled config backup: %s: %v", slug, err)
  168. continue
  169. }
  170. servedByAgent[slug] = true
  171. // #2011: el backup del agente llega por HTTP unos segundos
  172. // después y no sabe de dónde salió. Se anota aquí para que su
  173. // línea del journal diga "scheduled" como la de la vía SSH.
  174. s.markScheduledAgentBackup(slug, now)
  175. sent++
  176. }
  177. }
  178. // #1924: las unidades sin agente se copian por SSH en el mismo tick, y
  179. // solo las que su agente no haya servido ya en este pase.
  180. sent += s.configBackupSshPass(now, servedByAgent)
  181. if sent == 0 {
  182. // Ninguna unidad copiada no quema el slot: se reintenta dentro de la
  183. // misma semana.
  184. return
  185. }
  186. lastRun := time.Now().UnixMilli()
  187. if err := kvSetStr(s.db.DB, cfgBackupSchedulePrefix+"last_run_ms", strconv.FormatInt(lastRun, 10)); err != nil {
  188. log.Printf("[netpulse] scheduled config backup: save last_run: %v", err)
  189. return
  190. }
  191. log.Printf("[netpulse] scheduled config backup: %d unit(s) backed up", sent)
  192. }
  193. // configBackupAgentWait: cuánto vale la marca de "backup programado pedido a
  194. // este agente" (#2011). El agente responde en segundos, pero una unidad lenta
  195. // puede tardar minutos en comprimir y subir. Pasada la ventana, una subida se
  196. // considera ad hoc: mejor eso que etiquetar de programada una copia manual
  197. // hecha media hora después.
  198. const configBackupAgentWait = 10 * time.Minute
  199. // markScheduledAgentBackup anota que el programador acaba de pedir a este
  200. // agente un backup, para que la subida se registre como programada (#2011).
  201. func (s *server) markScheduledAgentBackup(slug string, now time.Time) {
  202. s.cfgBackupAgentMu.Lock()
  203. defer s.cfgBackupAgentMu.Unlock()
  204. if s.cfgBackupAgentPending == nil {
  205. s.cfgBackupAgentPending = map[string]time.Time{}
  206. }
  207. for k, at := range s.cfgBackupAgentPending {
  208. if now.Sub(at) > configBackupAgentWait {
  209. delete(s.cfgBackupAgentPending, k)
  210. }
  211. }
  212. s.cfgBackupAgentPending[slug] = now
  213. }
  214. // takeScheduledAgentBackup devuelve true si la subida de este slug responde a
  215. // un backup programado, y consume la marca (una subida, un log). Una marca
  216. // más vieja que la ventana se descarta.
  217. func (s *server) takeScheduledAgentBackup(slug string, now time.Time) bool {
  218. s.cfgBackupAgentMu.Lock()
  219. defer s.cfgBackupAgentMu.Unlock()
  220. at, ok := s.cfgBackupAgentPending[slug]
  221. if !ok {
  222. return false
  223. }
  224. delete(s.cfgBackupAgentPending, slug)
  225. return now.Sub(at) <= configBackupAgentWait
  226. }
  227. // configBackupSshRetry: una unidad sin agente solo se intenta por SSH cada
  228. // este intervalo. El tick es de 30 s y un dial SSH puede tardar 120 s: sin
  229. // freno, una unidad caída recibiría un intento cada medio minuto, el ruido que
  230. // ya se reportó en #1893.
  231. const configBackupSshRetry = 10 * time.Minute
  232. // configBackupSshTargets: selección pura del pase SSH (#1924). Entra toda
  233. // unidad que se pueda copiar por SSH (OpenWrt con host) que no esté marcada
  234. // agent-only y que su agente no haya servido ya en este pase.
  235. func configBackupSshTargets(rows []adapters.RouterConfig, servedByAgent map[string]bool) []adapters.RouterConfig {
  236. out := make([]adapters.RouterConfig, 0, len(rows))
  237. for _, rc := range rows {
  238. if rc.AgentOnly || servedByAgent[rc.ID] || rc.Host == "" {
  239. continue
  240. }
  241. if !routerConfigBackupSshCapable(rc) {
  242. continue
  243. }
  244. out = append(out, rc)
  245. }
  246. return out
  247. }
  248. // cfgBackupSshAllowed aplica el freno entre pases SSH. Se marca el intento al
  249. // empezar: un pase lento o con unidades caídas tampoco reintenta enseguida.
  250. func (s *server) cfgBackupSshAllowed(now time.Time) bool {
  251. s.cfgBackupSshMu.Lock()
  252. defer s.cfgBackupSshMu.Unlock()
  253. if !s.lastCfgBackupSsh.IsZero() && now.Sub(s.lastCfgBackupSsh) < configBackupSshRetry {
  254. return false
  255. }
  256. s.lastCfgBackupSsh = now
  257. return true
  258. }
  259. // configBackupSshPass copia por SSH las unidades sin agente y devuelve cuántas
  260. // copias se guardaron. Una unidad que falle no aborta el resto: se registra y
  261. // se sigue con la siguiente.
  262. func (s *server) configBackupSshPass(now time.Time, servedByAgent map[string]bool) int {
  263. if s.db == nil || s.pool == nil {
  264. return 0
  265. }
  266. targets := configBackupSshTargets(routerstore.ListRouters(s.db.DB), servedByAgent)
  267. if len(targets) == 0 {
  268. return 0
  269. }
  270. if !s.cfgBackupSshAllowed(now) {
  271. log.Printf("[netpulse] scheduled config backup: %d unit(s) without agent waiting for SSH", len(targets))
  272. return 0
  273. }
  274. copied := 0
  275. for _, rc := range targets {
  276. label := rc.Name
  277. if label == "" {
  278. label = rc.ID
  279. }
  280. name, size, err := s.backupConfigOverSsh(context.Background(), rc.ID, rc.SSHAddr())
  281. if err != nil {
  282. log.Printf("[netpulse] scheduled config backup: %s: %v", label, err)
  283. continue
  284. }
  285. copied++
  286. log.Printf("[netpulse] scheduled config backup: %s: SSH backup %s (%d bytes)", label, name, size)
  287. }
  288. return copied
  289. }