migrate_node.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // migrate_node.go — MIGRACIÓN desde el backend Node (SPEC §12, corazón del
  2. // refactor). El esquema Go es idéntico al de Node (mismo SQL literal), así
  3. // que la "importación" es preservación in situ:
  4. //
  5. // 1. Detección: el fichero existe y tiene las tablas firma de Node
  6. // (users, sessions, kv) sin el marcador de migración ya aplicada.
  7. // 2. Backup atómico (checkpoint TRUNCATE + copia a fichero temporal +
  8. // rename) ANTES de tocar nada: netpulse.db.bak-<timestamp>.
  9. // 3. Importación preservando: users (hashes bcrypt $2a/$2b portables),
  10. // kv COMPLETO (session_secret incluido → las sesiones vivas siguen
  11. // válidas, SIN forzar re-login), sessions vivas, routers (routerstore
  12. // persiste en la propia tabla routers de SQLite — nada externo que
  13. // importar), device_attrib, metrics/adguard_stats (epochs en MS, no se
  14. // tocan), y login_attempts RESETEADO (efímero).
  15. // 4. Log claro de qué se importó y cuántas filas.
  16. //
  17. // El marcador kv `go_migration` evita re-migrar en cada arranque (repetir el
  18. // reset de login_attempts rompería la persistencia del rate-limit, que en
  19. // Node sobrevive a reinicios). Es un detalle interno no observable por la API.
  20. package db
  21. import (
  22. "database/sql"
  23. "fmt"
  24. "io"
  25. "log"
  26. "os"
  27. "time"
  28. )
  29. // migrationMarkerKey es la clave kv que marca la migración ya hecha.
  30. const migrationMarkerKey = "go_migration"
  31. // MigrationReport resume lo importado (para el log de arranque).
  32. type MigrationReport struct {
  33. BackupPath string
  34. Users int
  35. Sessions int // vivas (expires_at > ahora)
  36. KV int
  37. Routers int
  38. DeviceAttrib int
  39. Metrics int
  40. AdguardStats int
  41. LoginAttemptsReset int
  42. }
  43. // Log emite el resumen de migración (formato [netpulse] …).
  44. func (r *MigrationReport) Log() {
  45. log.Printf("[netpulse] Node→Go migration: backup at %s", r.BackupPath)
  46. log.Printf("[netpulse] Node→Go migration: imported users=%d live_sessions=%d kv=%d routers=%d device_attrib=%d metrics=%d adguard_stats=%d · login_attempts reset (%d rows)",
  47. r.Users, r.Sessions, r.KV, r.Routers, r.DeviceAttrib, r.Metrics, r.AdguardStats, r.LoginAttemptsReset)
  48. }
  49. // MigrateNodeDB inspecciona dbPath y, si es una DB Node sin migrar, hace
  50. // backup y la importa. Devuelve nil si no hay nada que migrar (instalación
  51. // nueva o migración ya aplicada).
  52. func MigrateNodeDB(dbPath string) (*MigrationReport, error) {
  53. st, err := os.Stat(dbPath)
  54. if err != nil || st.Size() == 0 {
  55. return nil, nil // instalación nueva
  56. }
  57. sqldb, err := sql.Open("sqlite", dbPath+"?_pragma=busy_timeout(5000)")
  58. if err != nil {
  59. return nil, err
  60. }
  61. defer sqldb.Close()
  62. sqldb.SetMaxOpenConns(1)
  63. // Detección del esquema Node: tablas firma presentes.
  64. if !hasTable(sqldb, "users") || !hasTable(sqldb, "sessions") || !hasTable(sqldb, "kv") {
  65. log.Printf("[netpulse] warning: %s exists but does not look like a NetPulse DB, continuing without migration", dbPath)
  66. return nil, nil
  67. }
  68. // ¿Ya migrada?
  69. var marker string
  70. if err := sqldb.QueryRow("SELECT value FROM kv WHERE key = ?", migrationMarkerKey).Scan(&marker); err == nil && marker != "" {
  71. return nil, nil
  72. }
  73. // 1) Consolida el WAL en el fichero principal y cierra antes de copiar.
  74. if _, err := sqldb.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
  75. return nil, fmt.Errorf("checkpoint pre-backup: %w", err)
  76. }
  77. // 2) Backup atómico: copia a temporal + rename, ANTES de modificar la DB.
  78. ts := time.Now().Format("20060102-150405")
  79. backupPath := fmt.Sprintf("%s.bak-%s", dbPath, ts)
  80. if err := atomicCopy(dbPath, backupPath); err != nil {
  81. return nil, fmt.Errorf("backup: %w", err)
  82. }
  83. rep := &MigrationReport{BackupPath: backupPath}
  84. // 3) Conteos para el log (qué se importa y cuántas filas).
  85. rep.Users = countRows(sqldb, "users")
  86. rep.Sessions = countWhere(sqldb, "sessions", "expires_at > ?", NowMS())
  87. rep.KV = countRows(sqldb, "kv")
  88. rep.Routers = countRows(sqldb, "routers")
  89. rep.DeviceAttrib = countRows(sqldb, "device_attrib")
  90. rep.Metrics = countRows(sqldb, "metrics")
  91. rep.AdguardStats = countRows(sqldb, "adguard_stats")
  92. // 4) login_attempts es efímero: se resetea.
  93. res, err := sqldb.Exec("DELETE FROM login_attempts")
  94. if err == nil {
  95. n, _ := res.RowsAffected()
  96. rep.LoginAttemptsReset = int(n)
  97. }
  98. // 5) Marcador de migración aplicada (interno, no observable por la API).
  99. if _, err := sqldb.Exec(
  100. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
  101. migrationMarkerKey, time.Now().Format(time.RFC3339),
  102. ); err != nil {
  103. return nil, fmt.Errorf("marcador de migración: %w", err)
  104. }
  105. return rep, nil
  106. }
  107. // hasTable comprueba existencia en sqlite_master.
  108. func hasTable(db *sql.DB, name string) bool {
  109. var n int
  110. if err := db.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?", name).Scan(&n); err != nil {
  111. return false
  112. }
  113. return n > 0
  114. }
  115. func countRows(db *sql.DB, table string) int {
  116. if !hasTable(db, table) {
  117. return 0
  118. }
  119. var n int
  120. if err := db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", table)).Scan(&n); err != nil {
  121. return 0
  122. }
  123. return n
  124. }
  125. func countWhere(db *sql.DB, table, where string, args ...any) int {
  126. if !hasTable(db, table) {
  127. return 0
  128. }
  129. var n int
  130. if err := db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE %s", table, where), args...).Scan(&n); err != nil {
  131. return 0
  132. }
  133. return n
  134. }
  135. // atomicCopy copia src→dst vía fichero temporal + rename (misma partición).
  136. func atomicCopy(src, dst string) error {
  137. in, err := os.Open(src)
  138. if err != nil {
  139. return err
  140. }
  141. defer in.Close()
  142. tmp := dst + ".tmp"
  143. out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
  144. if err != nil {
  145. return err
  146. }
  147. if _, err := io.Copy(out, in); err != nil {
  148. out.Close()
  149. os.Remove(tmp)
  150. return err
  151. }
  152. if err := out.Sync(); err != nil {
  153. out.Close()
  154. os.Remove(tmp)
  155. return err
  156. }
  157. if err := out.Close(); err != nil {
  158. os.Remove(tmp)
  159. return err
  160. }
  161. return os.Rename(tmp, dst)
  162. }