Files
mirror-3x-ui/internal/web/service/inbound_migration.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

387 lines
13 KiB
Go

package service
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"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() {
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"),
database.JSONClientsFromInbound(),
)
result := db.Exec(query)
if result.Error != nil {
return result.Error
}
if result.RowsAffected > 0 {
logger.Infof("MigrationRemoveOrphanedTraffics: removed %d orphaned client_traffics row(s)", result.RowsAffected)
}
return nil
}
var errInboundMigrationBusy = errors.New("database is busy; retry the inbound migration after active database work has stopped")
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.Name() == database.DialectSQLite && tx.Migrator().HasColumn(&xray.ClientTraffic{}, "all_time") {
if err = tx.Migrator().DropColumn(&xray.ClientTraffic{}, "all_time"); err != nil {
return
}
}
if err = normalizeInboundShareAddressColumns(tx); 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
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return
}
for inbound_index := range inbounds {
settings := map[string]any{}
_ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
if raw, exists := settings["clients"]; exists && raw == nil {
settings["clients"] = []any{}
}
clients, ok := settings["clients"].([]any)
if ok {
// Fix Client configuration problems
newClients := make([]any, 0, len(clients))
hasVisionFlow := false
for client_index := range clients {
c := clients[client_index].(map[string]any)
// Add email='' if it is not exists
if _, ok := c["email"]; !ok {
c["email"] = ""
}
// Convert string tgId to int64
if _, ok := c["tgId"]; ok {
tgId := c["tgId"]
if tgIdStr, ok2 := tgId.(string); ok2 {
tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
if err == nil {
c["tgId"] = tgIdInt64
}
}
}
// Remove "flow": "xtls-rprx-direct"
if _, ok := c["flow"]; ok {
if c["flow"] == "xtls-rprx-direct" {
c["flow"] = ""
}
}
if flow, _ := c["flow"].(string); flow == "xtls-rprx-vision" {
hasVisionFlow = true
}
// Backfill created_at and updated_at
if _, ok := c["created_at"]; !ok {
c["created_at"] = time.Now().Unix() * 1000
}
c["updated_at"] = time.Now().Unix() * 1000
newClients = append(newClients, any(c))
}
settings["clients"] = newClients
// Drop orphaned testseed: VLESS-only field, only meaningful when at least
// one client uses the exact xtls-rprx-vision flow. Older versions saved it
// for any non-empty flow (including the UDP variant) or kept it after the
// flow was cleared from the client modal — clean those up here.
if inbounds[inbound_index].Protocol == model.VLESS && !hasVisionFlow {
delete(settings, "testseed")
}
var modifiedSettings []byte
modifiedSettings, err = json.MarshalIndent(settings, "", " ")
if err != nil {
return
}
inbounds[inbound_index].Settings = string(modifiedSettings)
}
// Add client traffic row for all clients which has email
var modelClients []model.Client
modelClients, err = s.GetClients(inbounds[inbound_index])
if err != nil {
return
}
for _, modelClient := range modelClients {
if len(modelClient.Email) > 0 {
var count int64
if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count).Error; err != nil {
return
}
if count == 0 {
if err = s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient); err != nil {
return
}
}
}
}
// Heal clients table for installs where the one-shot seeder
// skipped clients due to a tgId-string unmarshal error.
if err = s.clientService.SyncInbound(tx, inbounds[inbound_index].Id, modelClients); err != nil {
return
}
}
if err = saveInChunks(tx, inbounds); err != nil {
return
}
// Remove orphaned traffics
if err = tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{}).Error; err != nil {
return
}
// Migrate old MultiDomain to External Proxy
var externalProxy []struct {
Id int
Port int
StreamSettings string // text column on both DBs; safer than []byte for cross-DB scan
}
externalProxyQuery := `select id, port, stream_settings
from inbounds
WHERE protocol in ('vmess','vless','trojan')
AND json_extract(stream_settings, '$.security') = 'tls'
AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`
if database.IsPostgres() {
externalProxyQuery = `select id, port, stream_settings
from inbounds
WHERE protocol in ('vmess','vless','trojan')
AND NULLIF(stream_settings, '')::jsonb #>> '{security}' = 'tls'
AND NULLIF(stream_settings, '')::jsonb #> '{tlsSettings,settings,domains}' IS NOT NULL`
}
err = tx.Raw(externalProxyQuery).Scan(&externalProxy).Error
if err != nil || len(externalProxy) == 0 {
return
}
for _, ep := range externalProxy {
var reverses any
var stream map[string]any
_ = json.Unmarshal([]byte(ep.StreamSettings), &stream)
if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
if settings, ok := tlsSettings["settings"].(map[string]any); ok {
if domains, ok := settings["domains"].([]any); ok {
for _, domain := range domains {
if domainMap, ok := domain.(map[string]any); ok {
domainMap["forceTls"] = "same"
domainMap["port"] = ep.Port
domainMap["dest"] = domainMap["domain"].(string)
delete(domainMap, "domain")
}
}
}
reverses = settings["domains"]
delete(settings, "domains")
}
}
stream["externalProxy"] = reverses
newStream, marshalErr := json.MarshalIndent(stream, " ", " ")
if marshalErr != nil {
err = marshalErr
return
}
if err = tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream).Error; err != nil {
return
}
}
// Legacy tag cleanup for old auto-generated tags (e.g. "0.0.0.0:443-...").
// Must be cross-DB: INSTR/REPLACE work on SQLite; Postgres needs position().
tagCleanup := `UPDATE inbounds
SET tag = REPLACE(tag, '0.0.0.0:', '')
WHERE INSTR(tag, '0.0.0.0:') > 0
AND NOT EXISTS (
SELECT 1 FROM inbounds AS other
WHERE other.id <> inbounds.id
AND other.tag = REPLACE(inbounds.tag, '0.0.0.0:', '')
);`
if database.IsPostgres() {
tagCleanup = `UPDATE inbounds AS i
SET tag = REPLACE(tag, '0.0.0.0:', '')
WHERE position('0.0.0.0:' in tag) > 0
AND NOT EXISTS (
SELECT 1 FROM inbounds AS other
WHERE other.id <> i.id
AND other.tag = REPLACE(i.tag, '0.0.0.0:', '')
);`
}
err = tx.Exec(tagCleanup).Error
if err != nil {
return
}
return err
}
func (s *InboundService) MigrateDB() error {
return s.MigrateDBOn(database.GetDB())
}
// MigrateDBOn runs inbound repair through the caller's database connection.
func (s *InboundService) MigrateDBOn(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
// XTLS Vision flow because the inbound was not flow-eligible when the client was
// written (e.g. an XHTTP inbound whose vlessenc encryption was enabled only
// later). For each now-eligible inbound it restores flow=xtls-rprx-vision on
// clients whose intended flow (their flow_override on a sibling inbound) is
// 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() {
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 := tx.Model(&model.Inbound{}).
Where("protocol = ?", model.VLESS).
Find(&inbounds).Error; err != nil {
return fmt.Errorf("load VLESS inbounds for flow migration: %w", err)
}
for _, ib := range inbounds {
if ib.DisableFlow {
continue
}
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 {
return fmt.Errorf("parse clients for inbound %d during flow migration: %w", ib.Id, err)
}
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)
}
}
return nil
}