fix: address review findings for backup management

- HIGH: Add sync.Mutex to backup Engine to prevent concurrent
  backup/restore operations
- HIGH: Restore uses io.Copy instead of ReadFile to avoid OOM on
  large databases
- HIGH: Send HTTP response before closing DB during restore, then
  perform destructive operations in a goroutine
- HIGH: Create pre-restore safety backup before overwriting database
- HIGH: Autobackup cron reschedules dynamically when settings change
  via callback pattern (same as DNS provider changes)
This commit is contained in:
2026-04-02 15:39:54 +03:00
parent a9c7775bb7
commit 3c9727162a
5 changed files with 97 additions and 37 deletions
+56 -27
View File
@@ -1,9 +1,12 @@
package api
import (
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"time"
"github.com/alexei/docker-watcher/internal/store"
"github.com/go-chi/chi/v5"
@@ -93,7 +96,7 @@ func (s *Server) deleteBackup(w http.ResponseWriter, r *http.Request) {
}
// restoreBackup handles POST /api/backups/{id}/restore.
// This replaces the current database with the backup. The server should be restarted after.
// This replaces the current database with the backup and triggers a graceful shutdown.
func (s *Server) restoreBackup(w http.ResponseWriter, r *http.Request) {
if s.backupEngine == nil {
respondError(w, http.StatusServiceUnavailable, "backup engine not initialized")
@@ -107,36 +110,62 @@ func (s *Server) restoreBackup(w http.ResponseWriter, r *http.Request) {
return
}
// Read the backup file.
backupData, err := os.ReadFile(restorePath)
if err != nil {
respondError(w, http.StatusInternalServerError, "failed to read backup file: "+err.Error())
return
// Create a safety backup before restore so the user can undo if needed.
if _, err := s.backupEngine.CreateBackup("pre-restore"); err != nil {
slog.Warn("failed to create pre-restore backup", "error", err)
}
// Close the current database to release locks.
if err := s.store.Close(); err != nil {
respondError(w, http.StatusInternalServerError, "failed to close database: "+err.Error())
return
}
// Write backup over the main database file.
if err := os.WriteFile(s.dbPath, backupData, 0o644); err != nil {
respondError(w, http.StatusInternalServerError, "failed to write database: "+err.Error())
return
}
// Remove WAL and SHM files to ensure clean state.
os.Remove(s.dbPath + "-wal")
os.Remove(s.dbPath + "-shm")
// Send the response BEFORE closing the DB so the client gets confirmation.
respondJSON(w, http.StatusOK, map[string]any{
"status": "restored",
"message": "Database restored. The server needs to be restarted to apply changes.",
"status": "restoring",
"message": "Database restore initiated. The server will restart shortly.",
})
// Signal the server to shut down gracefully so it can be restarted.
if s.shutdownFunc != nil {
go s.shutdownFunc()
// Flush the response.
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
// Perform the destructive restore in a goroutine with a brief delay
// to allow the HTTP response to be fully sent.
go func() {
time.Sleep(500 * time.Millisecond)
// Close the current database to release locks.
if err := s.store.Close(); err != nil {
slog.Error("restore: failed to close database", "error", err)
return
}
// Copy the backup file over the main database using streaming (no full read into memory).
src, err := os.Open(restorePath)
if err != nil {
slog.Error("restore: failed to open backup file", "error", err)
return
}
defer src.Close()
dst, err := os.Create(s.dbPath)
if err != nil {
slog.Error("restore: failed to create database file", "error", err)
return
}
defer dst.Close()
if _, err := io.Copy(dst, src); err != nil {
slog.Error("restore: failed to copy backup to database", "error", err)
return
}
// Remove WAL and SHM files to ensure clean state.
os.Remove(s.dbPath + "-wal")
os.Remove(s.dbPath + "-shm")
slog.Info("restore: database replaced, triggering shutdown")
// Signal the server to shut down gracefully so it can be restarted.
if s.shutdownFunc != nil {
s.shutdownFunc()
}
}()
}