Files
mirror-3x-ui/internal/web/service/xray_lifecycle_telemetry_test.go
T
Sanaei d4ce11954d fix(clients): end a removed client's sessions without waiting on a config diff
With restart-on-client-disable on, a client the API removes from a running
inbound must be followed by a core restart: the removal drops the credential
only. The apply layer asked for that restart by setting the generic
need-restart flag, and the tick then restarted only when the generated config
differed from the running-config snapshot. A client added over the API is not
in that snapshot, so disabling or deleting it before any reconcile diffed as
"no change" and its live session kept passing traffic.

The removal now queues the session-drop restart itself, through the request
the depletion path already uses, so the tick replaces the core whatever the
snapshot holds. Detaching a client and bulk delete removed clients the same
way without asking for anything; they queue it too. WireGuard is left out: its
session ends with the peer.

The pending flag and the protocol predicate lose "depletion" from their names
now that manual removals share them.

Run on a panel with the real core: a client added after the core started,
holding a stream open, was cut and the core replaced within one tick of its
disable; before the change the stream ran on and the core kept its PID.
2026-11-29 21:48:57 +03:30

265 lines
9.3 KiB
Go

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)
depletion := pendingXraySessionDrop.Swap(false)
t.Cleanup(func() {
isManuallyStopped.Store(stopped)
pendingXrayRestart.Store(pending)
pendingXraySessionDrop.Store(depletion)
})
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)
useFreeXrayAPIPort(t)
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\":[]}")
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)
// The log buffer is shared by the package: only the lines this restart adds are judged.
rejections := func() (entries, causes []string) {
for _, line := range logger.GetLogs(10240, "INFO") {
if strings.Contains(line, "xray_lifecycle event=restarted") && strings.Contains(line, "reason=hot_apply_failed") {
entries = append(entries, line)
}
if strings.Contains(line, "hot apply: apply_routing failed:") && strings.Contains(line, privateDetail) {
causes = append(causes, line)
}
}
return entries, causes
}
entriesBefore, causesBefore := rejections()
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")
}
entries, causes := rejections()
if len(entries) != len(entriesBefore)+1 {
t.Fatalf("lifecycle entries added by the failed hot apply = %d, want 1", len(entries)-len(entriesBefore))
}
// GetLogs returns the newest line first.
for _, field := range []string{"hot_apply_step=apply_routing", "hot_apply_code=InvalidArgument"} {
if !strings.Contains(entries[0], field) {
t.Errorf("lifecycle entry lacks %q: %s", field, entries[0])
}
}
if strings.Contains(entries[0], privateDetail) {
t.Fatalf("lifecycle entry exposed a private error: %s", entries[0])
}
// The fixed-field entry cannot say what the core refused; the operator needs its words.
if len(causes) != len(causesBefore)+1 {
t.Fatalf("log lines carrying the core's refusal = %d, want 1", len(causes)-len(causesBefore))
}
}