config_backup_2011_test.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package httpapi
  2. // #2011: el backup de config hecho por el agente se registraba como
  3. // "config backup" aunque lo hubiera pedido el programador, mientras la vía SSH
  4. // decía "scheduled config backup". Un script que cuenta las líneas programadas
  5. // se quedaba corto con las unidades que llevan agente. El tick anota la unidad
  6. // al pedir el backup y la subida consume la marca para elegir el prefijo.
  7. import (
  8. "bytes"
  9. "context"
  10. "log"
  11. "net/http"
  12. "net/http/httptest"
  13. "path/filepath"
  14. "strings"
  15. "testing"
  16. "time"
  17. "github.com/gnacho/netpulse/server-go/internal/db"
  18. "github.com/gnacho/netpulse/server-go/internal/firmware"
  19. "github.com/gnacho/netpulse/server-go/internal/sse"
  20. )
  21. const backup2011Slug = "ap1"
  22. // newBackup2011Server monta el server con un agente conectado por SSE, que es
  23. // lo que el tick necesita para pedirle el backup. Devuelve el server, el token
  24. // del agente y el techo del stream.
  25. func newBackup2011Server(t *testing.T) (*server, string) {
  26. t.Helper()
  27. d, err := db.Open(filepath.Join(t.TempDir(), "test.db"))
  28. if err != nil {
  29. t.Fatalf("db.Open: %v", err)
  30. }
  31. t.Cleanup(func() { _ = d.Close() })
  32. token := "agent-secret-2011"
  33. if _, err := d.Exec(
  34. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`,
  35. agentTokenKey(backup2011Slug), hashAgentToken(token)); err != nil {
  36. t.Fatalf("token: %v", err)
  37. }
  38. hub := sse.NewAgentHub(func(slug, tok string) bool {
  39. return slug == backup2011Slug && tok == token
  40. })
  41. hub.SetAllowInsecureCommands(true)
  42. s := &server{db: d, agentHub: hub, firmware: firmware.NewStore(d.DB)}
  43. ctx, cancel := context.WithCancel(context.Background())
  44. req := httptest.NewRequest(http.MethodGet, "/api/agents/"+backup2011Slug+"/stream", nil).WithContext(ctx)
  45. req.SetPathValue("slug", backup2011Slug)
  46. req.Header.Set("Authorization", "Bearer "+token)
  47. rec := httptest.NewRecorder()
  48. go hub.HandleStream(rec, req)
  49. t.Cleanup(cancel)
  50. deadline := time.Now().Add(3 * time.Second)
  51. for time.Now().Before(deadline) && len(hub.ConnectedSlugs()) == 0 {
  52. time.Sleep(20 * time.Millisecond)
  53. }
  54. if len(hub.ConnectedSlugs()) == 0 {
  55. t.Fatal("el agente no llegó a conectarse al stream")
  56. }
  57. return s, token
  58. }
  59. // runScheduledTick fuerza un tick que vence ahora.
  60. func runScheduledTick(t *testing.T, s *server, now time.Time) {
  61. t.Helper()
  62. sched := ConfigBackupSchedule{Enabled: true, DayOfWeek: int(now.Weekday()), Time: "00:00"}
  63. if err := s.saveConfigBackupSchedule(sched); err != nil {
  64. t.Fatalf("save schedule: %v", err)
  65. }
  66. s.configBackupScheduleTickAt(now)
  67. }
  68. // uploadAgentBackup simula la subida del agente y devuelve lo que fue al
  69. // journal.
  70. func uploadAgentBackup(t *testing.T, s *server, token string) string {
  71. t.Helper()
  72. mux := http.NewServeMux()
  73. s.registerFirmwareBackupRoutes(mux)
  74. var buf bytes.Buffer
  75. prev := log.Writer()
  76. log.SetOutput(&buf)
  77. defer log.SetOutput(prev)
  78. req := httptest.NewRequest(http.MethodPost, "/api/agents/"+backup2011Slug+"/firmware-backup",
  79. strings.NewReader("\x1f\x8btar-gz-de-prueba"))
  80. req.Header.Set("Authorization", "Bearer "+token)
  81. rec := httptest.NewRecorder()
  82. mux.ServeHTTP(rec, req)
  83. if rec.Code != http.StatusOK {
  84. t.Fatalf("subida: status = %d, body = %s", rec.Code, rec.Body.String())
  85. }
  86. return buf.String()
  87. }
  88. func TestAgentBackupAfterScheduledTickLogsScheduled(t *testing.T) {
  89. s, token := newBackup2011Server(t)
  90. now := time.Now()
  91. runScheduledTick(t, s, now)
  92. line := uploadAgentBackup(t, s, token)
  93. if !strings.Contains(line, "[netpulse] scheduled config backup: "+backup2011Slug+": agent backup") {
  94. t.Fatalf("la subida pedida por el programador no se registró como programada: %q", line)
  95. }
  96. }
  97. func TestAgentBackupWithoutTickLogsAdHoc(t *testing.T) {
  98. s, token := newBackup2011Server(t)
  99. line := uploadAgentBackup(t, s, token)
  100. if strings.Contains(line, "scheduled config backup") {
  101. t.Fatalf("un backup manual no puede salir como programado: %q", line)
  102. }
  103. if !strings.Contains(line, "[netpulse] config backup: "+backup2011Slug+": agent backup") {
  104. t.Fatalf("falta la línea del backup ad hoc: %q", line)
  105. }
  106. }
  107. func TestScheduledAgentMarkIsConsumedOnce(t *testing.T) {
  108. s, _ := newBackup2011Server(t)
  109. now := time.Now()
  110. s.markScheduledAgentBackup(backup2011Slug, now)
  111. if !s.takeScheduledAgentBackup(backup2011Slug, now.Add(time.Minute)) {
  112. t.Fatal("la marca debe valer dentro de la ventana")
  113. }
  114. if s.takeScheduledAgentBackup(backup2011Slug, now.Add(2*time.Minute)) {
  115. t.Fatal("la marca se consume con la primera subida")
  116. }
  117. }
  118. func TestScheduledAgentMarkExpires(t *testing.T) {
  119. s, _ := newBackup2011Server(t)
  120. now := time.Now()
  121. s.markScheduledAgentBackup(backup2011Slug, now)
  122. // Pasada la ventana, una subida es ad hoc: no puede heredar el prefijo de
  123. // una petición programada de hace media hora.
  124. if s.takeScheduledAgentBackup(backup2011Slug, now.Add(configBackupAgentWait+time.Minute)) {
  125. t.Fatal("una marca vieja no debe etiquetar la subida como programada")
  126. }
  127. s.cfgBackupAgentMu.Lock()
  128. pending := len(s.cfgBackupAgentPending)
  129. s.cfgBackupAgentMu.Unlock()
  130. if pending != 0 {
  131. t.Fatalf("quedaron %d marcas sin limpiar", pending)
  132. }
  133. }