package main import ( "context" "errors" "fmt" "log" "os" "runtime" "strings" "sync/atomic" "syscall" "time" "github.com/mhsanaei/3x-ui/v3/internal/util/sys" ) // Each listener can take up to 30 seconds to drain ordinary HTTP traffic. const panelRestartTimeout = 75 * time.Second type panelRestartPhase struct { name string run func(context.Context) error } type panelRestartSignals struct { shutdown bool restartXray bool } func runPanelRestart(signals <-chan os.Signal, budget time.Duration, phases ...panelRestartPhase) (panelRestartSignals, error) { ctx, cancel := context.WithTimeout(context.Background(), budget) defer cancel() var phase atomic.Pointer[panelRestartPhase] result := make(chan error, 1) go func() { for i := range phases { if err := ctx.Err(); err != nil { result <- err return } step := &phases[i] phase.Store(step) started := time.Now() log.Printf("panel restart phase=%s state=started", step.name) err := step.run(ctx) log.Printf("panel restart phase=%s state=finished duration=%s error=%v", step.name, time.Since(started), err) if err != nil { result <- fmt.Errorf("%s: %w", step.name, err) return } } result <- ctx.Err() }() var pending panelRestartSignals phaseName := func() string { if current := phase.Load(); current != nil { return current.name } return "dispatch" } for { select { case err := <-result: if errors.Is(ctx.Err(), context.DeadlineExceeded) { return pending, fmt.Errorf("%s exceeded the %s panel restart deadline: %w", phaseName(), budget, ctx.Err()) } return pending, err case <-ctx.Done(): return pending, fmt.Errorf("%s exceeded the %s panel restart deadline: %w", phaseName(), budget, ctx.Err()) case sig, ok := <-signals: if !ok { signals = nil continue } switch sig { case syscall.SIGHUP: continue case sys.SIGUSR1: pending.restartXray = true default: // Let the current restart finish within its existing deadline, // then let the signal loop stop the new generation gracefully. pending.shutdown = true } } } } // Log function names only. Argument values and goroutine labels can contain panel data. func logPanelRestartStacks() { records := make([]runtime.StackRecord, 2048) n, ok := runtime.GoroutineProfile(records) if !ok { log.Printf("panel restart goroutine profile omitted: %d goroutines exceed diagnostic capacity", n) return } log.Printf("panel restart goroutine profile: %d goroutines, showing up to 24 stacks", n) for _, record := range records[:min(n, 24)] { frames := runtime.CallersFrames(record.Stack()) names := make([]string, 0, 12) for range cap(names) { frame, more := frames.Next() if frame.Function != "" { names = append(names, frame.Function) } if !more { break } } log.Print(strings.Join(names, " <- ")) } }