heartbeat.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Package heartbeat — Fase 5 (resiliencia del agente): el agente toca un
  2. // fichero en /tmp (RAM, nada en NAND) tras cada push CONFIRMADO por el
  3. // servidor. El watchdog cron del router (agent/deploy/watchdog.sh) usa la
  4. // edad de ese fichero para distinguir "proceso vivo y empujando" de
  5. // "proceso vivo pero roto" (vivo sin latido → reinicio del servicio).
  6. //
  7. // Diseño: stateless, sin dependencias, tolerante a cualquier fallo — un
  8. // error de heartbeat NUNCA puede afectar al ciclo de push.
  9. package heartbeat
  10. import (
  11. "bytes"
  12. "os"
  13. "path/filepath"
  14. "strconv"
  15. "time"
  16. )
  17. // DefaultFile: latido por defecto en tmpfs (se pierde al reiniciar el
  18. // router, que es lo correcto: tras un reboot el watchdog ve "sin fichero" y
  19. // no hace nada porque el agente aún no ha tenido tiempo de empujar).
  20. const DefaultFile = "/tmp/netpulse-agent.heartbeat"
  21. // Touch escribe el unix actual en el fichero de heartbeat. Nunca devuelve
  22. // error: el caller (main del agente) lo ignora deliberadamente.
  23. func Touch(path string, now time.Time) error {
  24. if path == "" {
  25. path = DefaultFile
  26. }
  27. _ = os.MkdirAll(filepath.Dir(path), 0o755)
  28. return os.WriteFile(path, []byte(strconv.FormatInt(now.Unix(), 10)+"\n"), 0o644)
  29. }
  30. // Age: segundos desde el último latido; (0, false) si el fichero no existe
  31. // o es ilegible (agente recién instalado / reboot reciente → el watchdog no
  32. // debe actuar por ausencia de fichero, solo por latido viejo CON fichero).
  33. func Age(path string, now time.Time) (time.Duration, bool) {
  34. data, err := os.ReadFile(path)
  35. if err != nil {
  36. return 0, false
  37. }
  38. ts, err := strconv.ParseInt(string(bytes.TrimSpace(data)), 10, 64)
  39. if err != nil || ts <= 0 {
  40. return 0, false
  41. }
  42. age := now.Sub(time.Unix(ts, 0))
  43. if age < 0 {
  44. age = 0
  45. }
  46. return age, true
  47. }