68 lines
2.4 KiB
Go
68 lines
2.4 KiB
Go
package models
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"git.mchus.pro/mchus/quoteforge/internal/mariadb"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// RestoreSQLMigrationSession is the shipped recovery path after interruption.
|
|
func RestoreSQLMigrationSession(db *gorm.DB, snapshot string) error {
|
|
return db.Connection(func(conn *gorm.DB) (err error) {
|
|
fresh := func() *gorm.DB { return conn.Session(&gorm.Session{NewDB: true}) }
|
|
var schema, zone string
|
|
var acquired int
|
|
if err := fresh().Raw("SELECT DATABASE(), @@time_zone").Row().Scan(&schema, &zone); err != nil {
|
|
return fmt.Errorf("read recovery session: %w", err)
|
|
}
|
|
lock := fmt.Sprintf("qfs-migrate-%x", sha256.Sum256([]byte(schema)))
|
|
if err := fresh().Raw("SELECT GET_LOCK(?,0)", lock).Scan(&acquired).Error; err != nil || acquired != 1 {
|
|
return fmt.Errorf("migration lock unavailable for recovery")
|
|
}
|
|
defer func() {
|
|
if e := fresh().Exec("SET time_zone=?", zone).Error; e != nil {
|
|
err = errors.Join(err, fmt.Errorf("reset recovery time zone: %w", e))
|
|
}
|
|
if e := fresh().Raw("SELECT RELEASE_LOCK(?)", lock).Scan(&acquired).Error; e != nil {
|
|
err = errors.Join(err, fmt.Errorf("release recovery lock: %w", e))
|
|
}
|
|
}()
|
|
if err := requireExclusiveMigrationSession(fresh()); err != nil {
|
|
return err
|
|
}
|
|
journalName, err := migrationJournalName(conn, schema)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
journal := filepath.Join(filepath.Dir(snapshot), journalName)
|
|
if content, e := os.ReadFile(journal); e == nil {
|
|
if strings.TrimSpace(string(content)) != snapshot {
|
|
return fmt.Errorf("pending recovery requires its original snapshot: %s", strings.TrimSpace(string(content)))
|
|
}
|
|
} else if !os.IsNotExist(e) {
|
|
return fmt.Errorf("read recovery marker: %w", e)
|
|
}
|
|
if err := fresh().Exec("SET time_zone='+00:00'").Error; err != nil {
|
|
return fmt.Errorf("set restore time zone: %w", err)
|
|
}
|
|
if err := mariadb.VerifySnapshot(fresh(), snapshot); err != nil {
|
|
return fmt.Errorf("verify recovery snapshot: %w", err)
|
|
}
|
|
if err := mariadb.RestoreSnapshot(fresh(), snapshot); err != nil {
|
|
return fmt.Errorf("restore migration session: %w", err)
|
|
}
|
|
if err := os.Remove(journal); err != nil && !os.IsNotExist(err) {
|
|
return fmt.Errorf("clear recovery marker: %w", err)
|
|
}
|
|
slog.Info("server migration snapshot restored", "schema", schema, "backup", snapshot, "state", "verified")
|
|
return nil
|
|
})
|
|
}
|