mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +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.
215 lines
7.0 KiB
Go
215 lines
7.0 KiB
Go
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")
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond)
|
|
defer cancel()
|
|
lease, err := database.TryConfiguredMaintenance(ctx, true)
|
|
if lease != nil {
|
|
_ = lease.Close()
|
|
}
|
|
if !errors.Is(err, database.ErrMaintenanceBusy) {
|
|
t.Fatalf("migration lease while node transaction is active: %v, want busy", err)
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|