From 783e0c54383c84250b05526f9cbc57bdb5595172 Mon Sep 17 00:00:00 2001 From: Hamed Date: Sun, 29 Nov 2026 17:03:00 +0330 Subject: [PATCH] feat(xray): report managed core lifecycle outcomes (#7264) At the default log level an operator could see the Xray child PID change many times a day without learning which of those changes the panel caused, or why. Write one xray_lifecycle line for every real start, stop, restart, hot apply, rejected config and unexpected child exit. It carries the old and new PID, the path that asked (manual, watchdog, client depletion, pending restart and its first trigger, ...), a fixed reason, the force flag, the duration, the hot-apply outcome and the previous child's exit code or signal. An unchanged config still emits nothing and restart policy is unchanged. A hot apply the core refuses also logs the core's own error once, with the inbound tag or client it concerned, so a restart labelled hot_apply_failed can be traced to its cause. Fixes #7260 --- internal/web/job/check_xray_running_job.go | 2 +- internal/web/job/node_traffic_sync_job.go | 4 +- internal/web/job/xray_traffic_job.go | 4 +- internal/web/service/server.go | 38 ++- .../web/service/tuic_relay_lifecycle_test.go | 8 +- .../web/service/tuic_user_routing_test.go | 2 +- .../web/service/wireguard_hot_apply_test.go | 2 +- internal/web/service/xray.go | 212 ++++++++++---- .../service/xray_hot_apply_persist_test.go | 5 + internal/web/service/xray_lifecycle_reason.go | 55 ++++ .../service/xray_lifecycle_telemetry_test.go | 260 ++++++++++++++++++ internal/web/service/xray_restart_test.go | 13 +- internal/web/web.go | 8 +- internal/xray/lifecycle.go | 64 +++++ internal/xray/process.go | 46 ++-- internal/xray/process_test.go | 44 +++ main.go | 4 +- 17 files changed, 660 insertions(+), 111 deletions(-) create mode 100644 internal/web/service/xray_lifecycle_reason.go create mode 100644 internal/web/service/xray_lifecycle_telemetry_test.go create mode 100644 internal/xray/lifecycle.go diff --git a/internal/web/job/check_xray_running_job.go b/internal/web/job/check_xray_running_job.go index 51e4488d7..8e2dcfd25 100644 --- a/internal/web/job/check_xray_running_job.go +++ b/internal/web/job/check_xray_running_job.go @@ -30,7 +30,7 @@ func (j *CheckXrayRunningJob) Run() { j.checkTime++ // only restart if it's down 2 times in a row if j.checkTime > 1 { - err := j.xrayService.RestartXray(false) + err := j.xrayService.RestartXrayFrom(false, service.XrayOriginWatchdog) j.checkTime = 0 if err != nil { logger.Error("Restart xray failed:", err) diff --git a/internal/web/job/node_traffic_sync_job.go b/internal/web/job/node_traffic_sync_job.go index 976ed2f31..882848dbe 100644 --- a/internal/web/job/node_traffic_sync_job.go +++ b/internal/web/job/node_traffic_sync_job.go @@ -153,9 +153,9 @@ func (j *NodeTrafficSyncJob) Run() { if restartOnDisable, settingErr := j.settingService.GetRestartXrayOnClientDisable(); settingErr == nil && restartOnDisable { // Not forced: a client only nodes serve leaves the local config unchanged, and a node // deciding when this tick disables clients must not decide when local users drop. - if err := j.xrayService.RestartXray(false); err != nil { + if err := j.xrayService.RestartXrayFrom(false, service.XrayOriginClientDepletion); err != nil { logger.Warning("node traffic sync: restart xray after disabling clients failed:", err) - j.xrayService.SetToNeedRestart() + j.xrayService.SetToNeedRestartFrom(service.XrayOriginNodeTrafficSync) } } else if settingErr != nil { logger.Warning("node traffic sync: get RestartXrayOnClientDisable failed:", settingErr) diff --git a/internal/web/job/xray_traffic_job.go b/internal/web/job/xray_traffic_job.go index 559f6d757..62b70a6b3 100644 --- a/internal/web/job/xray_traffic_job.go +++ b/internal/web/job/xray_traffic_job.go @@ -127,7 +127,7 @@ func (j *XrayTrafficJob) Run() { if restartOnDisable { if !j.xrayService.IsXrayRunning() { needRestart = true - } else if err := j.xrayService.RestartXray(false); err != nil { + } else if err := j.xrayService.RestartXrayFrom(false, service.XrayOriginClientDepletion); err != nil { logger.Warning("reconcile xray after disabling clients failed:", err) needRestart = true } @@ -135,7 +135,7 @@ func (j *XrayTrafficJob) Run() { websocket.BroadcastInvalidate(websocket.MessageTypeInbounds) } if needRestart { - j.xrayService.SetToNeedRestart() + j.xrayService.SetToNeedRestartFrom(service.XrayOriginTrafficAccounting) } if enabled, err := j.settingService.GetExternalTrafficInformEnable(); err != nil { logger.Warning("get ExternalTrafficInformEnable failed:", err) diff --git a/internal/web/service/server.go b/internal/web/service/server.go index 1ecf4ce85..395dfaf74 100644 --- a/internal/web/service/server.go +++ b/internal/web/service/server.go @@ -1029,7 +1029,11 @@ func (s *ServerService) GetXrayVersions() ([]string, error) { } func (s *ServerService) StopXrayService() error { - err := s.xrayService.StopXray() + return s.stopXrayService(XrayOriginManual) +} + +func (s *ServerService) stopXrayService(origin XrayOrigin) error { + err := s.xrayService.StopXrayFrom(origin) if err != nil { logger.Error("stop xray failed:", err) return err @@ -1038,7 +1042,11 @@ func (s *ServerService) StopXrayService() error { } func (s *ServerService) RestartXrayService() error { - err := s.xrayService.RestartXray(true) + return s.restartXrayService(XrayOriginManual) +} + +func (s *ServerService) restartXrayService(origin XrayOrigin) error { + err := s.xrayService.RestartXrayFrom(true, origin) if err != nil { logger.Error("start xray failed:", err) return err @@ -1271,7 +1279,7 @@ func (s *ServerService) UpdateXray(version string) error { if runtime.GOOS == "windows" { // Windows cannot replace a running executable. - if err := s.StopXrayService(); err != nil { + if err := s.stopXrayService(XrayOriginBinaryUpdate); err != nil { logger.Warning("failed to stop xray before update:", err) } _ = os.Remove(target) @@ -1280,7 +1288,7 @@ func (s *ServerService) UpdateXray(version string) error { return err } - if err := s.xrayService.RestartXray(true); err != nil { + if err := s.xrayService.RestartXrayFrom(true, XrayOriginBinaryUpdate); err != nil { logger.Error("start xray failed:", err) return fmt.Errorf("xray %s is installed, but the restart failed: %w", version, err) } @@ -1964,12 +1972,12 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err xrayStopped := true defer func() { if xrayStopped { - if errR := s.RestartXrayService(); errR != nil { + if errR := s.restartXrayService(XrayOriginDatabaseRestore); errR != nil { logger.Warningf("Failed to restart Xray after DB import error: %v", errR) } } }() - if errStop := s.StopXrayService(); errStop != nil { + if errStop := s.stopXrayService(XrayOriginDatabaseRestore); errStop != nil { logger.Warningf("Failed to stop Xray before DB import: %v", errStop) } @@ -2033,7 +2041,7 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err s.inboundService.MigrateDB() xrayStopped = false - if err = s.RestartXrayService(); err != nil { + if err = s.restartXrayService(XrayOriginDatabaseRestore); err != nil { return common.NewErrorf("Imported DB but failed to start Xray: %v; the previous database was kept at %s", err, fallbackPath) } @@ -2251,12 +2259,12 @@ func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSetting xrayStopped := true defer func() { if xrayStopped { - if errR := s.RestartXrayService(); errR != nil { + if errR := s.restartXrayService(XrayOriginDatabaseRestore); errR != nil { logger.Warningf("Failed to restart Xray after DB restore error: %v", errR) } } }() - if errStop := s.StopXrayService(); errStop != nil { + if errStop := s.stopXrayService(XrayOriginDatabaseRestore); errStop != nil { logger.Warningf("Failed to stop Xray before DB restore: %v", errStop) } @@ -2285,7 +2293,7 @@ func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSetting } xrayStopped = false - if err := s.RestartXrayService(); err != nil { + if err := s.restartXrayService(XrayOriginDatabaseRestore); err != nil { return common.NewErrorf("Restored DB but failed to start Xray: %v", err) } return nil @@ -2331,12 +2339,12 @@ func (s *ServerService) migrateSQLiteIntoPostgres(file multipart.File, isSQLDump xrayStopped := true defer func() { if xrayStopped { - if errR := s.RestartXrayService(); errR != nil { + if errR := s.restartXrayService(XrayOriginDatabaseRestore); errR != nil { logger.Warningf("Failed to restart Xray after DB restore error: %v", errR) } } }() - if errStop := s.StopXrayService(); errStop != nil { + if errStop := s.stopXrayService(XrayOriginDatabaseRestore); errStop != nil { logger.Warningf("Failed to stop Xray before DB restore: %v", errStop) } @@ -2359,7 +2367,7 @@ func (s *ServerService) migrateSQLiteIntoPostgres(file multipart.File, isSQLDump } xrayStopped = false - if err := s.RestartXrayService(); err != nil { + if err := s.restartXrayService(XrayOriginDatabaseRestore); err != nil { return common.NewErrorf("Restored DB but failed to start Xray: %v", err) } return nil @@ -2473,7 +2481,9 @@ type stagedGeofile struct { // restartXrayAfterGeofileUpdate is a seam: tests assert that an update which // installed nothing also restarted nothing. -var restartXrayAfterGeofileUpdate = (*ServerService).RestartXrayService +var restartXrayAfterGeofileUpdate = func(s *ServerService) error { + return s.restartXrayService(XrayOriginGeodataUpdate) +} func (s *ServerService) UpdateGeofile(fileName string) error { // Strict allowlist check to avoid writing uncontrolled files diff --git a/internal/web/service/tuic_relay_lifecycle_test.go b/internal/web/service/tuic_relay_lifecycle_test.go index 8cc8be889..fce39fb5a 100644 --- a/internal/web/service/tuic_relay_lifecycle_test.go +++ b/internal/web/service/tuic_relay_lifecycle_test.go @@ -18,11 +18,11 @@ func TestTuicFailedReconcileRetriesWithoutRequestingCoreRestart(t *testing.T) { t.Fatal(err) } wasStopped := isManuallyStopped.Swap(false) - wasRestart := isNeedXrayRestart.Swap(false) + wasRestart := pendingXrayRestart.Swap(nil) wasReconcile := isNeedXrayReconcile.Swap(false) t.Cleanup(func() { isManuallyStopped.Store(wasStopped) - isNeedXrayRestart.Store(wasRestart) + pendingXrayRestart.Store(wasRestart) isNeedXrayReconcile.Store(wasReconcile) }) svc := &XrayService{} @@ -32,8 +32,8 @@ func TestTuicFailedReconcileRetriesWithoutRequestingCoreRestart(t *testing.T) { t.Fatal(err) } svc.ApplyPendingRestart() - if isNeedXrayRestart.Load() || !isNeedXrayReconcile.Load() { - t.Fatalf("failed TUIC reconciliation became a core restart or lost retry: restart=%t reconcile=%t", isNeedXrayRestart.Load(), isNeedXrayReconcile.Load()) + if pendingXrayRestart.Load() != nil || !isNeedXrayReconcile.Load() { + t.Fatalf("failed TUIC reconciliation became a core restart or lost retry: restart=%t reconcile=%t", pendingXrayRestart.Load() != nil, isNeedXrayReconcile.Load()) } } diff --git a/internal/web/service/tuic_user_routing_test.go b/internal/web/service/tuic_user_routing_test.go index 385e09af6..e5fa8e55d 100644 --- a/internal/web/service/tuic_user_routing_test.go +++ b/internal/web/service/tuic_user_routing_test.go @@ -425,7 +425,7 @@ func verifyTuicHotUserUpdates(t *testing.T, initial *xray.Config, apiPort int, i } after.InboundConfigs = append(after.InboundConfigs, ordinary) diff, hot := xray.ComputeHotDiff(before, after) - if !hot || svc.restartToDropClients(diff) || applyTuicRelayReplacements(api, diff.TuicRelayChanges) != nil || !applyXrayHotDiff(api, diff) { + if !hot || svc.restartToDropClients(diff) || applyTuicRelayReplacements(api, diff.TuicRelayChanges) != nil || applyXrayHotDiff(api, diff).step != "" { t.Fatalf("account update requires a core restart: hot=%t diff=%+v", hot, diff) } native, err := (&InboundService{}).DesiredTuicInstances() diff --git a/internal/web/service/wireguard_hot_apply_test.go b/internal/web/service/wireguard_hot_apply_test.go index 6f02bbf79..ccf3e360e 100644 --- a/internal/web/service/wireguard_hot_apply_test.go +++ b/internal/web/service/wireguard_hot_apply_test.go @@ -84,7 +84,7 @@ func TestWireguardDeviceChangesKeepOtherCorePeers(t *testing.T) { if step.active && touched[0].User["keepAlive"] != "25" { t.Fatalf("%s: device peer lost the client's keepalive: %+v", step.name, touched[0].User) } - if !applyXrayHotDiff(api, diff) { + if applyXrayHotDiff(api, diff).step != "" { t.Fatalf("%s: peer update failed", step.name) } users, err := (*api.HandlerServiceClient).GetInboundUsers(t.Context(), &command.GetInboundUserRequest{Tag: inbound.Tag}) diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index e2c642998..e262e564f 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -10,6 +10,8 @@ import ( "slices" "strings" "sync" + "sync/atomic" + "time" "github.com/mhsanaei/3x-ui/v3/internal/amneziawg" "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet" @@ -20,15 +22,13 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/util/json_util" "github.com/mhsanaei/3x-ui/v3/internal/util/maskcompat" "github.com/mhsanaei/3x-ui/v3/internal/xray" - - "go.uber.org/atomic" ) var ( lock sync.Mutex isNeedXrayReconcile atomic.Bool - isNeedXrayRestart atomic.Bool // Indicates that restart was requested for Xray - isManuallyStopped atomic.Bool // Indicates that Xray was stopped manually from the panel + pendingXrayRestart atomic.Pointer[XrayOrigin] // First trigger in the pending restart batch + isManuallyStopped atomic.Bool // Indicates that Xray was stopped manually from the panel xrayState xrayLifecycle ) @@ -1540,6 +1540,19 @@ func (s *XrayService) TestRoute(req xray.RouteTestRequest) (*xray.RouteTestResul // routing rules/balancers are hot-reloadable); only changes the core cannot // take at runtime — or a force request — stop and restart the process. func (s *XrayService) RestartXray(isForce bool) error { + origin := XrayOriginConfigChange + if isForce { + origin = XrayOriginManual + } + return s.RestartXrayFrom(isForce, origin) +} + +// RestartXrayFrom records the initiating operation while applying the usual restart policy. +func (s *XrayService) RestartXrayFrom(isForce bool, origin XrayOrigin) error { + return s.restartXrayFrom(isForce, origin, "") +} + +func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin) error { lock.Lock() defer lock.Unlock() logger.Debug("restart Xray, force:", isForce) @@ -1547,19 +1560,38 @@ func (s *XrayService) RestartXray(isForce bool) error { return nil } isManuallyStopped.Store(false) + start := time.Now() + previous := currentXrayProcess() + oldPID, _ := previous.LifecycleState() + event := xray.LifecycleEvent{Origin: string(origin), Trigger: string(trigger), Force: isForce, OldPID: oldPID, HotApply: "not_attempted", Reason: "config_change"} + if isForce { + event.Reason = "forced" + } + defer func() { + if event.Event == "" { + return + } + event.Duration = time.Since(start) + _, event.Exit = previous.LifecycleState() + event.Log(event.Event == "start_failed" || event.Event == "apply_failed" || event.Event == "config_rejected" || event.StopResult == "failed") + }() xrayConfig, err := s.GetXrayConfig() if err != nil { - if process := currentXrayProcess(); process != nil && process.IsRunning() { + if previous != nil && previous.IsRunning() { xrayState.holdBack(fmt.Sprintf("config refused: %v", err)) + event.NewPID = oldPID } + event.Event, event.Reason = "config_rejected", "invalid_config" return err } - process := currentXrayProcess() - if process != nil && process.IsRunning() { + process := previous + wasRunning := process != nil && process.IsRunning() + if wasRunning { + event.NewPID = oldPID configUnchanged := process.GetConfig().Equals(xrayConfig) - if !isForce && configUnchanged && !isNeedXrayRestart.Load() { + if !isForce && configUnchanged && pendingXrayRestart.Load() == nil { logger.Debug("It does not need to restart Xray") return repairUnavailableTuicRelays(xrayConfig, process.GetAPIPort()) } @@ -1573,34 +1605,69 @@ func (s *XrayService) RestartXray(isForce bool) error { // The refusal is otherwise invisible: the operator's request // succeeded, so the status page has to carry the stale state. xrayState.holdBack(refused) + event.Event, event.Reason = "config_rejected", "bind_conflict" return fmt.Errorf("xray %s", refused) } if !isForce && !configUnchanged { - applied, err := s.tryHotApply(process, xrayConfig) + var failure hotApplyFailure + outcome, err := s.applyHotConfig(process, xrayConfig, &failure) + if failure.step != "" { + event.HotApplyStep, event.HotApplyCode = failure.step, failure.code() + logger.Info(failure.cause()) + } + event.HotApply = string(outcome) if err != nil { + event.Event, event.Reason = "apply_failed", "hot_apply_failed" return err } - if applied { - logger.Info("Xray config changes applied through the core API, no restart needed") + if outcome == hotApplied { + event.Event = "hot_applied" return nil } + event.Reason = string(outcome) + if outcome == hotFailed { + event.Reason = "hot_apply_failed" + } + } + if !isForce && configUnchanged { + event.Reason = "pending_restart" } invalidateTuicRelayReadiness(process.GetConfig()) invalidateTuicRelayReadiness(xrayConfig) - _ = process.Stop() + switch err := process.Stop(); { + case err == nil: + event.StopResult = "stopped" + case errors.Is(err, ErrXrayNotRunning): + event.StopResult = "already_exited" + default: + event.StopResult = "failed" + } } else if conflicts := bindConflicts(xrayConfig, nil); len(conflicts) > 0 { // Nothing is running to protect and the core is the authority on what it // can bind: start it and let its own error name the port it lost. logger.Warning("xray config may not start:", conflicts[0].String()) } + if !wasRunning && !isForce { + if origin == XrayOriginWatchdog && oldPID != 0 { + event.Reason = "crash_recovery" + } else { + event.Reason = "core_not_running" + } + } invalidateTuicRelayReadiness(xrayConfig) process = xray.NewProcess(xrayConfig) xrayState.replace(process) err = process.Start() + event.NewPID, _ = process.LifecycleState() if err != nil { + event.Event = "start_failed" return err } + event.Event = "started" + if event.StopResult == "stopped" { + event.Event = "restarted" + } if err := publishTuicRelayReadiness(xrayConfig); err != nil { return err @@ -1623,9 +1690,9 @@ func (s *XrayService) restartToDropClients(diff *xray.HotDiff) bool { return restart } -// tryHotApply reconciles the running core with newCfg over gRPC; false means restart, while a TUIC -// relay error defers that update instead of restarting unrelated connections. Hold the package lock. -func (s *XrayService) tryHotApply(process *xray.Process, newCfg *xray.Config) (applied bool, applyErr error) { +// applyHotConfig reconciles over gRPC while holding the package lock. +// A non-applied outcome permits restart only when no error is returned. +func (s *XrayService) applyHotConfig(process *xray.Process, newCfg *xray.Config, failure *hotApplyFailure) (outcome hotApplyOutcome, applyErr error) { defer func() { if applyErr != nil { s.SetToNeedReconcile() @@ -1634,43 +1701,42 @@ func (s *XrayService) tryHotApply(process *xray.Process, newCfg *xray.Config) (a oldCfg := process.GetConfig() diff, ok := xray.ComputeHotDiff(oldCfg, newCfg) if !ok { - logger.Debug("hot apply: config change is not API-applicable, falling back to restart") - return false, nil + return hotUnsupported, nil } if diff.Empty() { if err := repairUnavailableTuicRelays(newCfg, process.GetAPIPort()); err != nil { - return false, err + *failure = hotApplyFailure{step: "repair_tuic_relays", err: err} + return hotFailed, err } process.SetConfig(newCfg) persistHotConfig(process) - return true, nil + return hotApplied, nil } // The core's RemoveUser drops the credential only, so a disabled or deleted // client needs the restart this setting asks for. if s.restartToDropClients(diff) { - logger.Info("hot apply: clients left the config, restarting to drop their live sessions") - return false, nil + return hotClientsRemoved, nil } if tuicRequiresOrdinaryRemoval(oldCfg, diff.TuicRelayChanges) { - return false, nil + return hotUnsupported, nil } apiPort := process.GetAPIPort() if apiPort <= 0 { if len(diff.TuicRelayChanges) > 0 { - return false, errors.New("TUIC relay update requires the Xray HandlerService API") + return hotAPIUnavailable, errors.New("TUIC relay update requires the Xray HandlerService API") } - return false, nil + return hotAPIUnavailable, nil } // A dedicated client: s.xrayAPI may be in use by traffic polling on other // service instances and is reset around restarts. hotAPI := xray.XrayAPI{} if err := hotAPI.Init(apiPort); err != nil { - logger.Debug("hot apply: failed to init xray api:", err) + *failure = hotApplyFailure{step: "api_init", err: err} if len(diff.TuicRelayChanges) > 0 { - return false, err + return hotAPIUnavailable, err } - return false, nil + return hotAPIUnavailable, nil } defer hotAPI.Close() @@ -1696,28 +1762,32 @@ func (s *XrayService) tryHotApply(process *xray.Process, newCfg *xray.Config) (a process.SetConfig(&intermediate) persistHotConfig(process) - return false, errors.Join(relayErr, errors.New("independent Xray changes could not be planned after TUIC reconciliation")) + err := errors.Join(relayErr, errors.New("independent Xray changes could not be planned after TUIC reconciliation")) + *failure = hotApplyFailure{step: "plan_hot_diff", err: err} + return hotFailed, err } - if !applyXrayHotDiff(&hotAPI, ordinary) { + *failure = applyXrayHotDiff(&hotAPI, ordinary) + if failure.step != "" { relayErr = errors.Join(relayErr, staged.rollback(&hotAPI)) intermediate.InboundConfigs = oldCfg.InboundConfigs process.SetConfig(&intermediate) persistHotConfig(process) if relayErr != nil { - return false, relayErr + return hotFailed, relayErr } - return false, nil + return hotFailed, nil } balancerOverrides.reapply(process, &hotAPI, effective) process.SetConfig(effective) persistHotConfig(process) if relayErr != nil { - return false, relayErr + *failure = hotApplyFailure{step: "reconcile_tuic", err: relayErr} + return hotFailed, relayErr } - return true, nil + return hotApplied, nil } -func applyXrayHotDiff(hotAPI *xray.XrayAPI, diff *xray.HotDiff) bool { +func applyXrayHotDiff(hotAPI *xray.XrayAPI, diff *xray.HotDiff) hotApplyFailure { // Removals first so changed handlers and port swaps never collide with // the additions that follow. for _, u := range diff.RemovedUsers { @@ -1733,47 +1803,40 @@ func applyXrayHotDiff(hotAPI *xray.XrayAPI, diff *xray.HotDiff) bool { } } if err != nil { - logger.Info("hot apply: remove user [", u.Email, "] from [", u.Tag, "] failed:", err) - return false + return hotApplyFailure{step: "remove_user", subject: "[" + u.Email + "] from [" + u.Tag + "]", err: err} } } for _, tag := range diff.RemovedInboundTags { if err := hotAPI.DelInbound(tag); err != nil && !xray.IsMissingHandlerErr(err) { - logger.Info("hot apply: remove inbound [", tag, "] failed:", err) - return false + return hotApplyFailure{step: "remove_inbound", subject: "[" + tag + "]", err: err} } } for _, tag := range diff.RemovedOutboundTags { if err := hotAPI.DelOutbound(tag); err != nil && !xray.IsMissingHandlerErr(err) { - logger.Info("hot apply: remove outbound [", tag, "] failed:", err) - return false + return hotApplyFailure{step: "remove_outbound", subject: "[" + tag + "]", err: err} } } for _, ob := range diff.AddedOutbounds { if err := addOutboundReconciling(hotAPI, ob); err != nil { - logger.Info("hot apply: add outbound failed:", err) - return false + return hotApplyFailure{step: "add_outbound", err: err} } } for _, ib := range diff.AddedInbounds { if err := addInboundReconciling(hotAPI, ib); err != nil { - logger.Info("hot apply: add inbound failed:", err) - return false + return hotApplyFailure{step: "add_inbound", err: err} } } for _, u := range diff.AddedUsers { if err := addUserReconciling(hotAPI, u); err != nil { - logger.Info("hot apply: add user [", u.Email, "] to [", u.Tag, "] failed:", err) - return false + return hotApplyFailure{step: "add_user", subject: "[" + u.Email + "] to [" + u.Tag + "]", err: err} } } if diff.RoutingConfig != nil { if err := hotAPI.ApplyRoutingConfig(diff.RoutingConfig); err != nil { - logger.Info("hot apply: apply routing config failed:", err) - return false + return hotApplyFailure{step: "apply_routing", err: err} } } - return true + return hotApplyFailure{} } // persistHotConfig refreshes config.json after a hot apply; a write failure is @@ -1837,20 +1900,46 @@ func addOutboundReconciling(api *xray.XrayAPI, outbound []byte) error { // StopXray stops the running Xray process. func (s *XrayService) StopXray() error { + return s.StopXrayFrom(XrayOriginManual) +} + +// StopXrayFrom records the outcome of a stop initiated by the panel. +func (s *XrayService) StopXrayFrom(origin XrayOrigin) error { lock.Lock() defer lock.Unlock() isManuallyStopped.Store(true) logger.Debug("Attempting to stop Xray...") process := currentXrayProcess() - if process != nil && process.IsRunning() { - return process.Stop() + if process == nil || !process.IsRunning() { + return ErrXrayNotRunning } - return ErrXrayNotRunning + start := time.Now() + err := process.Stop() + pid, exit := process.LifecycleState() + event := xray.LifecycleEvent{ + Event: "stopped", Origin: string(origin), Reason: "stop_requested", OldPID: pid, + Duration: time.Since(start), Exit: exit, HotApply: "not_attempted", + } + if err != nil { + event.Event = "stop_failed" + if process.IsRunning() { + event.NewPID = pid + } + } + event.Log(err != nil) + return err } // SetToNeedRestart marks that Xray needs to be restarted. func (s *XrayService) SetToNeedRestart() { - isNeedXrayRestart.Store(true) + s.SetToNeedRestartFrom(XrayOriginConfigChange) +} + +// SetToNeedRestartFrom preserves the first trigger across coalesced requests. +func (s *XrayService) SetToNeedRestartFrom(origin XrayOrigin) { + if pendingXrayRestart.CompareAndSwap(nil, new(origin)) { + logger.Debug("xray_lifecycle_request origin=pending_restart trigger=" + string(origin)) + } } // SetToNeedReconcile schedules config reconciliation without forcing an unchanged core to restart. @@ -1879,21 +1968,26 @@ func (s *XrayService) GetXrayAPIPort() int { // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false. func (s *XrayService) IsNeedRestartAndSetFalse() bool { - return isNeedXrayRestart.CompareAndSwap(true, false) + return pendingXrayRestart.Swap(nil) != nil } // ApplyPendingRestart re-arms the original flags when applying fails, so the next tick retries; a // reconcile retry never becomes a restart, which would disconnect unrelated clients. func (s *XrayService) ApplyPendingRestart() { reconcile := isNeedXrayReconcile.Swap(false) - restart := s.IsNeedRestartAndSetFalse() - if !restart && !reconcile { + pending := pendingXrayRestart.Swap(nil) + if pending == nil && !reconcile { return } - if err := s.RestartXray(false); err != nil { + origin := XrayOriginConfigChange + var trigger XrayOrigin + if pending != nil { + origin, trigger = XrayOriginPendingRestart, *pending + } + if err := s.restartXrayFrom(false, origin, trigger); err != nil { logger.Error("reconcile xray failed:", err) - if restart { - s.SetToNeedRestart() + if pending != nil { + pendingXrayRestart.CompareAndSwap(nil, pending) } if reconcile { s.SetToNeedReconcile() diff --git a/internal/web/service/xray_hot_apply_persist_test.go b/internal/web/service/xray_hot_apply_persist_test.go index 1df2e9edd..2f6ddf8a8 100644 --- a/internal/web/service/xray_hot_apply_persist_test.go +++ b/internal/web/service/xray_hot_apply_persist_test.go @@ -46,3 +46,8 @@ func TestTuicChangeWithoutAPIDoesNotFallBackToCoreRestart(t *testing.T) { t.Fatal("direct reconciliation failure did not schedule a retry") } } + +func (s *XrayService) tryHotApply(process *xray.Process, cfg *xray.Config) (bool, error) { + outcome, err := s.applyHotConfig(process, cfg, new(hotApplyFailure)) + return outcome == hotApplied, err +} diff --git a/internal/web/service/xray_lifecycle_reason.go b/internal/web/service/xray_lifecycle_reason.go new file mode 100644 index 000000000..52173cf7f --- /dev/null +++ b/internal/web/service/xray_lifecycle_reason.go @@ -0,0 +1,55 @@ +package service + +import ( + "fmt" + + "google.golang.org/grpc/status" +) + +// XrayOrigin identifies the panel path that initiated a lifecycle operation. +type XrayOrigin string + +const ( + XrayOriginManual XrayOrigin = "manual" + XrayOriginConfigChange XrayOrigin = "config_change" + XrayOriginPendingRestart XrayOrigin = "pending_restart" + XrayOriginPanelStartup XrayOrigin = "panel_startup" + XrayOriginPanelShutdown XrayOrigin = "panel_shutdown" + XrayOriginWatchdog XrayOrigin = "watchdog" + XrayOriginClientDepletion XrayOrigin = "client_depletion" + XrayOriginTrafficAccounting XrayOrigin = "traffic_accounting" + XrayOriginNodeTrafficSync XrayOrigin = "node_traffic_sync" + XrayOriginTunnelHealth XrayOrigin = "tunnel_health" + XrayOriginSignal XrayOrigin = "signal" + XrayOriginBinaryUpdate XrayOrigin = "binary_update" + XrayOriginDatabaseRestore XrayOrigin = "database_restore" + XrayOriginGeodataUpdate XrayOrigin = "geodata_update" +) + +type hotApplyOutcome string + +const ( + hotApplied hotApplyOutcome = "applied" + hotUnsupported hotApplyOutcome = "unsupported_config" + hotClientsRemoved hotApplyOutcome = "clients_removed" + hotAPIUnavailable hotApplyOutcome = "api_unavailable" + hotFailed hotApplyOutcome = "failed" +) + +type hotApplyFailure struct { + step string + subject string + err error +} + +// code keeps the lifecycle entry to fixed fields; cause carries the core's own words. +func (f hotApplyFailure) code() string { + return status.Code(f.err).String() +} + +func (f hotApplyFailure) cause() string { + if f.subject == "" { + return fmt.Sprintf("hot apply: %s failed: %v", f.step, f.err) + } + return fmt.Sprintf("hot apply: %s %s failed: %v", f.step, f.subject, f.err) +} diff --git a/internal/web/service/xray_lifecycle_telemetry_test.go b/internal/web/service/xray_lifecycle_telemetry_test.go new file mode 100644 index 000000000..7a17be61d --- /dev/null +++ b/internal/web/service/xray_lifecycle_telemetry_test.go @@ -0,0 +1,260 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "net" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + + routercommand "github.com/xtls/xray-core/app/router/command" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/mhsanaei/3x-ui/v3/internal/logger" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestXrayLifecycleReportsActualReplacement(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the fake core is a shell script") + } + setupSettingTestDB(t) + t.Setenv("XUI_BIN_FOLDER", t.TempDir()) + t.Setenv("XUI_LOG_FOLDER", t.TempDir()) + binary := xray.GetBinaryPath() + if err := os.WriteFile(binary, []byte(fakeXrayCore("26.10.21", true)), 0o755); err != nil { + t.Fatal(err) + } + first := startFakeCore(t) + stopped := isManuallyStopped.Swap(false) + pending := pendingXrayRestart.Swap(nil) + t.Cleanup(func() { + isManuallyStopped.Store(stopped) + pendingXrayRestart.Store(pending) + }) + + svc := new(XrayService) + reports := func() []string { + var entries []string + for _, line := range logger.GetLogs(10240, "INFO") { + if _, report, found := strings.Cut(line, "xray_lifecycle "); found { + entries = append(entries, report) + } + } + return entries + } + check := func(before int, want ...string) (old, next int) { + t.Helper() + entries := reports() + if len(entries) != before+1 { + t.Fatalf("lifecycle entries added = %d, want 1 after %q", len(entries)-before, want) + } + report := entries[0] + for _, field := range want { + if !strings.Contains(report, field) { + t.Errorf("lifecycle report lacks %q: %s", field, report) + } + } + for _, field := range strings.Fields(report) { + key, value, _ := strings.Cut(field, "=") + switch key { + case "old_pid": + old, _ = strconv.Atoi(value) + case "new_pid": + next, _ = strconv.Atoi(value) + } + } + return old, next + } + + before := len(reports()) + if err := svc.RestartXray(false); err != nil { + t.Fatal(err) + } + if currentXrayProcess() != first || len(reports()) != before { + t.Fatal("unchanged config produced a lifecycle replacement") + } + + if err := svc.RestartXray(true); err != nil { + t.Fatal(err) + } + old, next := check(before, "event=restarted", "origin=manual", "reason=forced", "force=true", "hot_apply=not_attempted", "duration_ms=") + if old <= 0 || next <= 0 || next == old || first.IsRunning() { + t.Fatalf("force restart did not replace the logged child: %d -> %d", old, next) + } + + current := currentXrayProcess() + previous := *current.GetConfig() + previous.LogConfig = append([]byte(" "), previous.LogConfig...) + current.SetConfig(&previous) + if err := svc.RestartXray(false); err != nil { + t.Fatal(err) + } + old, pid := check(before+1, "event=hot_applied", "origin=config_change", "hot_apply=applied", "force=false") + if old != next || pid != next || currentXrayProcess() != current { + t.Fatal("hot apply did not retain the running PID") + } + + previous = *current.GetConfig() + previous.DNSConfig = []byte(`{"servers":["synthetic-config-secret"]}`) + current.SetConfig(&previous) + svc.SetToNeedRestartFrom(XrayOriginTrafficAccounting) + svc.SetToNeedRestartFrom(XrayOriginNodeTrafficSync) + svc.ApplyPendingRestart() + svc.ApplyPendingRestart() + old, last := check(before+2, "event=restarted", "origin=pending_restart", "trigger=traffic_accounting", "reason=unsupported_config", "hot_apply=unsupported_config", "force=false") + if old != next || last <= 0 || last == next { + t.Fatalf("fallback did not replace the logged child: %d -> %d", old, last) + } + if strings.Contains(reports()[0], "synthetic-config-secret") { + t.Fatal("lifecycle report disclosed config data") + } + + templateText, err := svc.settingService.GetXrayConfigTemplate() + if err != nil { + t.Fatal(err) + } + var template xray.Config + if err := json.Unmarshal([]byte(templateText), &template); err != nil { + t.Fatal(err) + } + template.InboundConfigs = append(template.InboundConfigs, xray.InboundConfig{ + Tag: "lifecycle-client", Protocol: "vless", Listen: []byte(`"127.0.0.1"`), Port: freeLoopbackPort(t), + Settings: []byte(`{"clients":[],"decryption":"none"}`), + }) + if err := svc.settingService.saveSetting("xrayTemplateConfig", string(mustJSON(t, template))); err != nil { + t.Fatal(err) + } + if err := svc.settingService.SetRestartXrayOnClientDisable(true); err != nil { + t.Fatal(err) + } + prior, err := svc.GetXrayConfig() + if err != nil { + t.Fatal(err) + } + for i := range prior.InboundConfigs { + if prior.InboundConfigs[i].Tag == "lifecycle-client" { + prior.InboundConfigs[i].Settings = []byte(`{"clients":[{"email":"fixture-depleted@example.test","id":"00000000-0000-4000-8000-000000000001"}],"decryption":"none"}`) + } + } + currentXrayProcess().SetConfig(prior) + if err := svc.RestartXrayFrom(false, XrayOriginClientDepletion); err != nil { + t.Fatal(err) + } + old, next = check(before+3, "event=restarted", "origin=client_depletion", "reason=clients_removed", "hot_apply=clients_removed", "force=false") + if old != last || next <= 0 || next == last || strings.Contains(reports()[0], "fixture-depleted") { + t.Fatalf("depletion did not produce a redacted replacement: %s", reports()[0]) + } + + if err := svc.StopXray(); err != nil { + t.Fatal(err) + } + old, pid = check(before+4, "event=stopped", "origin=manual", "new_pid=0", "signal=terminated") + if old != next || pid != 0 || currentXrayProcess().IsRunning() { + t.Fatal("the logged stop did not retire the current core") + } + + if err := os.Remove(binary); err != nil { + t.Fatal(err) + } + if err := svc.RestartXray(true); err == nil || !strings.Contains(err.Error(), filepath.Base(binary)) { + t.Fatalf("restart without executable = %v, want launch error", err) + } + pidBeforeFailure := old + old, next = check(before+5, "event=start_failed", "origin=manual", "reason=forced", "new_pid=0") + if old <= 0 || old != pidBeforeFailure || next != 0 || currentXrayProcess().IsRunning() { + t.Fatalf("startup failure reported an incorrect PID transition: %d -> %d", old, next) + } +} + +func TestXrayLifecycleIdentifiesRejectedHotApply(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the fake core is a shell script") + } + setupSettingTestDB(t) + t.Setenv("XUI_BIN_FOLDER", t.TempDir()) + t.Setenv("XUI_LOG_FOLDER", t.TempDir()) + if err := os.WriteFile(xray.GetBinaryPath(), []byte(fakeXrayCore("26.10.21", true)), 0o755); err != nil { + t.Fatal(err) + } + svc := new(XrayService) + template, err := svc.settingService.GetXrayConfigTemplate() + if err != nil { + t.Fatal(err) + } + var cfg xray.Config + if err := json.Unmarshal([]byte(template), &cfg); err != nil { + t.Fatal(err) + } + cfg.RouterConfig = []byte("{\"domainStrategy\":\"AsIs\",\"rules\":[]}") + // This test serves the core's gRPC API itself; the template's port may belong to a real core here. + for i := range cfg.InboundConfigs { + if cfg.InboundConfigs[i].Tag == "api" { + cfg.InboundConfigs[i].Port = freeLoopbackPort(t) + } + } + if err := svc.settingService.saveSetting("xrayTemplateConfig", string(mustJSON(t, cfg))); err != nil { + t.Fatal(err) + } + first := startFakeCore(t) + stopped := isManuallyStopped.Swap(false) + t.Cleanup(func() { isManuallyStopped.Store(stopped) }) + + listener, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", first.GetAPIPort())) + if err != nil { + t.Fatal(err) + } + const privateDetail = "private-account@example.test" + core := grpc.NewServer(grpc.UnaryInterceptor(func(context.Context, any, *grpc.UnaryServerInfo, grpc.UnaryHandler) (any, error) { + return nil, status.Error(codes.InvalidArgument, privateDetail) + })) + routercommand.RegisterRoutingServiceServer(core, routercommand.UnimplementedRoutingServiceServer{}) + go func() { _ = core.Serve(listener) }() + t.Cleanup(core.Stop) + + previous := *first.GetConfig() + var routing map[string]json.RawMessage + if err := json.Unmarshal(previous.RouterConfig, &routing); err != nil { + t.Fatal(err) + } + routing["rules"] = json.RawMessage("[{\"type\":\"field\",\"outboundTag\":\"direct\",\"domain\":[\"example.test\"]}]") + previous.RouterConfig = mustJSON(t, routing) + first.SetConfig(&previous) + if err := svc.RestartXray(false); err != nil { + t.Fatal(err) + } + if first.IsRunning() || first == currentXrayProcess() { + t.Fatal("rejected hot apply did not fall back to a core restart") + } + lifecycleEntries, causes := 0, 0 + for _, line := range logger.GetLogs(10240, "INFO") { + if strings.Contains(line, "xray_lifecycle event=restarted") && strings.Contains(line, "reason=hot_apply_failed") { + lifecycleEntries++ + for _, field := range []string{"hot_apply_step=apply_routing", "hot_apply_code=InvalidArgument"} { + if !strings.Contains(line, field) { + t.Errorf("lifecycle entry lacks %q: %s", field, line) + } + } + if strings.Contains(line, privateDetail) { + t.Fatalf("lifecycle entry exposed a private error: %s", line) + } + } + // The fixed-field entry cannot say what the core refused; the operator needs its words. + if strings.Contains(line, "hot apply: apply_routing failed:") && strings.Contains(line, privateDetail) { + causes++ + } + } + if lifecycleEntries != 1 { + t.Fatalf("lifecycle entries for the failed hot apply = %d, want 1", lifecycleEntries) + } + if causes != 1 { + t.Fatalf("log lines carrying the core's refusal = %d, want 1", causes) + } +} diff --git a/internal/web/service/xray_restart_test.go b/internal/web/service/xray_restart_test.go index 095213efc..348b636e9 100644 --- a/internal/web/service/xray_restart_test.go +++ b/internal/web/service/xray_restart_test.go @@ -24,17 +24,20 @@ func TestApplyPendingRestartReArmsFlagOnFailure(t *testing.T) { if err := (&SettingService{}).saveSetting("xrayTemplateConfig", "{ not valid json"); err != nil { t.Fatalf("seed template: %v", err) } + stopped := isManuallyStopped.Swap(false) + pending := pendingXrayRestart.Swap(nil) + reconcile := isNeedXrayReconcile.Swap(false) t.Cleanup(func() { - isManuallyStopped.Store(false) - isNeedXrayRestart.Store(false) + isManuallyStopped.Store(stopped) + pendingXrayRestart.Store(pending) + isNeedXrayReconcile.Store(reconcile) }) - isManuallyStopped.Store(false) svc := &XrayService{} - svc.SetToNeedRestart() + svc.SetToNeedRestartFrom(XrayOriginTrafficAccounting) svc.ApplyPendingRestart() - if !isNeedXrayRestart.Load() { + if trigger := pendingXrayRestart.Load(); trigger == nil || *trigger != XrayOriginTrafficAccounting { t.Fatal("a failed restart must re-arm the need-restart flag so the pending config change is retried") } } diff --git a/internal/web/web.go b/internal/web/web.go index 7afdb0a1b..65a49d319 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -327,7 +327,7 @@ const ( // jobs) which the panel relies on for periodic maintenance and monitoring. func (s *Server) startTask(restartXray bool, loc *time.Location) { if restartXray { - err := s.xrayService.RestartXray(true) + err := s.xrayService.RestartXrayFrom(true, service.XrayOriginPanelStartup) if err != nil { logger.Warning("start xray failed:", err) } @@ -821,7 +821,7 @@ func (s *Server) stop(stopXray bool, stopTgBot bool) error { amneziawgnet.GetOutboundManager().StopAll() } if stopXray { - if err := s.xrayService.StopXray(); err != nil && !errors.Is(err, service.ErrXrayNotRunning) { + if err := s.xrayService.StopXrayFrom(service.XrayOriginPanelShutdown); err != nil && !errors.Is(err, service.ErrXrayNotRunning) { err2 = common.Combine(err2, err) } } @@ -869,8 +869,8 @@ func (s *Server) GetWSHub() any { return s.wsHub } -func (s *Server) RestartXray() error { - return s.xrayService.RestartXray(true) +func (s *Server) RestartXray(origin service.XrayOrigin) error { + return s.xrayService.RestartXrayFrom(true, origin) } // scheduleSettingJob schedules j on an admin-typed spec, running it on fallback diff --git a/internal/xray/lifecycle.go b/internal/xray/lifecycle.go new file mode 100644 index 000000000..31016306c --- /dev/null +++ b/internal/xray/lifecycle.go @@ -0,0 +1,64 @@ +package xray + +import ( + "fmt" + "os" + "strings" + "syscall" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/logger" +) + +// LifecycleEvent contains only operational metadata from a managed core. +type LifecycleEvent struct { + Event string + Origin string + Reason string + Force bool + OldPID int + NewPID int + Duration time.Duration + HotApply string + HotApplyStep string + HotApplyCode string + Trigger string + StopResult string + Exit *os.ProcessState +} + +func (e LifecycleEvent) Log(warn bool) { + line := fmt.Sprintf("xray_lifecycle event=%s origin=%s reason=%s force=%t old_pid=%d new_pid=%d duration_ms=%d hot_apply=%s", + e.Event, e.Origin, e.Reason, e.Force, e.OldPID, e.NewPID, e.Duration.Milliseconds(), e.HotApply) + if e.Trigger != "" { + line += " trigger=" + e.Trigger + } + if e.HotApplyStep != "" { + line += " hot_apply_step=" + e.HotApplyStep + " hot_apply_code=" + e.HotApplyCode + } + if e.StopResult != "" { + line += " stop_result=" + e.StopResult + } + if e.Exit != nil { + if status, ok := e.Exit.Sys().(syscall.WaitStatus); ok && status.Signaled() { + line += " signal=" + strings.ReplaceAll(status.Signal().String(), " ", "_") + } else if code := e.Exit.ExitCode(); code >= 0 { + line += fmt.Sprintf(" exit_code=%d", code) + } + } + if warn { + logger.Warning(line) + } else { + logger.Info(line) + } +} + +// LifecycleState returns the last PID and any exit state recorded by Wait. +func (p *Process) LifecycleState() (int, *os.ProcessState) { + if p == nil { + return 0, nil + } + p.mu.RLock() + defer p.mu.RUnlock() + return p.pid, p.processState +} diff --git a/internal/xray/process.go b/internal/xray/process.go index 6fe89d505..f29c6ac0b 100644 --- a/internal/xray/process.go +++ b/internal/xray/process.go @@ -112,6 +112,7 @@ type Process struct { // NewProcess creates a new Xray process and sets up cleanup on garbage collection. func NewProcess(xrayConfig *Config) *Process { p := &Process{newProcess(xrayConfig)} + p.managed = true runtime.SetFinalizer(p, stopProcess) return p } @@ -133,9 +134,12 @@ type process struct { // GetAPIPort/Stop from other goroutines (status endpoint, check-xray-running // and traffic jobs). Snapshot under the lock, then do any blocking syscall // (Wait/Signal/Kill) on the local copy without holding it. - mu sync.RWMutex - cmd *exec.Cmd - done chan struct{} + mu sync.RWMutex + cmd *exec.Cmd + done chan struct{} + pid int + processState *os.ProcessState + managed bool version string apiPort int @@ -813,23 +817,20 @@ func writeFileAtomic(path string, data []byte, perm os.FileMode) (err error) { var renameFile = os.Rename func (p *process) startCommand(cmd *exec.Cmd) error { - p.mu.Lock() - p.cmd = cmd - p.done = make(chan struct{}) - p.exitErr = nil - done := p.done - p.mu.Unlock() - p.intentionalStop.Store(false) - if err := cmd.Start(); err != nil { - close(done) - p.mu.Lock() - p.cmd = nil - p.mu.Unlock() return err } attachChildLifetime(cmd) + done := make(chan struct{}) + p.mu.Lock() + p.cmd = cmd + p.done = done + p.pid = cmd.Process.Pid + p.processState = nil + p.exitErr = nil + p.intentionalStop.Store(false) + p.mu.Unlock() go p.waitForCommand(cmd, done) return nil @@ -845,8 +846,21 @@ func (p *process) waitForCommand(cmd *exec.Cmd, done chan struct{}) { defer close(done) err := cmd.Wait() + p.mu.Lock() + p.processState = cmd.ProcessState + p.mu.Unlock() p.logWriter.Flush() - if err == nil || p.intentionalStop.Load() { + if p.intentionalStop.Load() { + return + } + if p.managed { + LifecycleEvent{ + Event: "unexpected_exit", Origin: "child", Reason: "process_exit", + OldPID: cmd.Process.Pid, Duration: time.Since(p.startTime), + HotApply: "not_attempted", Exit: cmd.ProcessState, + }.Log(true) + } + if err == nil { return } diff --git a/internal/xray/process_test.go b/internal/xray/process_test.go index 066f9fa1b..adc131b7d 100644 --- a/internal/xray/process_test.go +++ b/internal/xray/process_test.go @@ -8,6 +8,8 @@ import ( "os/exec" "os/signal" "path/filepath" + "strconv" + "strings" "syscall" "testing" "time" @@ -217,3 +219,45 @@ func markProcessHelperReady(t *testing.T) { t.Fatalf("write helper ready file: %v", err) } } + +func TestManagedCoreLogsUnexpectedExitWithPIDAndStatus(t *testing.T) { + initProcessTestLogger(t) + for _, tc := range []struct { + name, command, field string + args []string + kill bool + }{ + {name: "external signal", command: "sleep", args: []string{"60"}, kill: true, field: "signal=killed"}, + {name: "clean child exit", command: "true", field: "exit_code=0"}, + } { + t.Run(tc.name, func(t *testing.T) { + core := NewProcess(nil) + cmd := exec.Command(tc.command, tc.args...) + if err := core.startCommand(cmd); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = core.Stop() }) + if tc.kill { + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + } + if err := core.waitForExit(3 * time.Second); err != nil { + t.Fatal(err) + } + matches := 0 + for _, line := range xuilogger.GetLogs(32, "WARNING") { + if strings.Contains(line, "xray_lifecycle event=unexpected_exit origin=child reason=process_exit") && + strings.Contains(line, " old_pid="+strconv.Itoa(cmd.Process.Pid)+" new_pid=0 ") { + matches++ + if !strings.Contains(line, tc.field) { + t.Errorf("unexpected exit lacked %q: %s", tc.field, line) + } + } + } + if matches != 1 { + t.Fatalf("unexpected exit entries for PID %d = %d, want 1", cmd.Process.Pid, matches) + } + }) + } +} diff --git a/main.go b/main.go index 75c7692d0..70bbfd739 100644 --- a/main.go +++ b/main.go @@ -161,7 +161,7 @@ func runWebServer() { monitor, err := tunnelmonitor.New(monitorCfg, func(_ context.Context) error { logger.Warning("Tunnel health monitor threshold reached, restarting xray-core") - return server.RestartXray() + return server.RestartXray(service.XrayOriginTunnelHealth) }) if err != nil { logger.Warning("Tunnel health monitor disabled: ", err) @@ -203,7 +203,7 @@ func runWebServer() { log.Println("Sub server restarted successfully.") case sys.SIGUSR1: logger.Info("Received USR1 signal, restarting xray-core...") - err := server.RestartXray() + err := server.RestartXray(service.XrayOriginSignal) if err != nil { logger.Error("Failed to restart xray-core:", err) }