perf: prevent cron job overlap, auto-set GOMEMLIMIT, fix tgbot userStates race

cron: SkipIfStillRunning stops a slow 5s/10s job from overlapping itself and racing the shared xrayAPI (grpc conn leak) and the StatsLastValues map (fatal concurrent map write). memlimit: auto-detect a Go soft memory limit from XUI_MEMORY_LIMIT, the cgroup limit, or system RAM (about 90 percent); opt-in pprof via XUI_PPROF. tgbot: userStates now goes through a mutex-guarded store with TTL pruning (was raced by worker-pool and delayed-delete goroutines). check_client_ip: prefilter inbounds by settings LIKE limitIp instead of loading and JSON-parsing all of them every scan. minor: prune StatsLastValues, RateLimiter.lastSent, reportedRemoteTagConflict. docker-compose: document the memory knobs.
This commit is contained in:
MHSanaei committed 2026-06-22 02:48:58 +02:00 Unverified
1 parent 679d2e1cca
commit 7d23a2c15b
11 files changed
+234 -27

No files matched your search

+8
View File
@@ -5,6 +5,9 @@ services:
dockerfile: ./Dockerfile
container_name: 3xui_app
# hostname: yourhostname <- optional
# Optional hard memory cap. When set, the panel auto-derives its Go soft
# limit (GOMEMLIMIT, ~90%) from this so it GCs before the OOM killer fires.
# mem_limit: 512m
# The bundled Fail2ban (XUI_ENABLE_FAIL2BAN below) enforces the IP limit
# with iptables, which needs NET_ADMIN. Without these caps a ban is logged
# and shown in fail2ban status but never actually applied. NET_RAW covers
@@ -18,6 +21,11 @@ services:
environment:
XRAY_VMESS_AEAD_FORCED: "false"
XUI_ENABLE_FAIL2BAN: "true"
# Go memory soft limit. If neither is set, the panel auto-detects the
# cgroup/host limit and targets ~90%. Pin it explicitly with one of:
# XUI_MEMORY_LIMIT: "400" # in MiB
# GOMEMLIMIT: "400MiB" # Go syntax, takes precedence
# XUI_PPROF: "true" # expose pprof on 127.0.0.1:6060 for profiling
# XUI_INIT_WEB_BASE_PATH: "/"
# XUI_PORT: "8080"
# To use PostgreSQL instead of the default SQLite, run:
+24 -5
View File
@@ -7,9 +7,10 @@ import (
// RateLimiter prevents notification spam from flapping events.
type RateLimiter struct {
mu sync.Mutex
lastSent map[string]time.Time
cooldown time.Duration
mu sync.Mutex
lastSent map[string]time.Time
cooldown time.Duration
lastPrune time.Time
}
// NewRateLimiter creates a rate limiter with the given cooldown period.
@@ -23,11 +24,29 @@ func NewRateLimiter(cooldown time.Duration) *RateLimiter {
// Allow returns true if the event should be sent (cooldown has elapsed).
func (r *RateLimiter) Allow(eventType EventType, source string) bool {
key := string(eventType) + ":" + source
now := time.Now()
r.mu.Lock()
defer r.mu.Unlock()
if time.Since(r.lastSent[key]) < r.cooldown {
r.pruneLocked(now)
if now.Sub(r.lastSent[key]) < r.cooldown {
return false
}
r.lastSent[key] = time.Now()
r.lastSent[key] = now
return true
}
// pruneLocked drops keys whose cooldown has elapsed. Such an entry no longer
// affects Allow's result, so removing it is safe and keeps the map from
// retaining one entry per (eventType, source) ever seen. Throttled to once per
// cooldown so a busy bus doesn't sweep the whole map on every event.
func (r *RateLimiter) pruneLocked(now time.Time) {
if now.Sub(r.lastPrune) < r.cooldown {
return
}
r.lastPrune = now
for k, v := range r.lastSent {
if now.Sub(v) >= r.cooldown {
delete(r.lastSent, k)
}
}
}
+78
View File
@@ -0,0 +1,78 @@
package sys
import (
"os"
"runtime/debug"
"strconv"
"strings"
"github.com/shirou/gopsutil/v4/mem"
)
// memLimitHeadroomPercent is the share of detected memory used for the soft
// limit, leaving room for non-heap (stacks, mmap, the xray child) before the OS
// OOM-kills the process.
const memLimitHeadroomPercent = 90
// ApplyMemoryLimit sets a Go soft memory limit (the runtime's GOMEMLIMIT) when
// one is not already configured, so a long-running panel in a memory-capped
// container or VPS triggers GC as it approaches the cap instead of growing RSS
// until the OS OOM-kills it. Precedence: an explicit GOMEMLIMIT env is left to
// the runtime; otherwise XUI_MEMORY_LIMIT (in MiB) wins; otherwise the limit is
// derived from the cgroup memory limit, falling back to total system RAM.
// Returns the limit applied in bytes (0 when none) and a short source label.
func ApplyMemoryLimit() (int64, string) {
if strings.TrimSpace(os.Getenv("GOMEMLIMIT")) != "" {
return 0, "GOMEMLIMIT env (handled by the Go runtime)"
}
if v := strings.TrimSpace(os.Getenv("XUI_MEMORY_LIMIT")); v != "" {
if mb, err := strconv.ParseInt(v, 10, 64); err == nil && mb > 0 {
limit := mb << 20
debug.SetMemoryLimit(limit)
return limit, "XUI_MEMORY_LIMIT=" + v + "MiB"
}
}
total, source := detectAvailableMemory()
if total <= 0 {
return 0, "undetectable; left at Go default"
}
limit := total / 100 * memLimitHeadroomPercent
debug.SetMemoryLimit(limit)
return limit, source
}
func detectAvailableMemory() (int64, string) {
if v, ok := cgroupMemoryLimit(); ok {
return v, "cgroup limit"
}
if vm, err := mem.VirtualMemory(); err == nil && vm.Total > 0 {
return int64(vm.Total), "system RAM"
}
return 0, ""
}
// cgroupMemoryLimit reads the container memory limit from cgroup v2 then v1.
// A "max" value or the v1 unlimited sentinel (~8 EiB) means no limit at this
// level, so it reports not-found and the caller falls back to system RAM. The
// files are absent off Linux, which also yields not-found.
func cgroupMemoryLimit() (int64, bool) {
const unlimited = int64(1) << 62
if b, err := os.ReadFile("/sys/fs/cgroup/memory.max"); err == nil {
if s := strings.TrimSpace(string(b)); s != "" && s != "max" {
if v, err := strconv.ParseInt(s, 10, 64); err == nil && v > 0 && v < unlimited {
return v, true
}
}
}
if b, err := os.ReadFile("/sys/fs/cgroup/memory/memory.limit_in_bytes"); err == nil {
if v, err := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64); err == nil && v > 0 && v < unlimited {
return v, true
}
}
return 0, false
}
Loaded 3 of 11 files, more files were not shown because too many files have changed in this diff. Show more