4
0

yield.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. // Package yield: ceder el paso a NetGrip (#369). El agente STANDALONE
  2. // (cmd/netpulse-agent) NO debe convivir con el agente embebido de NetGrip:
  3. // si ambos corren, pushean dos veces para el mismo slug. NetGrip ya detecta
  4. // y retira el standalone desde SU lado; este paquete es la protección
  5. // contraria: el standalone detecta NetGrip y se retira solo.
  6. //
  7. // Vive en agent/internal a propósito: el runtime (agent/runtime) lo comparten
  8. // el standalone y el agente embebido de NetGrip, y el sabor embebido NUNCA
  9. // debe ceder. Al ser internal, solo el módulo del agente puede importarlo:
  10. // NetGrip (otro módulo, que consume runtime) no tiene forma de llegar aquí
  11. // aunque quiera, y runtime no lo referencia (guardado por test de imports).
  12. package yield
  13. import (
  14. "context"
  15. "log/slog"
  16. "os"
  17. "os/exec"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "time"
  22. )
  23. // Interval por defecto del chequeo periódico.
  24. const Interval = 60 * time.Second
  25. // ReasonStartup / ReasonPeriodic: motivos que quedan anotados en el fichero
  26. // de estado y en los logs.
  27. const (
  28. ReasonStartup = "netgrip detected on this router at startup"
  29. ReasonPeriodic = "netgrip detected on this router (periodic check)"
  30. )
  31. // Paths: rutas que usa la detección y la cedida (inyectables en tests).
  32. type Paths struct {
  33. NetgripInit string // /etc/init.d/netgrip
  34. NetgripBin string // /usr/sbin/netgrip
  35. SelfInit string // /etc/init.d/netpulse-agent (propio; puede no existir)
  36. StateFile string // /tmp/netpulse-agent.yielded
  37. ProcRoot string // /proc (escaneo de procesos; "" = sin escanear)
  38. CronFile string // /etc/crontabs/root (línea del watchdog)
  39. }
  40. // DefaultPaths: rutas de producción en el router.
  41. func DefaultPaths() Paths {
  42. return Paths{
  43. NetgripInit: "/etc/init.d/netgrip",
  44. NetgripBin: "/usr/sbin/netgrip",
  45. SelfInit: "/etc/init.d/netpulse-agent",
  46. StateFile: "/tmp/netpulse-agent.yielded",
  47. ProcRoot: "/proc",
  48. CronFile: "/etc/crontabs/root",
  49. }
  50. }
  51. // runCmd inyectable (tests registran los comandos sin ejecutarlos).
  52. var runCmd = func(name string, args ...string) error {
  53. out, err := exec.Command(name, args...).CombinedOutput()
  54. if err != nil {
  55. slog.Warn("[netpulse-agent] yield cmd failed", "cmd", name, "err", err, "out", strings.TrimSpace(string(out)))
  56. }
  57. return err
  58. }
  59. // NetgripPresent: true si hay señales de NetGrip en este router: su init.d,
  60. // su binario o un proceso netgrip vivo. Barato: dos stat y, solo si ambos
  61. // fallan, un escaneo de /proc (nombres de proceso, sin tocar cmdline).
  62. func NetgripPresent(p Paths) bool {
  63. if fileExists(p.NetgripInit) || fileExists(p.NetgripBin) {
  64. return true
  65. }
  66. return procHasNetgrip(p.ProcRoot)
  67. }
  68. // procHasNetgrip escanea <procRoot>/*/comm buscando "netgrip" (comm trunca a
  69. // 15 chars; "netgrip" entra entero). procRoot vacío desactiva el escaneo.
  70. func procHasNetgrip(procRoot string) bool {
  71. if procRoot == "" {
  72. return false
  73. }
  74. entries, err := os.ReadDir(procRoot)
  75. if err != nil {
  76. return false
  77. }
  78. for _, e := range entries {
  79. if !e.IsDir() {
  80. continue
  81. }
  82. if _, err := strconv.Atoi(e.Name()); err != nil {
  83. continue
  84. }
  85. comm, err := os.ReadFile(filepath.Join(procRoot, e.Name(), "comm"))
  86. if err != nil {
  87. continue
  88. }
  89. if strings.TrimSpace(string(comm)) == "netgrip" {
  90. return true
  91. }
  92. }
  93. return false
  94. }
  95. // Yield ejecuta la cedida (idempotente y mejor esfuerzo):
  96. // 1. aviso claro en el log (visible en logread),
  97. // 2. fichero de estado con motivo y ts (para NetGrip o un humano),
  98. // 3. retira la línea del watchdog del crontab (si no, el cron relanza el
  99. // agente cada 2 min y la cedida no termina),
  100. // 4. disable + stop del propio init.d. El binario NO se autodesinstala:
  101. // los ficheros quedan (NetGrip los retira en su siguiente recheck, y un
  102. // humano puede re-activar el standalone si algún día se desinstala
  103. // NetGrip; el servicio queda disabled hasta entonces).
  104. //
  105. // cancel (opcional) se invoca al final para que el bucle principal del
  106. // agente devuelva el control si el stop de procd no nos mata antes.
  107. func Yield(p Paths, reason string, cancel func()) {
  108. slog.Warn("[netpulse-agent] netgrip detected: embedded netpulse agent takes over, stopping standalone")
  109. writeStateFile(p.StateFile, reason)
  110. removeCronWatchdog(p.CronFile)
  111. if fileExists(p.SelfInit) {
  112. _ = runCmd(p.SelfInit, "disable")
  113. _ = runCmd(p.SelfInit, "stop")
  114. }
  115. if cancel != nil {
  116. cancel()
  117. }
  118. }
  119. // writeStateFile: motivo + ts en dos líneas KEY=VALUE (tmpfs: muere al
  120. // reiniciar, que es cuando la detección volvería a evaluarse).
  121. func writeStateFile(path, reason string) {
  122. if path == "" {
  123. return
  124. }
  125. content := "yielded=1\nts=" + time.Now().UTC().Format(time.RFC3339) + "\nreason=" + reason + "\n"
  126. if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
  127. slog.Warn("[netpulse-agent] yield: state write failed", "file", path, "err", err)
  128. }
  129. }
  130. // removeCronWatchdog borra las líneas del watchdog del standalone del
  131. // crontab conservando el resto (mismo criterio que el cleanup de NetGrip).
  132. func removeCronWatchdog(path string) {
  133. if path == "" {
  134. return
  135. }
  136. data, err := os.ReadFile(path)
  137. if err != nil {
  138. return
  139. }
  140. var kept []string
  141. for _, line := range strings.Split(string(data), "\n") {
  142. if strings.Contains(line, "netpulse-watchdog") {
  143. continue
  144. }
  145. kept = append(kept, line)
  146. }
  147. out := strings.Join(kept, "\n")
  148. if out == string(data) {
  149. return
  150. }
  151. mode := os.FileMode(0o600)
  152. if st, err := os.Stat(path); err == nil {
  153. mode = st.Mode().Perm()
  154. }
  155. if err := os.WriteFile(path, []byte(out), mode); err != nil {
  156. slog.Warn("[netpulse-agent] yield: cron cleanup failed", "file", path, "err", err)
  157. }
  158. }
  159. // Watch: chequeo periódico de NetgripPresent. Al primer hallazgo ejecuta la
  160. // cedida y termina (no repite: el proceso o muere o su ctx se cancela).
  161. // Sin NetGrip no hace nada salvo volver a mirar cada every.
  162. func Watch(ctx context.Context, p Paths, every time.Duration, cancel func()) {
  163. if every <= 0 {
  164. every = Interval
  165. }
  166. t := time.NewTicker(every)
  167. defer t.Stop()
  168. for {
  169. select {
  170. case <-ctx.Done():
  171. return
  172. case <-t.C:
  173. if NetgripPresent(p) {
  174. Yield(p, ReasonPeriodic, cancel)
  175. return
  176. }
  177. }
  178. }
  179. }
  180. func fileExists(path string) bool {
  181. st, err := os.Stat(path)
  182. return err == nil && !st.IsDir()
  183. }