mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 16:04:50 +03:00
12e0b076a8
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.
511 lines
14 KiB
Go
511 lines
14 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
|
)
|
|
|
|
// PostgreSQL scopes advisory keys to a database. Share this key with writer transactions.
|
|
const postgresMaintenanceKey int64 = 0x3378756964626d74
|
|
|
|
const MaintenanceWait = 5 * time.Second
|
|
|
|
var ErrMaintenanceBusy = errors.New("database maintenance lock is busy; the database is in use by another process")
|
|
|
|
type maintenanceBackend interface {
|
|
setMode(context.Context, bool) error
|
|
close() error
|
|
}
|
|
|
|
// MaintenanceLease holds a shared runtime or exclusive maintenance lock independently of the app pool.
|
|
type MaintenanceLease struct {
|
|
backend maintenanceBackend
|
|
available atomic.Bool
|
|
}
|
|
|
|
var runtimeMaintenanceLease atomic.Pointer[MaintenanceLease]
|
|
|
|
func SetRuntimeMaintenanceLease(lease *MaintenanceLease) {
|
|
runtimeMaintenanceLease.Store(lease)
|
|
}
|
|
|
|
var ErrMaintenanceUnavailable = errors.New("database maintenance connection is unavailable")
|
|
|
|
func RuntimeMaintenanceAvailable() bool {
|
|
lease := runtimeMaintenanceLease.Load()
|
|
return lease == nil || lease.available.Load()
|
|
}
|
|
|
|
// AcquireStartupMaintenance retries PostgreSQL connection setup independently
|
|
// of the shorter advisory lock wait.
|
|
func AcquireStartupMaintenance(ctx context.Context) (*MaintenanceLease, error) {
|
|
if config.GetDBKind() != DialectPostgres {
|
|
lock, cancel := context.WithTimeout(ctx, MaintenanceWait)
|
|
defer cancel()
|
|
return AcquireConfiguredMaintenance(lock, true)
|
|
}
|
|
cfg, err := postgresMaintenanceConfig(config.GetDBDSN())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, delay := range postgresStartupDelays {
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
case <-time.After(delay):
|
|
}
|
|
attempt, cancel := context.WithTimeout(ctx, MaintenanceWait)
|
|
var conn *pgx.Conn
|
|
conn, err = pgx.ConnectConfig(attempt, cfg)
|
|
cancel()
|
|
if err == nil {
|
|
lock, cancelLock := context.WithTimeout(ctx, MaintenanceWait)
|
|
defer cancelLock()
|
|
return acquireMaintenance(lock, &postgresMaintenance{cfg: cfg, conn: conn}, true)
|
|
}
|
|
log.Printf("connect for PostgreSQL maintenance: %v", err)
|
|
}
|
|
return nil, fmt.Errorf("connect for PostgreSQL maintenance: %w", err)
|
|
}
|
|
|
|
func AcquireConfiguredMaintenance(ctx context.Context, exclusive bool) (*MaintenanceLease, error) {
|
|
if config.GetDBKind() == DialectPostgres {
|
|
return AcquirePostgresMaintenance(ctx, config.GetDBDSN(), exclusive)
|
|
}
|
|
return AcquireSQLiteMaintenance(ctx, config.GetDBPath(), exclusive)
|
|
}
|
|
|
|
// TryConfiguredMaintenance checks once for contention but still bounds connection setup by ctx.
|
|
func TryConfiguredMaintenance(ctx context.Context, exclusive bool) (*MaintenanceLease, error) {
|
|
return AcquireConfiguredMaintenance(context.WithValue(ctx, noMaintenanceRetry{}, true), exclusive)
|
|
}
|
|
|
|
type noMaintenanceRetry struct{}
|
|
|
|
func postgresMaintenanceConfig(dsn string) (*pgx.ConnConfig, error) {
|
|
cfg, err := pgx.ParseConfig(dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("configure PostgreSQL maintenance connection: %w", err)
|
|
}
|
|
cfg.RuntimeParams["application_name"] = "3x-ui-maintenance"
|
|
return cfg, nil
|
|
}
|
|
|
|
func AcquirePostgresMaintenance(ctx context.Context, dsn string, exclusive bool) (*MaintenanceLease, error) {
|
|
cfg, err := postgresMaintenanceConfig(dsn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
conn, err := pgx.ConnectConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("connect for PostgreSQL maintenance: %w", err)
|
|
}
|
|
return acquireMaintenance(ctx, &postgresMaintenance{cfg: cfg, conn: conn}, exclusive)
|
|
}
|
|
|
|
// SQLiteDatabasePath follows the final link even while its target is being replaced.
|
|
func SQLiteDatabasePath(dbPath string) (string, error) {
|
|
target, err := filepath.Abs(dbPath)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
for range 255 {
|
|
parent, err := filepath.EvalSymlinks(filepath.Dir(target))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
target = filepath.Join(parent, filepath.Base(target))
|
|
info, err := os.Lstat(target)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return target, nil
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if info.Mode()&os.ModeSymlink == 0 {
|
|
return target, nil
|
|
}
|
|
link, err := os.Readlink(target)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if !filepath.IsAbs(link) {
|
|
link = filepath.Join(parent, link)
|
|
}
|
|
target = link
|
|
}
|
|
return "", fmt.Errorf("too many symlinks resolving the SQLite database path %q", dbPath)
|
|
}
|
|
|
|
func AcquireSQLiteMaintenance(ctx context.Context, dbPath string, exclusive bool) (*MaintenanceLease, error) {
|
|
if err := os.MkdirAll(filepath.Dir(dbPath), 0o700); err != nil {
|
|
return nil, err
|
|
}
|
|
target, err := SQLiteDatabasePath(dbPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
intent, err := os.OpenFile(target+".maintenance-intent", os.O_RDWR|os.O_CREATE, 0o600)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
owner, err := os.OpenFile(target+".maintenance-lock", os.O_RDWR|os.O_CREATE, 0o600)
|
|
if err != nil {
|
|
_ = intent.Close()
|
|
return nil, err
|
|
}
|
|
return acquireMaintenance(ctx, &sqliteMaintenance{owner: owner, intent: intent}, exclusive)
|
|
}
|
|
|
|
func acquireMaintenance(ctx context.Context, backend maintenanceBackend, exclusive bool) (*MaintenanceLease, error) {
|
|
lease := &MaintenanceLease{backend: backend}
|
|
if pg, ok := backend.(*postgresMaintenance); ok {
|
|
pg.onLoss = func() { lease.available.Store(false) }
|
|
}
|
|
if err := lease.SetExclusive(ctx, exclusive); err != nil {
|
|
return nil, errors.Join(err, lease.Close())
|
|
}
|
|
lease.available.Store(true)
|
|
return lease, nil
|
|
}
|
|
|
|
func (l *MaintenanceLease) SetExclusive(ctx context.Context, exclusive bool) error {
|
|
started := time.Now()
|
|
err := l.backend.setMode(ctx, exclusive)
|
|
if errors.Is(err, ErrMaintenanceUnavailable) {
|
|
l.available.Store(false)
|
|
}
|
|
if exclusive {
|
|
log.Printf("database maintenance: pid=%d lock_wait_ms=%d acquired=%t", os.Getpid(), time.Since(started).Milliseconds(), err == nil)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (l *MaintenanceLease) Close() error {
|
|
l.available.Store(false)
|
|
return l.backend.close()
|
|
}
|
|
|
|
// AcquireRestoreMaintenance upgrades the panel's lease after local work has drained.
|
|
func AcquireRestoreMaintenance(ctx context.Context) (*MaintenanceLease, func() error, error) {
|
|
if lease := runtimeMaintenanceLease.Load(); lease != nil {
|
|
if err := lease.SetExclusive(ctx, true); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return lease, func() error {
|
|
timeout, cancel := context.WithTimeout(context.Background(), MaintenanceWait)
|
|
defer cancel()
|
|
return lease.SetExclusive(timeout, false)
|
|
}, nil
|
|
}
|
|
lease, err := AcquireConfiguredMaintenance(ctx, true)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return lease, lease.Close, nil
|
|
}
|
|
|
|
// CheckRuntimeConnection stops admitting work if the PostgreSQL lease is lost.
|
|
func (l *MaintenanceLease) CheckRuntimeConnection(ctx context.Context) error {
|
|
pg, ok := l.backend.(*postgresMaintenance)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
pg.mu.Lock()
|
|
defer pg.mu.Unlock()
|
|
if pg.conn == nil {
|
|
l.available.Store(false)
|
|
return ErrMaintenanceUnavailable
|
|
}
|
|
if err := pg.conn.Ping(ctx); err != nil {
|
|
l.available.Store(false)
|
|
return errors.Join(err, pg.dropConnection())
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RecoverRuntimeConnection reconnects shared runtime sessions. An interrupted
|
|
// exclusive operation requires recovery under a new maintenance lease.
|
|
func (l *MaintenanceLease) RecoverRuntimeConnection(ctx context.Context) error {
|
|
pg, ok := l.backend.(*postgresMaintenance)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
pg.mu.Lock()
|
|
defer pg.mu.Unlock()
|
|
if pg.closed {
|
|
return ErrMaintenanceUnavailable
|
|
}
|
|
if pg.conn != nil {
|
|
return nil
|
|
}
|
|
if pg.exclusive {
|
|
return ErrMaintenanceUnavailable
|
|
}
|
|
conn, err := pgx.ConnectConfig(ctx, pg.cfg)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pg.conn = conn
|
|
if err := pg.setModeLocked(ctx, false); err != nil {
|
|
return errors.Join(err, pg.dropConnection())
|
|
}
|
|
l.available.Store(true)
|
|
return nil
|
|
}
|
|
|
|
// LockPostgresWriter keeps a conflicting transaction protected even if the
|
|
// runtime's dedicated connection drops while the transaction is in flight.
|
|
func LockPostgresWriter(tx *gorm.DB) error {
|
|
if tx.Error != nil {
|
|
return tx.Error
|
|
}
|
|
if tx.Name() != DialectPostgres {
|
|
return nil
|
|
}
|
|
var locked bool
|
|
if err := tx.Raw("SELECT pg_try_advisory_xact_lock_shared(?)", postgresMaintenanceKey).Scan(&locked).Error; err != nil {
|
|
return err
|
|
}
|
|
if !locked {
|
|
return ErrMaintenanceBusy
|
|
}
|
|
if err := tx.Raw("SELECT pg_try_advisory_xact_lock_shared(?)", postgresMaintenanceWorkKey).Scan(&locked).Error; err != nil {
|
|
return err
|
|
}
|
|
if !locked {
|
|
return ErrMaintenanceBusy
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func waitMaintenance(ctx context.Context, try func() (bool, error)) error {
|
|
busy := false
|
|
for {
|
|
if err := ctx.Err(); err != nil {
|
|
if busy {
|
|
return errors.Join(ErrMaintenanceBusy, err)
|
|
}
|
|
return err
|
|
}
|
|
ok, err := try()
|
|
if err != nil {
|
|
if busy && ctx.Err() != nil {
|
|
return errors.Join(ErrMaintenanceBusy, ctx.Err())
|
|
}
|
|
return err
|
|
}
|
|
if ok {
|
|
return nil
|
|
}
|
|
if ctx.Value(noMaintenanceRetry{}) != nil {
|
|
return ErrMaintenanceBusy
|
|
}
|
|
busy = true
|
|
select {
|
|
case <-ctx.Done():
|
|
return errors.Join(ErrMaintenanceBusy, ctx.Err())
|
|
case <-time.After(50 * time.Millisecond):
|
|
}
|
|
}
|
|
}
|
|
|
|
type postgresMaintenance struct {
|
|
mu sync.Mutex
|
|
cfg *pgx.ConnConfig
|
|
conn *pgx.Conn
|
|
closed bool
|
|
held bool
|
|
exclusive bool
|
|
workContext context.Context
|
|
cancelWork context.CancelFunc
|
|
onLoss func()
|
|
}
|
|
|
|
func (p *postgresMaintenance) setMode(ctx context.Context, exclusive bool) error {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
return p.setModeLocked(ctx, exclusive)
|
|
}
|
|
|
|
func (p *postgresMaintenance) setModeLocked(ctx context.Context, exclusive bool) error {
|
|
if p.conn == nil || p.closed {
|
|
return ErrMaintenanceUnavailable
|
|
}
|
|
if p.held && p.exclusive == exclusive {
|
|
return nil
|
|
}
|
|
lock, unlock := "SELECT pg_try_advisory_lock_shared($1)", "SELECT pg_advisory_unlock_shared($1)"
|
|
unlockOld := "SELECT pg_advisory_unlock($1)"
|
|
if exclusive {
|
|
lock, unlock, unlockOld = "SELECT pg_try_advisory_lock($1)", unlockOld, unlock
|
|
}
|
|
if err := waitMaintenance(ctx, func() (bool, error) {
|
|
var ok bool
|
|
if err := p.conn.QueryRow(ctx, lock, postgresMaintenanceKey).Scan(&ok); err != nil {
|
|
return false, errors.Join(ErrMaintenanceUnavailable, err, p.dropConnection())
|
|
}
|
|
if !ok {
|
|
return false, nil
|
|
}
|
|
// The new lease must also be compatible with work still running
|
|
// on a separate execution session.
|
|
if err := p.conn.QueryRow(ctx, lock, postgresMaintenanceWorkKey).Scan(&ok); err != nil {
|
|
return false, errors.Join(ErrMaintenanceUnavailable, err, p.dropConnection())
|
|
}
|
|
key := postgresMaintenanceKey
|
|
if ok {
|
|
key = postgresMaintenanceWorkKey
|
|
}
|
|
var released bool
|
|
if err := p.conn.QueryRow(ctx, unlock, key).Scan(&released); err != nil || !released {
|
|
return false, errors.Join(ErrMaintenanceUnavailable, err, p.dropConnection())
|
|
}
|
|
if !ok || exclusive {
|
|
return ok, nil
|
|
}
|
|
pending, err := postgresRestorePending(func(query string, result *bool) error {
|
|
return p.conn.QueryRow(ctx, query).Scan(result)
|
|
})
|
|
if err != nil || pending {
|
|
if pending {
|
|
err = ErrPostgresRestorePending
|
|
}
|
|
return false, errors.Join(err, p.dropConnection())
|
|
}
|
|
return true, nil
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
if p.held {
|
|
var released bool
|
|
if err := p.conn.QueryRow(ctx, unlockOld, postgresMaintenanceKey).Scan(&released); err != nil || !released {
|
|
return errors.Join(ErrMaintenanceUnavailable, errors.New("could not release previous PostgreSQL maintenance mode"), err, p.dropConnection())
|
|
}
|
|
}
|
|
p.held, p.exclusive = true, exclusive
|
|
if exclusive {
|
|
p.watchWorkLocked()
|
|
} else if p.cancelWork != nil {
|
|
p.cancelWork()
|
|
p.cancelWork = nil
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *postgresMaintenance) watchWorkLocked() {
|
|
if p.cancelWork == nil {
|
|
p.workContext, p.cancelWork = context.WithCancel(context.Background())
|
|
go p.watchWork(p.workContext)
|
|
}
|
|
}
|
|
|
|
func (p *postgresMaintenance) watchWork(ctx context.Context) {
|
|
ticker := time.NewTicker(time.Second)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
}
|
|
p.mu.Lock()
|
|
if ctx.Err() != nil {
|
|
p.mu.Unlock()
|
|
return
|
|
}
|
|
ping, cancel := context.WithTimeout(ctx, MaintenanceWait)
|
|
err := p.conn.Ping(ping)
|
|
cancel()
|
|
if err != nil {
|
|
_ = p.dropConnection()
|
|
}
|
|
p.mu.Unlock()
|
|
}
|
|
}
|
|
|
|
func (p *postgresMaintenance) close() error {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
p.closed = true
|
|
return p.dropConnection()
|
|
}
|
|
|
|
func (p *postgresMaintenance) dropConnection() error {
|
|
if p.onLoss != nil {
|
|
p.onLoss()
|
|
}
|
|
if p.cancelWork != nil {
|
|
p.cancelWork()
|
|
p.cancelWork = nil
|
|
}
|
|
conn := p.conn
|
|
p.conn, p.held = nil, false
|
|
if conn == nil {
|
|
return nil
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), MaintenanceWait)
|
|
defer cancel()
|
|
return conn.Close(ctx)
|
|
}
|
|
|
|
type sqliteMaintenance struct {
|
|
mu sync.Mutex
|
|
owner, intent *os.File
|
|
held bool
|
|
exclusive bool
|
|
}
|
|
|
|
func (s *sqliteMaintenance) setMode(ctx context.Context, exclusive bool) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.held && s.exclusive == exclusive {
|
|
return nil
|
|
}
|
|
if err := waitMaintenance(ctx, func() (bool, error) { return s.tryMode(exclusive) }); err != nil {
|
|
return err
|
|
}
|
|
s.held, s.exclusive = true, exclusive
|
|
return nil
|
|
}
|
|
|
|
func (s *sqliteMaintenance) tryMode(exclusive bool) (locked bool, err error) {
|
|
intent, err := tryMaintenanceFileLock(s.intent, true)
|
|
if !intent || err != nil {
|
|
return false, err
|
|
}
|
|
defer func() { err = errors.Join(err, unlockMaintenanceFile(s.intent)) }()
|
|
if s.held {
|
|
if err := unlockMaintenanceFile(s.owner); err != nil {
|
|
return false, err
|
|
}
|
|
}
|
|
locked, err = tryMaintenanceFileLock(s.owner, exclusive)
|
|
if !locked && s.held {
|
|
// Restore the old mode before letting another process try to acquire.
|
|
ok, relock := tryMaintenanceFileLock(s.owner, s.exclusive)
|
|
if !ok || relock != nil {
|
|
return false, errors.Join(err, errors.New("lost previous SQLite maintenance mode"), relock)
|
|
}
|
|
}
|
|
return locked, err
|
|
}
|
|
|
|
func (s *sqliteMaintenance) close() error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return errors.Join(s.owner.Close(), s.intent.Close())
|
|
}
|