Files
mirror-3x-ui/internal/database/postgres_maintenance_fence.go
T
Hamed 12e0b076a8 fix(database): coordinate migrations and restores across processes (#7322)
Coordinate database maintenance across panel, CLI, node synchronization, and restore paths.

- Add cross-process PostgreSQL advisory locks and pinned execution fences; cancel CLI work when its lease session is lost.
- Serialize SQLite file replacement with OS-level process locks and stable lock identity.
- Drain traffic writers and node-sync work before restore, then resume after migration and validation.
- Persist PostgreSQL restore-pending state and recover interrupted restores on startup.
- Add regression coverage for concurrent migrations/restores, session-loss fencing, CLI work cancellation, and recovery.

Closes #7318.
2026-12-03 12:05:51 +03:30

164 lines
5.3 KiB
Go

package database
import (
"context"
"database/sql/driver"
"errors"
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// The executing connection holds this key even if the coordinating session disappears.
const postgresMaintenanceWorkKey int64 = postgresMaintenanceKey + 1
type PostgresMaintenanceFence struct {
Context context.Context
pid int32
start int64
exclusive bool
}
func (l *MaintenanceLease) PostgresFence() (PostgresMaintenanceFence, error) {
return l.postgresFence(true)
}
func (l *MaintenanceLease) postgresFence(requireExclusive bool) (PostgresMaintenanceFence, error) {
pg, ok := l.backend.(*postgresMaintenance)
if !ok {
return PostgresMaintenanceFence{}, ErrMaintenanceUnavailable
}
pg.mu.Lock()
defer pg.mu.Unlock()
if pg.conn == nil || !pg.held || (requireExclusive && !pg.exclusive) {
return PostgresMaintenanceFence{}, ErrMaintenanceUnavailable
}
pg.watchWorkLocked()
ctx, cancel := context.WithTimeout(pg.workContext, MaintenanceWait)
defer cancel()
fence := PostgresMaintenanceFence{Context: pg.workContext, pid: int32(pg.conn.PgConn().PID()), exclusive: pg.exclusive}
err := pg.conn.QueryRow(ctx, `SELECT (extract(epoch FROM backend_start) * 1000000)::bigint
FROM pg_stat_activity WHERE pid = pg_backend_pid()`).Scan(&fence.start)
if err != nil {
l.available.Store(false)
return PostgresMaintenanceFence{}, errors.Join(ErrMaintenanceUnavailable, err, pg.dropConnection())
}
return fence, nil
}
func (f PostgresMaintenanceFence) ownerSQL() string {
mode := "ShareLock"
if f.exclusive {
mode = "ExclusiveLock"
}
return fmt.Sprintf(`SELECT EXISTS (
SELECT 1 FROM pg_locks AS l JOIN pg_stat_activity AS s USING (pid)
WHERE l.locktype = 'advisory' AND l.mode = '%s' AND l.granted
AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database())
AND l.classid = %d AND l.objid = %d AND l.objsubid = 1
AND l.pid = %d AND (extract(epoch FROM s.backend_start) * 1000000)::bigint = %d
)`, mode, uint64(postgresMaintenanceKey)>>32, uint32(postgresMaintenanceKey&0xffffffff), f.pid, f.start)
}
// TransactionFenceSQL fences an external SQL restore on the connection that executes it.
// It must run first inside the same transaction as the archive.
func (f PostgresMaintenanceFence) TransactionFenceSQL() string {
return fmt.Sprintf(`DO $xui$ BEGIN
IF NOT pg_try_advisory_xact_lock(%d) THEN
RAISE EXCEPTION 'PostgreSQL maintenance work is already executing';
END IF;
IF NOT (%s) THEN
RAISE EXCEPTION 'PostgreSQL maintenance ownership was lost';
END IF;
END $xui$`, postgresMaintenanceWorkKey, f.ownerSQL())
}
// WithPostgresWork runs maintenance through a pinned and fenced connection.
// The caller must use the provided GORM handle for every statement.
func (l *MaintenanceLease) WithPostgresWork(db *gorm.DB, work func(*gorm.DB) error) error {
return l.withPostgresWork(db, true, work)
}
// RunCLIWork binds a standalone CLI's database handles to its lease for the
// duration of the command. It must not be used by the running panel.
func (l *MaintenanceLease) RunCLIWork(work func() error) error {
return l.withPostgresWork(GetDB(), false, func(conn *gorm.DB) error {
pool, previous := db, publishedDB.Swap(conn)
db = conn
defer func() {
db = pool
publishedDB.Store(previous)
}()
return work()
})
}
func (l *MaintenanceLease) withPostgresWork(db *gorm.DB, requireExclusive bool, work func(*gorm.DB) error) (err error) {
if db.Name() != DialectPostgres {
return work(db)
}
fence, err := l.postgresFence(requireExclusive)
if err != nil {
return err
}
pool, err := db.DB()
if err != nil {
return err
}
raw, err := pool.Conn(fence.Context)
if err != nil {
return err
}
defer raw.Close()
// Populate both GORM's default and statement connection. Its default
// transaction callbacks reset the statement to the default connection.
fenced, err := gorm.Open(postgres.New(postgres.Config{Conn: raw}), &gorm.Config{
Logger: db.Logger, NamingStrategy: db.NamingStrategy, DisableAutomaticPing: true,
DisableForeignKeyConstraintWhenMigrating: db.DisableForeignKeyConstraintWhenMigrating,
})
if err != nil {
return err
}
conn := fenced.WithContext(fence.Context)
discard := func() { _ = raw.Raw(func(any) error { return driver.ErrBadConn }) }
take, release := "SELECT pg_try_advisory_lock_shared(?)", "SELECT pg_advisory_unlock_shared(?)"
if fence.exclusive {
take, release = "SELECT pg_try_advisory_lock(?)", "SELECT pg_advisory_unlock(?)"
}
var locked bool
if err := conn.Raw(take, postgresMaintenanceWorkKey).Scan(&locked).Error; err != nil {
discard()
return err
}
if !locked {
return ErrMaintenanceBusy
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), MaintenanceWait)
defer cancel()
var released bool
unlockErr := conn.WithContext(ctx).Raw(release, postgresMaintenanceWorkKey).Scan(&released).Error
if unlockErr != nil || !released {
// Never return a session that might retain its fence to the app pool.
discard()
err = errors.Join(err, ErrMaintenanceUnavailable, unlockErr)
}
}()
checkOwner := func() error {
var held bool
err := conn.Raw(fence.ownerSQL()).Scan(&held).Error
if err != nil || !held {
return errors.Join(ErrMaintenanceUnavailable, err)
}
return nil
}
if err := checkOwner(); err != nil {
return err
}
if err := work(conn); err != nil {
return err
}
return checkOwner()
}