diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 73f7498be..d7129f87a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -238,6 +238,16 @@ jobs: exit 1 fi + - name: PostgreSQL inbound migration contention + run: | + set -o pipefail + go test -p=1 ./internal/database ./internal/web/service -run '^(TestInitDBKeepsRestorePoolPrivate|TestMigrationRequirementsRejectsLiveNodeMergePostgres|TestInboundMigrationAllowsPostgresReaders)$' -count=1 -v | tee /tmp/postgres-inbound-migration.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-inbound-migration.log || true) + if [ "$passed" -ne 3 ]; then + echo "expected 3 passing PostgreSQL inbound migration and restore tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL slim inbound cache regressions run: | set -o pipefail diff --git a/install.sh b/install.sh index e8008aa4d..5f56d462c 100644 --- a/install.sh +++ b/install.sh @@ -1473,8 +1473,6 @@ EOF echo -e "${green}SSL certificate already configured. No action needed.${plain}" fi fi - - ${xui_folder}/x-ui migrate } xui_env_file_path() { @@ -1961,6 +1959,10 @@ install_x-ui() { chmod +x /usr/bin/x-ui mkdir -p /var/log/x-ui config_after_install + if ! "${xui_folder}/x-ui" migrate; then + echo -e "${red}ERROR: Database migration failed; stopping installation.${plain}" >&2 + exit 1 + fi setup_fail2ban "$fail2ban_mode" # Etckeeper compatibility diff --git a/internal/database/db.go b/internal/database/db.go index 21c4f0199..9cdf97862 100644 --- a/internal/database/db.go +++ b/internal/database/db.go @@ -37,9 +37,11 @@ import ( "gorm.io/gorm/logger" ) -var db *gorm.DB - -var connectionGeneration atomic.Uint64 +var ( + db *gorm.DB + publishedDB atomic.Pointer[gorm.DB] + connectionGeneration atomic.Uint64 +) // ConnectionGeneration invalidates read histories when InitDB replaces the database pool. func ConnectionGeneration() uint64 { return connectionGeneration.Load() } @@ -52,13 +54,11 @@ const ( ) func IsPostgres() bool { - if db == nil { - return config.GetDBKind() == "postgres" - } - return db.Name() == "postgres" + return config.GetDBKind() == DialectPostgres } func Dialect() string { + db := GetDB() if db == nil { return "" } @@ -3495,6 +3495,13 @@ func isTableEmpty(tableName string) (bool, error) { } func InitDB(dbPath string) error { + return InitDBBeforePublish(dbPath, nil) +} + +// InitDBBeforePublish initializes a replacement pool and runs finish before +// making it visible to requests and jobs. If finish fails, the initialized +// pool is still published so the panel can report the error and recover. +func InitDBBeforePublish(dbPath string, finish func(*gorm.DB) error) error { var gormLogger logger.Interface if config.IsDebug() { gormLogger = logger.New( @@ -3600,8 +3607,13 @@ func InitDB(dbPath string) error { if err := runSeeders(isUsersEmpty); err != nil { return err } + var finishErr error + if finish != nil { + finishErr = finish(db) + } + publishedDB.Store(db) connectionGeneration.Add(1) - return nil + return finishErr } func normalizeApiTokenCreatedAtSeconds() error { @@ -3733,7 +3745,7 @@ func CloseDB() error { } func GetDB() *gorm.DB { - return db + return publishedDB.Load() } func IsNotFound(err error) bool { diff --git a/internal/database/db_reopen_test.go b/internal/database/db_reopen_test.go index c3c856161..ccec56542 100644 --- a/internal/database/db_reopen_test.go +++ b/internal/database/db_reopen_test.go @@ -1,8 +1,12 @@ package database import ( + "database/sql" + "errors" "path/filepath" "testing" + + "gorm.io/gorm" ) // A replaced pool that stays open keeps its database file open; Windows then @@ -25,3 +29,28 @@ func TestInitDBClosesThePoolItReplaces(t *testing.T) { t.Fatalf("replaced pool Ping() = %v, want sql: database is closed", err) } } + +func TestInitDBKeepsRestorePoolPrivate(t *testing.T) { + initMigrateDB(t) + previous := GetDB() + dbPath := filepath.Join(t.TempDir(), "restored.db") + finishErr := errors.New("restore migration failed") + var replacement *gorm.DB + err := InitDBBeforePublish(dbPath, func(db *gorm.DB) error { + replacement = db + if GetDB() != previous || db == previous { + t.Fatal("the replacement pool was visible during restore migration") + } + if err := GetDB().Exec("SELECT 1").Error; !errors.Is(err, sql.ErrConnDone) && + (err == nil || err.Error() != "sql: database is closed") { + t.Fatalf("request could still use the old pool: %v", err) + } + if err := db.Exec("SELECT 1").Error; err != nil { + t.Fatalf("restore could not use the replacement pool: %v", err) + } + return finishErr + }) + if !errors.Is(err, finishErr) || GetDB() != replacement { + t.Fatalf("restore failure was not surfaced with a usable pool: %v", err) + } +} diff --git a/internal/web/service/inbound_migration.go b/internal/web/service/inbound_migration.go index e3e96e192..5fa9671a5 100644 --- a/internal/web/service/inbound_migration.go +++ b/internal/web/service/inbound_migration.go @@ -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,39 +31,106 @@ 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) { - 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) - } - } - } else { - tx.Rollback() - } - }() +var errInboundMigrationBusy = errors.New("database is busy; retry the inbound migration after active database work has stopped") - if tx.Migrator().HasColumn(&model.Inbound{}, "all_time") { +func runInboundMigration(db *gorm.DB, repairSchema bool, migrate func(*gorm.DB) error) error { + started := time.Now() + err := db.Transaction(func(tx *gorm.DB) error { + if tx.Name() == database.DialectPostgres { + if err := preparePostgresInboundMigration(tx, repairSchema); err != nil { + return err + } + } + 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 lockInboundMigrationTables(tx *gorm.DB, tables, mode string) error { + err := tx.Exec("LOCK TABLE " + tables + " IN " + mode + " MODE NOWAIT").Error + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "55P03" { + return fmt.Errorf("%w: %w", errInboundMigrationBusy, err) + } + if err != nil { + return fmt.Errorf("lock inbound migration tables: %w", err) + } + return nil +} + +func preparePostgresInboundMigration(tx *gorm.DB, repairSchema bool) error { + // EXCLUSIVE admits plain SELECTs and excludes writes and SELECT FOR UPDATE. + // Acquire the complete write set before DDL or DML, without waiting behind a live writer. + if err := lockInboundMigrationTables(tx, "inbounds, client_traffics, clients, client_inbounds, client_groups", "EXCLUSIVE"); err != nil || !repairSchema { + return err + } + + var changes []struct{ TableName, ColumnName string } + if err := tx.Raw(` + SELECT legacy.table_name, legacy.column_name + FROM (VALUES + ('inbounds', 'all_time'), ('client_traffics', 'all_time'), + ('inbounds', 'enable'), ('client_traffics', 'enable'), + ('clients', 'enable'), ('nodes', 'enable'), + ('api_tokens', 'enabled'), ('outbound_subscriptions', 'enabled') + ) AS legacy(table_name, column_name) + JOIN pg_catalog.pg_attribute AS a + ON a.attrelid = pg_catalog.to_regclass(legacy.table_name) + AND a.attname = legacy.column_name AND a.attnum > 0 AND NOT a.attisdropped + WHERE legacy.column_name = 'all_time' OR a.atttypid <> 'pg_catalog.bool'::regtype + ORDER BY legacy.table_name, legacy.column_name`).Scan(&changes).Error; err != nil { + return fmt.Errorf("inspect legacy inbound migration columns: %w", err) + } + var tables []string + for _, change := range changes { + if len(tables) == 0 || tables[len(tables)-1] != change.TableName { + tables = append(tables, change.TableName) + } + } + if len(tables) > 0 { + // ALTER TABLE needs ACCESS EXCLUSIVE, but upgraded schemas need no DDL. + if err := lockInboundMigrationTables(tx, strings.Join(tables, ", "), "ACCESS EXCLUSIVE"); err != nil { + return err + } + } + for _, change := range changes { + table, col := change.TableName, change.ColumnName + stmt := fmt.Sprintf("ALTER TABLE %s DROP COLUMN %s", table, col) + if col != "all_time" { + stmt = fmt.Sprintf("ALTER TABLE %s ALTER COLUMN %s TYPE boolean USING (CASE WHEN %s::text IN ('1','true','t','yes') THEN true ELSE false END)", table, col, col) + } + if err := tx.Exec(stmt).Error; err != nil { + return fmt.Errorf("normalize legacy column %s.%s: %w", table, col, err) + } + } + return nil +} + +func (s *InboundService) MigrationRequirements() error { + return runInboundMigration(database.GetDB(), true, s.migrationRequirements) +} + +func (s *InboundService) migrationRequirements(tx *gorm.DB) (err error) { + if tx.Name() == database.DialectSQLite && tx.Migrator().HasColumn(&model.Inbound{}, "all_time") { if err = tx.Migrator().DropColumn(&model.Inbound{}, "all_time"); err != nil { return } } - if tx.Migrator().HasColumn(&xray.ClientTraffic{}, "all_time") { + if tx.Name() == database.DialectSQLite && tx.Migrator().HasColumn(&xray.ClientTraffic{}, "all_time") { if err = tx.Migrator().DropColumn(&xray.ClientTraffic{}, "all_time"); err != nil { return } @@ -66,39 +139,6 @@ func (s *InboundService) MigrationRequirements() (err error) { return } - // Normalize "enable" columns to boolean on Postgres. Legacy SQLite data - // (0/1 integers), partial migrations, or mixed write paths (public API - // inbound updates that flow through UpdateClientStat + client syncs, plus - // node traffic merge deltas) can leave the column as integer or with mixed - // interpretation. This (combined with the dialect-aware - // ClientTrafficEnableMergeExpr) prevents type problems in the node traffic - // sync merge (SetRemoteTraffic) and makes the sync robust even when - // inbounds are updated via the public API (incl. ones carrying - // externalProxy in streamSettings). The same expression is also safe on - // SQLite (no PG :: casts). - if database.IsPostgres() { - // Use DO block so it is idempotent and doesn't fail if already boolean. - normalizeBool := func(table, col string) error { - return tx.Exec(fmt.Sprintf(` - DO $$ - BEGIN - IF EXISTS ( - SELECT 1 FROM information_schema.columns - WHERE table_name = '%s' AND column_name = '%s' - AND data_type <> 'boolean' - ) THEN - ALTER TABLE %s ALTER COLUMN %s - TYPE boolean USING (CASE WHEN %s::text IN ('1','true','t','yes') THEN true ELSE false END); - END IF; - END $$;`, table, col, table, col, col)).Error - } - for _, column := range [][2]string{{"inbounds", "enable"}, {"client_traffics", "enable"}, {"nodes", "enable"}, {"clients", "enable"}, {"api_tokens", "enabled"}, {"outbound_subscriptions", "enabled"}} { - if err = normalizeBool(column[0], column[1]); err != nil { - return - } - } - } - // Fix inbounds based problems var inbounds []*model.Inbound err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan", "shadowsocks", "hysteria"}).Find(&inbounds).Error @@ -286,12 +326,20 @@ 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 s.migrateDB(database.GetDB()) +} + +func (s *InboundService) migrateDB(db *gorm.DB) error { + return runInboundMigration(db, true, 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 +350,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(database.GetDB(), false, 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 } diff --git a/internal/web/service/inbound_migration_contention_test.go b/internal/web/service/inbound_migration_contention_test.go new file mode 100644 index 000000000..f2039bbbd --- /dev/null +++ b/internal/web/service/inbound_migration_contention_test.go @@ -0,0 +1,204 @@ +package service + +import ( + "context" + "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 TestInboundMigrationAllowsPostgresReaders(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL table locks") + } + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "migration-reader.db")) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + reader := db.WithContext(ctx).Begin() + if reader.Error != nil { + t.Fatal(reader.Error) + } + defer reader.Rollback() + if err := reader.Exec("SELECT id FROM inbounds").Error; err != nil { + t.Fatal(err) + } + + if err := runInboundMigration(db, true, func(tx *gorm.DB) error { + if err := db.WithContext(ctx).Exec("SELECT id FROM inbounds").Error; err != nil { + return fmt.Errorf("reader during migration: %w", err) + } + return tx.Exec("UPDATE inbounds SET remark = remark").Error + }); err != nil { + t.Fatalf("a pre-existing or new reader blocked the migration: %v", err) + } + if err := reader.Rollback().Error; err != nil { + t.Fatal(err) + } + + if err := db.Exec("ALTER TABLE inbounds ADD COLUMN all_time bigint").Error; err != nil { + t.Fatal(err) + } + reader = db.WithContext(ctx).Begin() + if reader.Error != nil { + t.Fatal(reader.Error) + } + defer reader.Rollback() + if err := reader.Exec("SELECT id FROM inbounds").Error; err != nil { + t.Fatal(err) + } + svc := &InboundService{} + if err := svc.MigrationRequirements(); !errors.Is(err, errInboundMigrationBusy) { + t.Fatalf("legacy DDL with a reader: %v, want immediate lock-conflict error", err) + } + if err := reader.Rollback().Error; err != nil { + t.Fatal(err) + } + if err := svc.MigrationRequirements(); err != nil || db.Migrator().HasColumn(&model.Inbound{}, "all_time") { + t.Fatalf("legacy column not removed after reader finished: %v", err) + } +} + +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) + } +} diff --git a/internal/web/service/server.go b/internal/web/service/server.go index d39f8f796..27bc2ab64 100644 --- a/internal/web/service/server.go +++ b/internal/web/service/server.go @@ -52,6 +52,7 @@ import ( "github.com/shirou/gopsutil/v4/host" "github.com/shirou/gopsutil/v4/load" "github.com/shirou/gopsutil/v4/mem" + "gorm.io/gorm" ) // ProcessState represents the current state of a system process. @@ -1888,14 +1889,13 @@ func captureHostBoundSettings() hostBoundSnapshot { } func restoreHostBoundSettings(snap hostBoundSnapshot) { - if !snap.taken { + restoreHostBoundSettingsOn(database.GetDB(), snap) +} + +func restoreHostBoundSettingsOn(db *gorm.DB, snap hostBoundSnapshot) { + if !snap.taken || db == nil { return } - db := database.GetDB() - if db == nil { - return - } - settingSvc := &SettingService{} for _, key := range hostBoundSettingKeys { if _, had := snap.present[key]; !had { // Absent because it is minted on demand, not because a default applied: @@ -1910,7 +1910,7 @@ func restoreHostBoundSettings(snap hostBoundSnapshot) { } // saveSetting rather than Assign(struct): GORM drops zero-valued fields from // the assignment map, so an empty local value never overwrote the import. - if err := settingSvc.saveSetting(key, snap.values[key]); err != nil { + if err := saveSettingOn(db, key, snap.values[key]); err != nil { logger.Warningf("Import: could not restore setting %q for this machine: %v", key, err) } } @@ -2045,7 +2045,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 { @@ -2210,7 +2212,12 @@ func sniffUploadKind(file multipart.File) (int, error) { return sniffImportKind(header[:n]), nil } +var postgresImportMu sync.Mutex + func (s *ServerService) importPostgresDB(file multipart.File, keepHostSettings bool) error { + postgresImportMu.Lock() + defer postgresImportMu.Unlock() + kind, err := sniffUploadKind(file) if err != nil { return common.NewErrorf("Error reading uploaded file: %v", err) @@ -2227,6 +2234,33 @@ func (s *ServerService) importPostgresDB(file multipart.File, keepHostSettings b } } +func (s *ServerService) reopenPostgresAfterImport(imported bool, keptSettings hostBoundSnapshot) error { + var migrationErr error + err := database.InitDBBeforePublish(config.GetDBPath(), func(db *gorm.DB) error { + if !imported { + return nil + } + restoreHostBoundSettingsOn(db, keptSettings) + // Jobs and requests still see the closed pool. Another process may + // briefly hold locks, so retry only lock acquisition, before any writes. + deadline := time.Now().Add(10 * time.Second) + for { + migrationErr = s.inboundService.migrateDB(db) + if !errors.Is(migrationErr, errInboundMigrationBusy) || time.Now().After(deadline) { + return migrationErr + } + time.Sleep(100 * time.Millisecond) + } + }) + if migrationErr != nil { + return fmt.Errorf("database data was imported, but inbound migration failed: %w", migrationErr) + } + if err != nil { + return fmt.Errorf("reopening PostgreSQL after import failed: %w", err) + } + return nil +} + func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSettings bool) error { bin, err := exec.LookPath("pg_restore") if err != nil { @@ -2288,17 +2322,13 @@ func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSetting cmd.Stderr = &stderr runErr := cmd.Run() - if errInit := database.InitDB(config.GetDBPath()); errInit != nil { - return common.NewErrorf("Restore finished but reopening the database failed: %v", errInit) + if err := s.reopenPostgresAfterImport(runErr == nil, keptSettings); err != nil { + return err } - restoreHostBoundSettings(keptSettings) - - s.inboundService.MigrateDB() if runErr != nil { return common.NewErrorf("pg_restore failed (database left unchanged): %v: %s", runErr, strings.TrimSpace(stderr.String())) } - xrayStopped = false if err := s.restartXrayService(XrayOriginDatabaseRestore); err != nil { return common.NewErrorf("Restored DB but failed to start Xray: %v", err) @@ -2361,18 +2391,12 @@ func (s *ServerService) migrateSQLiteIntoPostgres(file multipart.File, isSQLDump migrateErr := database.MigrateData(dbPath, config.GetDBDSN()) - if errInit := database.InitDB(config.GetDBPath()); errInit != nil { - return common.NewErrorf("Restore finished but reopening the database failed: %v", errInit) + if err := s.reopenPostgresAfterImport(migrateErr == nil, keptSettings); err != nil { + return err } - 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) } - xrayStopped = false if err := s.restartXrayService(XrayOriginDatabaseRestore); err != nil { return common.NewErrorf("Restored DB but failed to start Xray: %v", err) diff --git a/internal/web/service/setting.go b/internal/web/service/setting.go index f801e920e..f5ab63fc7 100644 --- a/internal/web/service/setting.go +++ b/internal/web/service/setting.go @@ -465,8 +465,12 @@ func (s *SettingService) getSetting(key string) (*model.Setting, error) { } func (s *SettingService) saveSetting(key string, value string) error { - setting, err := s.getSetting(key) - db := database.GetDB() + return saveSettingOn(database.GetDB(), key, value) +} + +func saveSettingOn(db *gorm.DB, key string, value string) error { + var setting model.Setting + err := db.Where("key = ?", key).First(&setting).Error if database.IsNotFound(err) { return db.Create(&model.Setting{ Key: key, @@ -477,7 +481,7 @@ func (s *SettingService) saveSetting(key string, value string) error { } setting.Key = key setting.Value = value - return db.Save(setting).Error + return db.Save(&setting).Error } func (s *SettingService) getString(key string) (string, error) { diff --git a/main.go b/main.go index 0f53f15cf..ce24b4db5 100644 --- a/main.go +++ b/main.go @@ -575,7 +575,9 @@ func migrateDb() { log.Fatal(err) } fmt.Println("Start migrating database...") - inboundService.MigrateDB() + if err := inboundService.MigrateDB(); err != nil { + log.Fatalf("Migration failed: %v", err) + } fmt.Println("Migration done!") } diff --git a/scripts_base_path_test.go b/scripts_base_path_test.go index 0fba126c7..540d7a30d 100644 --- a/scripts_base_path_test.go +++ b/scripts_base_path_test.go @@ -31,7 +31,11 @@ func scriptFunction(t *testing.T, script, name string) string { const settingsCLIMock = `#!/bin/bash set -eu state=$TEST_SETTINGS_DIR -if [[ "$1" == migrate ]]; then exit 0; fi +if [[ "$1" == migrate ]]; then + printf 'migrate\n' >> "$state/lifecycle" + if [[ "$TEST_READ_MODE" == migration_failure ]]; then exit 1; fi + exit 0 +fi shift case "$1" in -show) @@ -145,7 +149,8 @@ fail2ban_mode=install body := scriptFunction(t, script, parent) startCall := function if script == "update.sh" { - startCall = "setup_fail2ban" + startCall = `echo -e "${green}Migrating database...${plain}"` + driver += scriptFunction(t, script, "_fail") } start := strings.Index(body, "\n "+startCall) if start < 0 { @@ -274,7 +279,7 @@ func TestScriptConfigReadFailureKeepsServiceSetup(t *testing.T) { if err != nil || !strings.Contains(out, "Unable to read webBasePath") { t.Errorf("service setup should continue after the settings warning: %v\n%s", err, out) } - wantLifecycle, wantServices := "fail2ban\nunit\n", "daemon-reload\nenable x-ui\nstart x-ui\n" + wantLifecycle, wantServices := "migrate\nfail2ban\nunit\n", "daemon-reload\nenable x-ui\nstart x-ui\n" if script == "install.sh" { wantServices = "daemon-reload\nenable x-ui\nrestart x-ui\n" } @@ -289,3 +294,115 @@ func TestScriptConfigReadFailureKeepsServiceSetup(t *testing.T) { }) } } + +func TestInstallMigrationFailurePreventsServiceStart(t *testing.T) { + dir, out, err := runScriptConfig(t, "install.sh", "/a/", false, "migration_failure", 1, true) + if err == nil || !strings.Contains(out, "Database migration failed") { + t.Fatalf("migration failure should abort the update: %v\n%s", err, out) + } + if got := readScriptState(t, dir, "restarts"); got != "" { + t.Fatalf("service started after a failed migration: %q", got) + } + if got := readScriptState(t, dir, "lifecycle"); got != "migrate\n" { + t.Fatalf("lifecycle after failed migration: %q", got) + } +} + +func TestUpdateMigrationFailureKeepsServiceUnitForRetry(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("updater regression requires a POSIX environment") + } + bash, err := exec.LookPath("bash") + if err != nil { + t.Skip("bash is required for the isolated updater regression") + } + for _, distro := range []struct { + name, unit, stopped, started string + }{ + {"ubuntu", "systemd/x-ui.service", "systemctl stop x-ui\nsystemctl disable x-ui\n", "systemctl daemon-reload\nsystemctl enable x-ui\nsystemctl start x-ui\n"}, + {"alpine", "init.d/x-ui", "rc-service x-ui stop\nrc-update del x-ui\n", "rc-update add x-ui\nrc-service x-ui start\n"}, + } { + t.Run(distro.name, func(t *testing.T) { + dir := t.TempDir() + for _, folder := range []string{"x-ui", "systemd", "init.d", "release/x-ui", "bin"} { + if err := os.MkdirAll(filepath.Join(dir, folder), 0o700); err != nil { + t.Fatal(err) + } + } + const binary = `#!/bin/bash +if [[ $1 == migrate ]]; then + printf 'migrate\n' >> "$TEST_ROOT/events" + [[ $TEST_FAIL_MIGRATION == 0 ]] +else + printf 'test version\n' +fi +` + for name, value := range map[string]string{ + distro.unit: "old unit\n", "x-ui/x-ui": binary, "release/x-ui/x-ui": binary, + "release/x-ui/x-ui.sh": "#!/bin/bash\n", "release/x-ui/x-ui.service": "new unit\n", + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(value), 0o700); err != nil { + t.Fatal(err) + } + } + driver := `red= green= yellow= blue= plain= +xui_folder="$TEST_ROOT/x-ui" +xui_service="$TEST_ROOT/systemd" +release="$TEST_DISTRO" +XUI_UPDATE_TAG=test +curl_bin=fake_curl +load_xui_env() { :; } +setup_fail2ban() { :; } +config_after_update() { :; } +_xui_service_write_paths_dropin() { :; } +_xui_warn_unsupported_hardening() { :; } +chown() { :; } +pkill() { :; } +systemctl() { printf 'systemctl %s\n' "$*" >> "$TEST_ROOT/events"; } +rc-service() { printf 'rc-service %s\n' "$*" >> "$TEST_ROOT/events"; } +rc-update() { printf 'rc-update %s\n' "$*" >> "$TEST_ROOT/events"; } +fake_curl() { + case "$*" in + *.sha256) printf 404 ;; + */x-ui.rc) printf 'new unit\n' > "$2" ;; + *) tar -czf "$2" -C "$TEST_ROOT/release" x-ui ;; + esac +} +` + driver += scriptFunction(t, "update.sh", "_fail") + scriptFunction(t, "update.sh", "_install_xui_service_unit") + driver += strings.NewReplacer( + "/etc/init.d/x-ui", "$TEST_ROOT/init.d/x-ui", + "/usr/bin/x-ui", "$TEST_ROOT/bin/x-ui", + "/var/log/x-ui", "$TEST_ROOT/log", + ).Replace(scriptFunction(t, "update.sh", "update_x-ui")) + driver += "update_x-ui\n" + + run := func(failMigration string) (string, error) { + t.Helper() + cmd := exec.Command(bash, "-c", driver) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "TEST_ROOT="+dir, "TEST_DISTRO="+distro.name, "TEST_FAIL_MIGRATION="+failMigration) + out, err := cmd.CombinedOutput() + return string(out), err + } + if out, err := run("1"); err == nil || !strings.Contains(out, "Database migration failed") { + t.Fatalf("first update should fail in migration: %v\n%s", err, out) + } + if unit := readScriptState(t, dir, distro.unit); unit != "old unit\n" { + t.Fatalf("failed update changed the service unit: %q", unit) + } + if got := readScriptState(t, dir, "events"); got != distro.stopped+"migrate\n" { + t.Fatalf("failed update service actions: %q", got) + } + if out, err := run("0"); err != nil { + t.Fatalf("ordinary update retry failed: %v\n%s", err, out) + } + if unit := readScriptState(t, dir, distro.unit); unit != "new unit\n" { + t.Fatalf("retry did not install the replacement unit: %q", unit) + } + if got := readScriptState(t, dir, "events"); got != strings.Repeat(distro.stopped+"migrate\n", 2)+distro.started { + t.Fatalf("retry service actions: %q", got) + } + }) + } +} diff --git a/update.sh b/update.sh index 7d7e3a1ff..6c1b1299b 100755 --- a/update.sh +++ b/update.sh @@ -172,7 +172,6 @@ config_after_update() { echo -e "${yellow}x-ui settings:${plain}" ${xui_folder}/x-ui setting -show true - ${xui_folder}/x-ui migrate # Properly detect empty cert by checking if cert: line exists and has content after it local existing_cert=$(${xui_folder}/x-ui setting -getCert true 2> /dev/null | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]') @@ -578,12 +577,12 @@ update_x-ui() { if [[ -e ${xui_folder}/ ]]; then echo -e "${green}Stopping x-ui...${plain}" + # Keep the stopped, disabled unit in place so an update can be retried + # if migration fails before the replacement unit is installed. if [[ $release == "alpine" ]]; then if [ -f "/etc/init.d/x-ui" ]; then rc-service x-ui stop > /dev/null 2>&1 rc-update del x-ui > /dev/null 2>&1 - echo -e "${green}Removing old service unit version...${plain}" - rm -f /etc/init.d/x-ui > /dev/null 2>&1 else rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1 _fail "ERROR: x-ui service unit not installed." @@ -592,9 +591,6 @@ update_x-ui() { if [ -f "${xui_service}/x-ui.service" ]; then systemctl stop x-ui > /dev/null 2>&1 systemctl disable x-ui > /dev/null 2>&1 - echo -e "${green}Removing old systemd unit version...${plain}" - rm ${xui_service}/x-ui.service -f > /dev/null 2>&1 - systemctl daemon-reload > /dev/null 2>&1 else rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1 _fail "ERROR: x-ui systemd unit not installed." @@ -608,10 +604,12 @@ update_x-ui() { pkill -f 'tuic-server.*-c .*bin/tuic/tuic_[0-9]+\.json' > /dev/null 2>&1 || true echo -e "${green}Removing old x-ui version...${plain}" rm ${xui_folder} -f > /dev/null 2>&1 - rm ${xui_folder}/x-ui.service -f > /dev/null 2>&1 - rm ${xui_folder}/x-ui.service.debian -f > /dev/null 2>&1 - rm ${xui_folder}/x-ui.service.arch -f > /dev/null 2>&1 - rm ${xui_folder}/x-ui.service.rhel -f > /dev/null 2>&1 + local template + for template in x-ui.service x-ui.service.debian x-ui.service.arch x-ui.service.rhel; do + if [[ ! "${xui_folder}/${template}" -ef "${xui_service}/x-ui.service" ]]; then + rm -f "${xui_folder}/${template}" > /dev/null 2>&1 + fi + done rm ${xui_folder}/x-ui -f > /dev/null 2>&1 rm ${xui_folder}/x-ui.sh -f > /dev/null 2>&1 echo -e "${green}Removing old mtg version...${plain}" @@ -680,10 +678,14 @@ update_x-ui() { chmod 640 ${xui_folder}/bin/config.json > /dev/null 2>&1 fi - # Finish the schema/data migrations before the service starts, so the service and - # config_after_update's CLI calls never run them on the same database at once (#6728). + # Finish the schema/data migrations before the service starts. echo -e "${green}Migrating database...${plain}" - "${xui_folder}/x-ui" migrate + if ! "${xui_folder}/x-ui" migrate; then + if [[ $release == "alpine" ]]; then + rm -f "${xui_rc_temp}" + fi + _fail "ERROR: Database migration failed; x-ui was not started. Fix the migration error and rerun the update." + fi setup_fail2ban if [[ $release == "alpine" ]]; then