mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 16:04:50 +03:00
fix(database): guard inbound migrations against active PostgreSQL writes
Acquire non-blocking database locks before inbound migration. Keep migration passes atomic and return errors to the CLI and import callers.
This commit is contained in:
@@ -194,6 +194,16 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL inbound migration contention
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test ./internal/web/service -run '^TestMigrationRequirementsRejectsLiveNodeMergePostgres$' -count=1 -v | tee /tmp/postgres-inbound-migration.log
|
||||
passed=$(grep -c -- '^--- PASS' /tmp/postgres-inbound-migration.log || true)
|
||||
if [ "$passed" -ne 1 ]; then
|
||||
echo "expected the PostgreSQL inbound migration contention test to pass, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL node snapshot regressions
|
||||
run: |
|
||||
set -o pipefail
|
||||
|
||||
@@ -13,11 +13,17 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (s *InboundService) MigrationRemoveOrphanedTraffics() {
|
||||
db := database.GetDB()
|
||||
if err := removeOrphanedMigrationTraffics(database.GetDB()); err != nil {
|
||||
logger.Warning("MigrationRemoveOrphanedTraffics failed:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func removeOrphanedMigrationTraffics(db *gorm.DB) error {
|
||||
query := fmt.Sprintf(
|
||||
"DELETE FROM client_traffics WHERE email NOT IN (SELECT email FROM clients) AND email NOT IN (SELECT %s %s)",
|
||||
database.JSONFieldText("client.value", "email"),
|
||||
@@ -25,33 +31,47 @@ func (s *InboundService) MigrationRemoveOrphanedTraffics() {
|
||||
)
|
||||
result := db.Exec(query)
|
||||
if result.Error != nil {
|
||||
logger.Warning("MigrationRemoveOrphanedTraffics failed:", result.Error)
|
||||
return
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected > 0 {
|
||||
logger.Infof("MigrationRemoveOrphanedTraffics: removed %d orphaned client_traffics row(s)", result.RowsAffected)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *InboundService) MigrationRequirements() (err error) {
|
||||
func runInboundMigration(migrate func(*gorm.DB) error) error {
|
||||
db := database.GetDB()
|
||||
tx := db.Begin()
|
||||
defer func() {
|
||||
if err == nil {
|
||||
if commitErr := tx.Commit().Error; commitErr != nil {
|
||||
err = commitErr
|
||||
return
|
||||
}
|
||||
if !database.IsPostgres() {
|
||||
if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
|
||||
logger.Warningf("VACUUM failed: %v", dbErr)
|
||||
started := time.Now()
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
if tx.Name() == database.DialectPostgres {
|
||||
// Take maintenance locks before touching any of these tables. NOWAIT
|
||||
// also protects against writers in another process or an older panel.
|
||||
err := tx.Exec(`LOCK TABLE inbounds, client_traffics, clients, client_inbounds, client_groups,
|
||||
nodes, api_tokens, outbound_subscriptions IN ACCESS EXCLUSIVE MODE NOWAIT`).Error
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "55P03" {
|
||||
return fmt.Errorf("database is busy; retry the inbound migration after active database work has stopped: %w", err)
|
||||
}
|
||||
return fmt.Errorf("lock inbound migration tables: %w", err)
|
||||
}
|
||||
} else {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
return migrate(tx)
|
||||
})
|
||||
logger.Debugf("inbound migration: tx_ms=%d committed=%t", time.Since(started).Milliseconds(), err == nil)
|
||||
if err == nil && db.Name() == database.DialectSQLite {
|
||||
if vacuumErr := db.Exec(`VACUUM "main"`).Error; vacuumErr != nil {
|
||||
logger.Warningf("VACUUM failed: %v", vacuumErr)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *InboundService) MigrationRequirements() error {
|
||||
return runInboundMigration(s.migrationRequirements)
|
||||
}
|
||||
|
||||
func (s *InboundService) migrationRequirements(tx *gorm.DB) (err error) {
|
||||
if tx.Migrator().HasColumn(&model.Inbound{}, "all_time") {
|
||||
if err = tx.Migrator().DropColumn(&model.Inbound{}, "all_time"); err != nil {
|
||||
return
|
||||
@@ -286,12 +306,16 @@ func (s *InboundService) MigrationRequirements() (err error) {
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *InboundService) MigrateDB() {
|
||||
if err := s.MigrationRequirements(); err != nil {
|
||||
logger.Errorf("MigrationRequirements failed: %v", err)
|
||||
}
|
||||
s.MigrationRemoveOrphanedTraffics()
|
||||
s.MigrationRestoreVisionFlow()
|
||||
func (s *InboundService) MigrateDB() error {
|
||||
return runInboundMigration(func(tx *gorm.DB) error {
|
||||
if err := s.migrationRequirements(tx); err != nil {
|
||||
return fmt.Errorf("inbound migration requirements: %w", err)
|
||||
}
|
||||
if err := removeOrphanedMigrationTraffics(tx); err != nil {
|
||||
return fmt.Errorf("remove orphaned traffic during migration: %w", err)
|
||||
}
|
||||
return s.migrationRestoreVisionFlow(tx)
|
||||
})
|
||||
}
|
||||
|
||||
// MigrationRestoreVisionFlow repairs VLESS inbounds whose clients lost their
|
||||
@@ -302,37 +326,36 @@ func (s *InboundService) MigrateDB() {
|
||||
// Vision. Idempotent: once a client carries the flow it is skipped, so this is a
|
||||
// no-op on healthy installs and on subsequent boots.
|
||||
func (s *InboundService) MigrationRestoreVisionFlow() {
|
||||
db := database.GetDB()
|
||||
if err := runInboundMigration(s.migrationRestoreVisionFlow); err != nil {
|
||||
logger.Warning("MigrationRestoreVisionFlow failed:", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *InboundService) migrationRestoreVisionFlow(tx *gorm.DB) error {
|
||||
var inbounds []*model.Inbound
|
||||
if err := db.Model(&model.Inbound{}).
|
||||
if err := tx.Model(&model.Inbound{}).
|
||||
Where("protocol = ?", model.VLESS).
|
||||
Find(&inbounds).Error; err != nil {
|
||||
logger.Warning("MigrationRestoreVisionFlow: load inbounds failed:", err)
|
||||
return
|
||||
return fmt.Errorf("load VLESS inbounds for flow migration: %w", err)
|
||||
}
|
||||
for _, ib := range inbounds {
|
||||
if ib.DisableFlow {
|
||||
continue
|
||||
}
|
||||
restored, changed := s.restoreVisionFlowForEligibleInbound(nil, ib.Settings, ib.StreamSettings, ib.Protocol)
|
||||
restored, changed := s.restoreVisionFlowForEligibleInbound(tx, ib.Settings, ib.StreamSettings, ib.Protocol)
|
||||
if !changed {
|
||||
continue
|
||||
}
|
||||
clients, err := s.GetClients(&model.Inbound{Settings: restored})
|
||||
if err != nil {
|
||||
logger.Warning("MigrationRestoreVisionFlow: parse clients for inbound", ib.Id, "failed:", err)
|
||||
continue
|
||||
return fmt.Errorf("parse clients for inbound %d during flow migration: %w", ib.Id, err)
|
||||
}
|
||||
err = db.Transaction(func(tx *gorm.DB) error {
|
||||
if e := tx.Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("settings", restored).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
return s.clientService.SyncInbound(tx, ib.Id, clients)
|
||||
})
|
||||
if err != nil {
|
||||
logger.Warning("MigrationRestoreVisionFlow: update inbound", ib.Id, "failed:", err)
|
||||
continue
|
||||
if err := tx.Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("settings", restored).Error; err != nil {
|
||||
return fmt.Errorf("update inbound %d during flow migration: %w", ib.Id, err)
|
||||
}
|
||||
if err := s.clientService.SyncInbound(tx, ib.Id, clients); err != nil {
|
||||
return fmt.Errorf("sync inbound %d during flow migration: %w", ib.Id, err)
|
||||
}
|
||||
logger.Info("MigrationRestoreVisionFlow: restored XTLS Vision flow on inbound", ib.Id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func TestMigrationRequirementsRejectsLiveNodeMergePostgres(t *testing.T) {
|
||||
if config.GetDBKind() != database.DialectPostgres {
|
||||
t.Skip("requires PostgreSQL table locks")
|
||||
}
|
||||
db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "migration.db"))
|
||||
node := &model.Node{Name: "migration-contention", Enable: true}
|
||||
seedNodeRow(t, db, node)
|
||||
svc := &InboundService{}
|
||||
const email = "migration-client@example.test"
|
||||
snapshot := func(up, quota int64) *runtime.TrafficSnapshot {
|
||||
settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true,"totalGB":%d}]}`, email, quota)
|
||||
snap := snapshotWithClients(t, "migration-contention", settings, xray.ClientTraffic{
|
||||
Email: email, Up: up, Total: quota, Enable: true,
|
||||
})
|
||||
snap.Inbounds[0].Up = up
|
||||
snap.Inbounds[0].Protocol = model.VLESS
|
||||
return snap
|
||||
}
|
||||
if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
locked, unblock := make(chan struct{}), make(chan struct{})
|
||||
var hold, release sync.Once
|
||||
finishMerge := func() { release.Do(func() { close(unblock) }) }
|
||||
if err := db.Callback().Update().After("gorm:update").Register("test:hold_node_merge", func(tx *gorm.DB) {
|
||||
if tx.Statement.Table == "inbounds" && tx.Error == nil {
|
||||
hold.Do(func() {
|
||||
close(locked)
|
||||
<-unblock
|
||||
})
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
report := snapshot(130, 2000)
|
||||
mergeDone := make(chan struct{})
|
||||
var mergeErr error
|
||||
go func() {
|
||||
defer close(mergeDone)
|
||||
_, mergeErr = svc.SetRemoteTraffic(node.Id, report, false, false)
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
finishMerge()
|
||||
<-mergeDone
|
||||
})
|
||||
select {
|
||||
case <-locked:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("fixture merge never acquired write locks")
|
||||
}
|
||||
|
||||
migrationDone := make(chan struct{})
|
||||
var migrationErr error
|
||||
go func() {
|
||||
defer close(migrationDone)
|
||||
migrationErr = svc.MigrationRequirements()
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
finishMerge()
|
||||
<-migrationDone
|
||||
})
|
||||
select {
|
||||
case <-migrationDone:
|
||||
var pgErr *pgconn.PgError
|
||||
if !errors.As(migrationErr, &pgErr) || pgErr.Code != "55P03" {
|
||||
t.Fatalf("concurrent migration error=%v, want lock not available", migrationErr)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("migration waited behind the merge instead of refusing to start")
|
||||
}
|
||||
|
||||
finishMerge()
|
||||
<-mergeDone
|
||||
if mergeErr != nil {
|
||||
t.Fatal(mergeErr)
|
||||
}
|
||||
if err := svc.MigrateDB(); err != nil {
|
||||
t.Fatalf("retry after merge committed: %v", err)
|
||||
}
|
||||
if row := readTraffic(t, db, email); row.Up != 130 || row.Total != 2000 {
|
||||
t.Fatalf("merge or migration lost traffic counters: %+v", row)
|
||||
}
|
||||
if record := lookupClientRecord(t, email); record.TotalGB != 2000 || linkCount(t, db, email) != 1 {
|
||||
t.Fatalf("merge or migration lost the updated client or its membership: %+v", record)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateDBRollsBackRequirementsWhenTrafficCleanupFails(t *testing.T) {
|
||||
if config.GetDBKind() == database.DialectPostgres {
|
||||
t.Skip("uses a SQLite trigger to fail orphan cleanup")
|
||||
}
|
||||
db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "migration-rollback.db"))
|
||||
ib := model.Inbound{
|
||||
UserId: 1, Tag: "migration-rollback", Port: 24443, Protocol: model.VLESS,
|
||||
Settings: `{"clients":[]}`, StreamSettings: `{"network":"tcp"}`,
|
||||
ShareAddrStrategy: "custom", ShareAddr: " example.test ",
|
||||
}
|
||||
if err := db.Create(&ib).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
orphan := xray.ClientTraffic{InboundId: ib.Id, Email: "orphan@x"}
|
||||
if err := db.Create(&orphan).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`CREATE TRIGGER reject_orphan_cleanup BEFORE DELETE ON client_traffics
|
||||
WHEN OLD.email = 'orphan@x' BEGIN SELECT RAISE(ABORT, 'injected orphan cleanup failure'); END`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := &InboundService{}
|
||||
if err := svc.MigrateDB(); err == nil || !strings.Contains(err.Error(), "injected orphan cleanup failure") {
|
||||
t.Fatalf("migration error=%v, want the orphan cleanup failure", err)
|
||||
}
|
||||
var stored model.Inbound
|
||||
if err := db.First(&stored, ib.Id).Error; err != nil || stored.ShareAddr != ib.ShareAddr {
|
||||
t.Fatalf("requirements leaked from rolled back migration: share_addr=%q err=%v", stored.ShareAddr, err)
|
||||
}
|
||||
if err := db.Exec("DROP TRIGGER reject_orphan_cleanup").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.MigrateDB(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.First(&stored, ib.Id).Error; err != nil || stored.ShareAddr != "example.test" {
|
||||
t.Fatalf("retried migration did not normalize the inbound: share_addr=%q err=%v", stored.ShareAddr, err)
|
||||
}
|
||||
var remaining int64
|
||||
if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", orphan.Email).Count(&remaining).Error; err != nil || remaining != 0 {
|
||||
t.Fatalf("retried migration left %d orphaned stats: %v", remaining, err)
|
||||
}
|
||||
}
|
||||
@@ -2038,7 +2038,9 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err
|
||||
|
||||
restoreHostBoundSettings(keptSettings)
|
||||
|
||||
s.inboundService.MigrateDB()
|
||||
if err := s.inboundService.MigrateDB(); err != nil {
|
||||
return common.NewErrorf("Imported DB but inbound migration failed: %v; the previous database was kept at %s", err, fallbackPath)
|
||||
}
|
||||
|
||||
xrayStopped = false
|
||||
if err = s.restartXrayService(XrayOriginDatabaseRestore); err != nil {
|
||||
@@ -2286,11 +2288,12 @@ func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSetting
|
||||
}
|
||||
restoreHostBoundSettings(keptSettings)
|
||||
|
||||
s.inboundService.MigrateDB()
|
||||
|
||||
if runErr != nil {
|
||||
return common.NewErrorf("pg_restore failed (database left unchanged): %v: %s", runErr, strings.TrimSpace(stderr.String()))
|
||||
}
|
||||
if err := s.inboundService.MigrateDB(); err != nil {
|
||||
return common.NewErrorf("Restored DB but inbound migration failed: %v", err)
|
||||
}
|
||||
|
||||
xrayStopped = false
|
||||
if err := s.restartXrayService(XrayOriginDatabaseRestore); err != nil {
|
||||
@@ -2360,11 +2363,12 @@ func (s *ServerService) migrateSQLiteIntoPostgres(file multipart.File, isSQLDump
|
||||
if migrateErr == nil {
|
||||
restoreHostBoundSettings(keptSettings)
|
||||
}
|
||||
s.inboundService.MigrateDB()
|
||||
|
||||
if migrateErr != nil {
|
||||
return common.NewErrorf("Importing the SQLite data into PostgreSQL failed: %v; the import runs in a single transaction, so the database was left unchanged", migrateErr)
|
||||
}
|
||||
if err := s.inboundService.MigrateDB(); err != nil {
|
||||
return common.NewErrorf("Imported DB but inbound migration failed: %v", err)
|
||||
}
|
||||
|
||||
xrayStopped = false
|
||||
if err := s.restartXrayService(XrayOriginDatabaseRestore); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user