config_backup_2011_test.go 5.1 KB

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