feat(sub): report why a subscription balancer emits nothing (#7209)

A subscription balancer whose inbounds were deleted, disabled, changed to a protocol with no JSON outbound, left without clients or closed by their hosts simply vanished from the JSON subscription, and nothing in the panel or the log said why.

GET /panel/api/sub-balancers now returns a problems[] array per balancer with stable codes: unknown_inbound, disabled_inbound, json_incapable_protocol, inbound_without_clients, hosts_excluded_from_json and no_members. Settings -> Sub Balancers shows a warning tag whose tooltip names each cause and the affected inbounds, and the log records a balancer's problems when they change instead of on every listing.

The advisories are read from the stored rows and never change what a subscription emits: a balancer with no usable member is still omitted. The list of JSON-incapable protocols is pinned to the renderer, the subscription allowlist and the form by tests.
This commit is contained in:
amirim
2026-11-28 09:23:14 +03:00
committed by GitHub
parent eb99820dd8
commit e071f220e9
30 changed files with 1419 additions and 13 deletions
+35
View File
@@ -477,6 +477,36 @@ func (s *SubJsonService) hiddenMemberConfig(subReq *SubService, inbound *model.I
return s.getConfig(subReq, inbound, client, host)
}
// omittedBalancerWarned remembers which balancers already warned, so a subscription
// fetched once per client device does not repeat the same line on every request.
var omittedBalancerWarned = struct {
sync.Mutex
seen map[int]bool
}{seen: map[int]bool{}}
func warnOmittedBalancer(balancer *model.SubBalancer) {
omittedBalancerWarned.Lock()
already := omittedBalancerWarned.seen[balancer.Id]
omittedBalancerWarned.seen[balancer.Id] = true
omittedBalancerWarned.Unlock()
if already {
return
}
logger.Warningf("SubJsonService: balancer %q (#%d) omitted, its inbounds are in this subscription but produced no member",
balancer.Remark, balancer.Id)
}
// selectsPresentBalancer is true when an inbound the balancer selects is among this
// subscriber's entries: the only case where an empty member list signals a fault.
func selectsPresentBalancer(inboundIds []int, sources []subConfigEntry) bool {
for _, entry := range sources {
if entry.kind == 0 && slices.Contains(inboundIds, entry.id) {
return true
}
}
return false
}
// appendBalancerEntries appends one entry per balancer that has at least one member outbound
// among the inbound entries; hidden inbounds' entries are members but never output themselves.
func (s *SubJsonService) appendBalancerEntries(entries, hidden []subConfigEntry, balancers []model.SubBalancer) []subConfigEntry {
@@ -500,6 +530,11 @@ func (s *SubJsonService) appendBalancerEntries(entries, hidden []subConfigEntry,
for i := range balancers {
config := s.buildBalancerConfig(&balancers[i], sources, entryProxies)
if config == nil {
// Balancers are global, sources are this subscriber's: an empty
// intersection is normal, only a present-but-memberless one warns.
if selectsPresentBalancer(balancers[i].InboundIds, sources) {
warnOmittedBalancer(&balancers[i])
}
continue
}
entries = append(entries, subConfigEntry{
+4 -1
View File
@@ -81,11 +81,14 @@ func (a *SubBalancerController) parseID(c *gin.Context) (int, error) {
}
func (a *SubBalancerController) list(c *gin.Context) {
balancers, err := a.SubBalancerService.List()
balancers, err := a.SubBalancerService.ListWithProblems()
if err != nil {
jsonMsg(c, I18nWeb(c, "pages.settings.subBalancers.toasts.list"), err)
return
}
for _, balancer := range balancers {
service.LogSubBalancerProblems(&balancer.SubBalancer, balancer.Problems)
}
jsonObj(c, balancers, nil)
}
@@ -0,0 +1,253 @@
package service
import (
"slices"
"strconv"
"strings"
"sync"
"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"
)
// SubBalancerProblem codes. They are part of the API contract (the panel UI
// maps them to i18n keys), so treat them as stable identifiers.
const (
// An import or a restored backup can bring back the id of a deleted inbound.
SubBalancerProblemUnknownInbound = "unknown_inbound"
SubBalancerProblemDisabledInbound = "disabled_inbound"
// The protocol renders share links and Clash proxies but has no JSON outbound.
SubBalancerProblemJSONIncapable = "json_incapable_protocol"
// No selected inbound can contribute, so the JSON subscription omits the balancer.
SubBalancerProblemNoMembers = "no_members"
// Enabled and renderable, but with no client it reaches no subscription.
SubBalancerProblemInboundWithoutClients = "inbound_without_clients"
// Every enabled host excludes the JSON format, so hostEndpoints closes the inbound.
SubBalancerProblemHostsExcluded = "hosts_excluded_from_json"
)
// SubBalancerProblem is one reason a balancer cannot emit what an operator expects.
// Advisories never change the emitted config, and per-client losses are out of scope.
type SubBalancerProblem struct {
Code string `json:"code" example:"unknown_inbound"`
InboundIds []int `json:"inboundIds,omitempty" example:"[7,9]"`
Detail string `json:"detail,omitempty" example:"amneziawg"`
}
// jsonIncapableProtocols mirrors the Protocol switch in internal/sub/json_service.go;
// sub_balancer_problems_parity_test.go fails when the two drift.
var jsonIncapableProtocols = map[string]struct{}{
"amneziawg": {},
"tuic": {},
"mtproto": {},
}
// SubBalancerWithProblems embeds the row by value so it marshals flat; Problems is
// always non-nil so the response shape is stable.
type SubBalancerWithProblems struct {
model.SubBalancer
Problems []SubBalancerProblem `json:"problems"`
}
// ListWithProblems returns every balancer with its advisories attached.
func (s *SubBalancerService) ListWithProblems() ([]*SubBalancerWithProblems, error) {
balancers, err := s.List()
if err != nil {
return nil, err
}
ids := make([]int, 0, len(balancers))
for _, b := range balancers {
ids = append(ids, b.InboundIds...)
}
byID, clientCounts, hostsClosed, err := loadBalancerMemberInbounds(ids)
if err != nil {
return nil, err
}
out := make([]*SubBalancerWithProblems, 0, len(balancers))
for _, b := range balancers {
problems := diagnoseSubBalancer(b, byID, clientCounts, hostsClosed)
out = append(out, &SubBalancerWithProblems{SubBalancer: *b, Problems: problems})
}
return out, nil
}
// loadBalancerMemberInbounds reads only the columns the diagnosis needs, plus
// grouped client and host counts that decide reachability per inbound.
func loadBalancerMemberInbounds(ids []int) (map[int]*model.Inbound, map[int]int, map[int]bool, error) {
byID := map[int]*model.Inbound{}
clients := map[int]int{}
hostsClosed := map[int]bool{}
unique := make([]int, 0, len(ids))
for _, id := range ids {
if !slices.Contains(unique, id) {
unique = append(unique, id)
}
}
if len(unique) == 0 {
return byID, clients, hostsClosed, nil
}
var inbounds []*model.Inbound
err := database.GetDB().Model(&model.Inbound{}).
Select("id", "protocol", "enable").
Where("id IN ?", unique).Find(&inbounds).Error
if err != nil {
return nil, nil, nil, err
}
for _, ib := range inbounds {
byID[ib.Id] = ib
}
var counts []struct {
InboundId int
Total int
}
err = database.GetDB().Model(&model.ClientInbound{}).
Select("inbound_id, COUNT(*) AS total").
Where("inbound_id IN ?", unique).
Group("inbound_id").Scan(&counts).Error
if err != nil {
return nil, nil, nil, err
}
for _, c := range counts {
clients[c.InboundId] = c.Total
}
// An inbound whose enabled hosts all exclude JSON is closed by hostEndpoints,
// so its clients never render. The column is a JSON array, hence the quoted match.
var hostRows []struct {
InboundId int
Enabled int
ExcludingJSONCount int
}
err = database.GetDB().Model(&model.Host{}).
Select(`inbound_id, COUNT(*) AS enabled, `+
`SUM(CASE WHEN exclude_from_sub_types LIKE '%"json"%' THEN 1 ELSE 0 END) AS excluding_json_count`).
Where("inbound_id IN ? AND is_disabled = ?", unique, false).
Group("inbound_id").Scan(&hostRows).Error
if err != nil {
return nil, nil, nil, err
}
for _, h := range hostRows {
if h.Enabled > 0 && h.ExcludingJSONCount == h.Enabled {
hostsClosed[h.InboundId] = true
}
}
return byID, clients, hostsClosed, nil
}
// diagnoseSubBalancer groups per-inbound problems by code in selection order,
// then appends no_members when nothing could be emitted.
func diagnoseSubBalancer(b *model.SubBalancer, byID map[int]*model.Inbound, clientCounts map[int]int, hostsClosed map[int]bool) []SubBalancerProblem {
unknown := []int{}
disabled := []int{}
incapable := []int{}
empty := []int{}
closedHosts := []int{}
incapableDetail := ""
contributing := 0
for _, id := range b.InboundIds {
ib, ok := byID[id]
if !ok {
unknown = append(unknown, id)
continue
}
if !ib.Enable {
disabled = append(disabled, id)
continue
}
if _, bad := jsonIncapableProtocols[string(ib.Protocol)]; bad {
incapable = append(incapable, id)
if incapableDetail == "" {
incapableDetail = string(ib.Protocol)
}
continue
}
if clientCounts[id] == 0 {
// Renderable but unreachable: with no client on it the inbound never
// enters any subscription, so the balancer drops out for everyone.
empty = append(empty, id)
continue
}
if hostsClosed[id] {
// Every enabled host excludes the JSON format, so hostEndpoints closes
// the inbound and none of its clients render.
closedHosts = append(closedHosts, id)
continue
}
contributing++
}
problems := make([]SubBalancerProblem, 0, 6)
if len(unknown) > 0 {
problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemUnknownInbound, InboundIds: unknown})
}
if len(disabled) > 0 {
problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemDisabledInbound, InboundIds: disabled})
}
if len(incapable) > 0 {
problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemJSONIncapable, InboundIds: incapable, Detail: incapableDetail})
}
if len(empty) > 0 {
problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemInboundWithoutClients, InboundIds: empty})
}
if len(closedHosts) > 0 {
problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemHostsExcluded, InboundIds: closedHosts})
}
if contributing == 0 {
problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemNoMembers})
}
return problems
}
// loggedProblems remembers the last reported fingerprint per balancer, so the
// read path warns when something changes instead of on every listing.
var loggedProblems = struct {
sync.Mutex
byID map[int]string
}{byID: map[int]string{}}
// LogSubBalancerProblems warns when a balancer's problems change. Identical listings
// stay silent, and a resolution is reported only when a problem was known before.
func LogSubBalancerProblems(b *model.SubBalancer, problems []SubBalancerProblem) {
fingerprint := problemsFingerprint(problems)
loggedProblems.Lock()
previous, seen := loggedProblems.byID[b.Id]
if fingerprint == "" {
delete(loggedProblems.byID, b.Id)
} else {
loggedProblems.byID[b.Id] = fingerprint
}
loggedProblems.Unlock()
if fingerprint == "" {
// Nothing to report for a balancer that never had a problem; a known one
// going quiet is a real transition worth one line.
if seen {
logger.Noticef("[SubBalancer] balancer %q (#%d) no longer has problems", b.Remark, b.Id)
}
return
}
if seen && previous == fingerprint {
return
}
logger.Warningf("[SubBalancer] balancer %q (#%d) has %d problem(s), inboundIds=%v: %+v",
b.Remark, b.Id, len(problems), b.InboundIds, problems)
}
// problemsFingerprint renders the advisories deterministically; empty means
// healthy, which also clears the stored entry.
func problemsFingerprint(problems []SubBalancerProblem) string {
if len(problems) == 0 {
return ""
}
parts := make([]string, 0, len(problems))
for _, p := range problems {
ids := make([]string, 0, len(p.InboundIds))
for _, id := range p.InboundIds {
ids = append(ids, strconv.Itoa(id))
}
parts = append(parts, p.Code+"["+strings.Join(ids, ",")+"]"+p.Detail)
}
return strings.Join(parts, ";")
}
@@ -0,0 +1,149 @@
package service
import (
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"testing"
)
// A protocol the JSON service never renders must not count as a working member.
// Both sides are parsed from source, so drift fails here rather than in production.
func TestJSONIncapableProtocolsMatchRenderer(t *testing.T) {
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("cannot locate test file")
}
subDir := filepath.Join(filepath.Dir(thisFile), "..", "..", "sub")
capable := rendererCapableProtocols(t, filepath.Join(subDir, "json_service.go"))
allowlist := subscriptionAllowlist(t, filepath.Join(subDir, "service.go"))
if len(capable) == 0 || len(allowlist) == 0 {
t.Fatalf("parsed nothing meaningful (capable=%d allowlist=%d); did the sources move?", len(capable), len(allowlist))
}
want := make([]string, 0, len(allowlist))
for _, protocol := range allowlist {
if !capable[protocol] {
want = append(want, protocol)
}
}
got := make([]string, 0, len(jsonIncapableProtocols))
for protocol := range jsonIncapableProtocols {
got = append(got, protocol)
}
sort.Strings(want)
sort.Strings(got)
if strings.Join(want, ",") != strings.Join(got, ",") {
t.Fatalf("jsonIncapableProtocols = %v, want %v (allowlist minus renderer-handled protocols)", got, want)
}
}
// rendererCapableProtocols returns the protocols whose case in the Protocol
// switch adds an outbound; a case that only continues (or is absent) cannot.
func rendererCapableProtocols(t *testing.T, path string) map[string]bool {
t.Helper()
file, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)
if err != nil {
t.Fatalf("parse %s: %v", path, err)
}
capable := map[string]bool{}
ast.Inspect(file, func(n ast.Node) bool {
switchStmt, ok := n.(*ast.SwitchStmt)
if !ok {
return true
}
tag, ok := switchStmt.Tag.(*ast.SelectorExpr)
if !ok || tag.Sel.Name != "Protocol" {
return true
}
for _, stmt := range switchStmt.Body.List {
clause, ok := stmt.(*ast.CaseClause)
if !ok {
continue
}
onlyContinue := len(clause.Body) == 1
if onlyContinue {
if branch, ok := clause.Body[0].(*ast.BranchStmt); !ok || branch.Tok != token.CONTINUE {
onlyContinue = false
}
}
if onlyContinue {
continue
}
for _, expr := range clause.List {
if lit, ok := expr.(*ast.BasicLit); ok {
capable[strings.Trim(lit.Value, `"`)] = true
}
}
}
return true
})
return capable
}
// subscriptionAllowlist reads the protocol list the subscription query selects,
// so a protocol added there without renderer support is caught too.
func subscriptionAllowlist(t *testing.T, path string) []string {
t.Helper()
source, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
clause := regexp.MustCompile(`inbounds\.protocol in \(([^)]*)\)`).FindSubmatch(source)
if clause == nil {
t.Fatalf("subscription protocol allowlist not found in %s", path)
}
quoted := regexp.MustCompile(`'([a-z]+)'`).FindAllSubmatch(clause[1], -1)
protocols := make([]string, 0, len(quoted))
for _, match := range quoted {
protocols = append(protocols, string(match[1]))
}
return protocols
}
// The form offers a fixed protocol list; the advisory must agree with it, or the
// UI hides an inbound the diagnosis calls healthy (or offers one it calls broken).
func TestJSONIncapableProtocolsMatchFormList(t *testing.T) {
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("cannot locate test file")
}
formPath := filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "frontend", "src",
"pages", "settings", "SubBalancerFormModal.tsx")
source, err := os.ReadFile(formPath)
if err != nil {
t.Fatalf("read %s: %v", formPath, err)
}
block := regexp.MustCompile(`MULTI_CLIENT_PROTOCOLS\s*=\s*new Set\(\[([^\]]*)\]\)`).FindSubmatch(source)
if block == nil {
t.Fatalf("MULTI_CLIENT_PROTOCOLS not found in %s", formPath)
}
offered := map[string]bool{}
for _, m := range regexp.MustCompile(`'([a-z0-9]+)'`).FindAllSubmatch(block[1], -1) {
offered[string(m[1])] = true
}
if len(offered) == 0 {
t.Fatal("parsed no protocols from the form list")
}
allowlist := subscriptionAllowlist(t, filepath.Join(filepath.Dir(thisFile), "..", "..", "sub", "service.go"))
for _, protocol := range allowlist {
offeredByForm := offered[protocol]
listedByUs := false
if _, ok := jsonIncapableProtocols[protocol]; ok {
listedByUs = true
}
if offeredByForm == listedByUs {
t.Errorf("protocol %q: form offers=%v, advisory lists incapable=%v — they must be opposites",
protocol, offeredByForm, listedByUs)
}
}
}
@@ -0,0 +1,347 @@
package service
import (
"fmt"
"strings"
"sync"
"testing"
"github.com/op/go-logging"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
)
// seedDiagInbound also links one client: a client-less inbound is its own advisory,
// separately tested, and must not leak into tests aimed at other codes.
func seedDiagInbound(t *testing.T, id int, protocol model.Protocol, enable bool) {
t.Helper()
ib := &model.Inbound{
Id: id, UserId: 1, Tag: fmt.Sprintf("diag-%d", id), Enable: enable,
Listen: "203.0.113.9", Port: 4000 + id, Protocol: protocol,
Remark: fmt.Sprintf("diag-%d", id), Settings: `{}`, StreamSettings: `{}`,
}
if err := database.GetDB().Create(ib).Error; err != nil {
t.Fatalf("seed inbound %d: %v", id, err)
}
client := &model.ClientRecord{
Email: fmt.Sprintf("diag-%d@test", id), SubID: fmt.Sprintf("diag%d", id), Enable: true,
}
if err := database.GetDB().Create(client).Error; err != nil {
t.Fatalf("seed client %d: %v", id, err)
}
if err := database.GetDB().Create(&model.ClientInbound{
ClientId: client.Id, InboundId: id,
}).Error; err != nil {
t.Fatalf("link client %d: %v", id, err)
}
}
// seedDiagInboundWithoutClients inserts only the inbound row, leaving
// client_inbounds empty for it.
func seedDiagInboundWithoutClients(t *testing.T, id int, protocol model.Protocol) {
t.Helper()
ib := &model.Inbound{
Id: id, UserId: 1, Tag: fmt.Sprintf("diag-%d", id), Enable: true,
Listen: "203.0.113.9", Port: 4000 + id, Protocol: protocol,
Remark: fmt.Sprintf("diag-%d", id), Settings: `{}`, StreamSettings: `{}`,
}
if err := database.GetDB().Create(ib).Error; err != nil {
t.Fatalf("seed inbound %d: %v", id, err)
}
}
// problemCodes flattens the codes so table assertions stay readable.
func problemCodes(problems []SubBalancerProblem) []string {
codes := make([]string, 0, len(problems))
for _, p := range problems {
codes = append(codes, p.Code)
}
return codes
}
func wantCodes(got []string, want ...string) string {
if len(got) != len(want) {
return fmt.Sprintf("codes = %v, want %v", got, want)
}
for i := range got {
if got[i] != want[i] {
return fmt.Sprintf("codes = %v, want %v", got, want)
}
}
return ""
}
// Mixed healthy, dangling, disabled and JSON-incapable inbounds report one problem
// per class in a stable order, and no no_members while one member survives.
func TestSubBalancerProblemsMixedClasses(t *testing.T) {
setupSubBalancerDB(t)
seedDiagInbound(t, 1, model.VLESS, true)
seedDiagInbound(t, 2, model.VLESS, false)
seedDiagInbound(t, 3, model.AmneziaWG, true)
svc := &SubBalancerService{}
if _, err := svc.Create(&model.SubBalancer{
Remark: "mixed", Strategy: "random", InboundIds: []int{1, 2, 3, 99}, SortOrder: 1, Enabled: true,
}); err != nil {
t.Fatalf("create: %v", err)
}
list, err := svc.ListWithProblems()
if err != nil {
t.Fatalf("ListWithProblems: %v", err)
}
if len(list) != 1 {
t.Fatalf("len = %d, want 1", len(list))
}
got := problemCodes(list[0].Problems)
if diff := wantCodes(got, SubBalancerProblemUnknownInbound, SubBalancerProblemDisabledInbound, SubBalancerProblemJSONIncapable); diff != "" {
t.Fatal(diff)
}
if ids := list[0].Problems[0].InboundIds; len(ids) != 1 || ids[0] != 99 {
t.Fatalf("unknown ids = %v, want [99]", ids)
}
if ids := list[0].Problems[1].InboundIds; len(ids) != 1 || ids[0] != 2 {
t.Fatalf("disabled ids = %v, want [2]", ids)
}
if detail := list[0].Problems[2].Detail; detail != "amneziawg" {
t.Fatalf("detail = %q, want amneziawg", detail)
}
}
// Every selected inbound unusable means the balancer is omitted at render
// time; the advisory says so once, without per-inbound codes meaning nothing.
func TestSubBalancerProblemsNoMembers(t *testing.T) {
setupSubBalancerDB(t)
seedDiagInbound(t, 1, model.TUIC, true)
svc := &SubBalancerService{}
if _, err := svc.Create(&model.SubBalancer{
Remark: "dead", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true,
}); err != nil {
t.Fatalf("create: %v", err)
}
list, err := svc.ListWithProblems()
if err != nil {
t.Fatalf("ListWithProblems: %v", err)
}
got := problemCodes(list[0].Problems)
if diff := wantCodes(got, SubBalancerProblemJSONIncapable, SubBalancerProblemNoMembers); diff != "" {
t.Fatal(diff)
}
}
// A purely healthy balancer carries an empty, non-nil slice so the JSON shape
// stays "problems": [] rather than dropping the field.
func TestSubBalancerProblemsHealthyIsEmpty(t *testing.T) {
setupSubBalancerDB(t)
seedDiagInbound(t, 1, model.VLESS, true)
svc := &SubBalancerService{}
if _, err := svc.Create(&model.SubBalancer{
Remark: "fine", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true,
}); err != nil {
t.Fatalf("create: %v", err)
}
list, err := svc.ListWithProblems()
if err != nil {
t.Fatalf("ListWithProblems: %v", err)
}
if list[0].Problems == nil {
t.Fatal("Problems = nil, want non-nil empty slice")
}
if len(list[0].Problems) != 0 {
t.Fatalf("Problems = %v, want empty", list[0].Problems)
}
}
// diagnoseSubBalancer is pure; unknown ids keep selection order and no_members
// is never reported while one member contributes.
func TestDiagnoseSubBalancerOrderAndNoMembers(t *testing.T) {
byID := map[int]*model.Inbound{
1: {Id: 1, Protocol: model.VLESS, Enable: true},
2: {Id: 2, Protocol: model.VLESS, Enable: false},
}
// Inbound 1 has a client, so it still contributes and no_members stays away.
clientCounts := map[int]int{1: 3}
bal := &model.SubBalancer{Id: 7, Remark: "pure", InboundIds: []int{42, 2, 1, 41}}
problems := diagnoseSubBalancer(bal, byID, clientCounts, nil)
if diff := wantCodes(problemCodes(problems), SubBalancerProblemUnknownInbound, SubBalancerProblemDisabledInbound); diff != "" {
t.Fatal(diff)
}
if ids := problems[0].InboundIds; len(ids) != 2 || ids[0] != 42 || ids[1] != 41 {
t.Fatalf("unknown ids = %v, want [42 41] in selection order", ids)
}
allDisabled := &model.SubBalancer{Id: 8, Remark: "off", InboundIds: []int{2}}
problems = diagnoseSubBalancer(allDisabled, byID, clientCounts, nil)
if diff := wantCodes(problemCodes(problems), SubBalancerProblemDisabledInbound, SubBalancerProblemNoMembers); diff != "" {
t.Fatal(diff)
}
}
// A renderable inbound nobody sits on reaches no subscription, so the balancer
// drops out for everyone — the silence this feature exists to explain.
func TestSubBalancerProblemsInboundWithoutClients(t *testing.T) {
setupSubBalancerDB(t)
// Seeding only the inbound leaves client_inbounds empty.
seedDiagInboundWithoutClients(t, 1, model.VLESS)
svc := &SubBalancerService{}
if _, err := svc.Create(&model.SubBalancer{
Remark: "empty", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true,
}); err != nil {
t.Fatalf("create: %v", err)
}
list, err := svc.ListWithProblems()
if err != nil {
t.Fatalf("ListWithProblems: %v", err)
}
got := problemCodes(list[0].Problems)
if diff := wantCodes(got, SubBalancerProblemInboundWithoutClients, SubBalancerProblemNoMembers); diff != "" {
t.Fatal(diff)
}
}
// The log is the contract, not the fingerprint map: assert on what was written.
func TestLogSubBalancerProblemsDeduplicates(t *testing.T) {
xuilogger.InitLogger(logging.DEBUG)
bal := &model.SubBalancer{Id: 9001, Remark: "dedup-9001", InboundIds: []int{5}}
problem := []SubBalancerProblem{{Code: SubBalancerProblemUnknownInbound, InboundIds: []int{5}}}
before := len(logLines())
LogSubBalancerProblems(bal, problem)
if got := logLinesSince(before); countContaining(got, "dedup-9001") != 1 {
t.Fatalf("first listing: want exactly one line, got %v", got)
}
// Same problem set again: the journal must not repeat itself.
before = len(logLines())
LogSubBalancerProblems(bal, problem)
if got := logLinesSince(before); countContaining(got, "dedup-9001") != 0 {
t.Fatalf("repeat listing: want no line, got %v", got)
}
// A known problem going quiet is a real transition: exactly one notice.
before = len(logLines())
LogSubBalancerProblems(bal, nil)
lines := logLinesSince(before)
if countContaining(lines, "no longer has problems") != 1 {
t.Fatalf("resolution: want one notice, got %v", lines)
}
// A balancer that never had a problem must stay silent on every listing.
healthy := &model.SubBalancer{Id: 9002, Remark: "healthy-9002", InboundIds: []int{6}}
for i := 0; i < 3; i++ {
before = len(logLines())
LogSubBalancerProblems(healthy, nil)
if got := logLinesSince(before); countContaining(got, "healthy-9002") != 0 {
t.Fatalf("healthy listing %d: want silence, got %v", i, got)
}
}
}
// GetLogs returns newest first and caps at c, so read a large window and take a
// snapshot before each call instead of trusting absolute indices.
func logLines() []string { return xuilogger.GetLogs(1_000_000, "DEBUG") }
func logLinesSince(n int) []string {
all := logLines()
if len(all) <= n {
return nil
}
return all[:len(all)-n]
}
func countContaining(lines []string, substr string) int {
count := 0
for _, line := range lines {
if strings.Contains(line, substr) {
count++
}
}
return count
}
// The map is shared across concurrent listings (settings tab + refetches).
func TestLogSubBalancerProblemsConcurrent(t *testing.T) {
var wg sync.WaitGroup
for i := 0; i < 16; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
bal := &model.SubBalancer{Id: 9100 + id, Remark: "race", InboundIds: []int{id}}
problems := []SubBalancerProblem{
{Code: SubBalancerProblemUnknownInbound, InboundIds: []int{id}},
}
LogSubBalancerProblems(bal, problems)
}(i)
}
wg.Wait()
}
// An inbound whose every enabled host excludes the JSON format is closed by
// hostEndpoints: its clients never render, so the balancer emits nothing.
func TestSubBalancerProblemsAllHostsExcludedFromJSON(t *testing.T) {
setupSubBalancerDB(t)
seedDiagInbound(t, 1, model.VLESS, true) // also links one client
for i, types := range [][]string{{"json"}, {"json", "clash"}} {
host := &model.Host{
InboundId: 1, Remark: fmt.Sprintf("host-%d", i),
Address: "cdn.example.com", Port: 443, ExcludeFromSubTypes: types,
}
if err := database.GetDB().Create(host).Error; err != nil {
t.Fatalf("seed host %d: %v", i, err)
}
}
svc := &SubBalancerService{}
if _, err := svc.Create(&model.SubBalancer{
Remark: "closed", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true,
}); err != nil {
t.Fatalf("create: %v", err)
}
list, err := svc.ListWithProblems()
if err != nil {
t.Fatalf("ListWithProblems: %v", err)
}
got := problemCodes(list[0].Problems)
if diff := wantCodes(got, SubBalancerProblemHostsExcluded, SubBalancerProblemNoMembers); diff != "" {
t.Fatal(diff)
}
}
// One host still serving JSON keeps the inbound usable, so no advisory appears.
func TestSubBalancerProblemsPartiallyExcludedHostsAreHealthy(t *testing.T) {
setupSubBalancerDB(t)
seedDiagInbound(t, 1, model.VLESS, true)
hosts := []*model.Host{
{InboundId: 1, Remark: "closed", Address: "a.example.com", Port: 443, ExcludeFromSubTypes: []string{"json"}},
{InboundId: 1, Remark: "open", Address: "b.example.com", Port: 443},
}
for _, h := range hosts {
if err := database.GetDB().Create(h).Error; err != nil {
t.Fatalf("seed host: %v", err)
}
}
svc := &SubBalancerService{}
if _, err := svc.Create(&model.SubBalancer{
Remark: "partial", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true,
}); err != nil {
t.Fatalf("create: %v", err)
}
list, err := svc.ListWithProblems()
if err != nil {
t.Fatalf("ListWithProblems: %v", err)
}
if len(list[0].Problems) != 0 {
t.Fatalf("Problems = %v, want none", problemCodes(list[0].Problems))
}
}
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "الموضع في قائمة الاشتراك، متداخل مع ترتيب الإينبوندات؛ عند تساوي الرقم يأتي الموزّع بعد الإينباند.",
"inbounds": "الإينبوندات",
"inboundsCount": "{count} الإينبوندات",
"problems": "المشكلات",
"problemsCount": "{count} مشكلة",
"problem": {
"unknown_inbound": "الإنباند لم يعد موجودًا",
"disabled_inbound": "الإنباند معطّل",
"json_incapable_protocol": "البروتوكول لا يحتوي على خروج JSON، لذا لا يمكن أن يكون عضوًا",
"no_members": "لا يوجد عضو قابل للاستخدام: يتم استبعاد الموزّع من اشتراك JSON",
"inbound_without_clients": "الإنباند ليس لديه عملاء، لذا لا يصل إلى أي اشتراك",
"hosts_excluded_from_json": "جميع المضيفين المفعّلين لهذا الإنباند مستبعدون من تنسيق JSON"
},
"weights": "أوزان الأعضاء",
"weightsHelp": "لـ LeastLoad فقط: الوزن الأقل يُختار أكثر؛ العضو بدون قيمة وزنه 1.",
"enabled": "مُفعّل",
+10
View File
@@ -1857,6 +1857,16 @@
"sortOrderHelp": "Position in the subscription list, interleaved with the inbounds' own order; on equal numbers the balancer comes after the inbound.",
"inbounds": "Inbounds",
"inboundsCount": "{count} Inbounds",
"problems": "Problems",
"problemsCount": "{count} problem(s)",
"problem": {
"unknown_inbound": "Inbound no longer exists",
"disabled_inbound": "Inbound is disabled",
"json_incapable_protocol": "Protocol has no JSON outbound, so it cannot be a member",
"no_members": "No usable member: the balancer is omitted from the JSON subscription",
"inbound_without_clients": "Inbound has no clients, so it reaches no subscription",
"hosts_excluded_from_json": "All enabled hosts of this inbound are excluded from the JSON format"
},
"weights": "Member weights",
"weightsHelp": "Only for LeastLoad: a lower weight is picked more often; members without a value weigh 1.",
"enabled": "Enabled",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "Posición en la lista de la suscripción, intercalada con el orden de los inbounds; con el mismo número, el balanceador va después del inbound.",
"inbounds": "Inbounds",
"inboundsCount": "{count} Inbounds",
"problems": "Problemas",
"problemsCount": "{count} problema(s)",
"problem": {
"unknown_inbound": "El inbound ya no existe",
"disabled_inbound": "El inbound está deshabilitado",
"json_incapable_protocol": "El protocolo no tiene outbound JSON, así que no puede ser miembro",
"no_members": "Ningún miembro utilizable: el balanceador se omite de la suscripción JSON",
"inbound_without_clients": "El inbound no tiene clientes, así que no llega a ninguna suscripción",
"hosts_excluded_from_json": "Todos los hosts habilitados de este inbound están excluidos del formato JSON"
},
"weights": "Pesos de miembros",
"weightsHelp": "Solo para LeastLoad: un peso más bajo se elige con más frecuencia; los miembros sin valor pesan 1.",
"enabled": "Activado",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "جایگاه در فهرست اشتراک، درهم‌تنیده با ترتیب اینباند‌ها؛ با شمارهٔ برابر، موزان‌کننده بعد از اینباند می‌آید.",
"inbounds": "اینباند‌ها",
"inboundsCount": "{count} اینباند‌ها",
"problems": "مشکلات",
"problemsCount": "{count} مشکل",
"problem": {
"unknown_inbound": "اینباند دیگر وجود ندارد",
"disabled_inbound": "اینباند غیرفعال است",
"json_incapable_protocol": "پروتکل خروجی JSON ندارد، بنابراین نمیتواند عضو باشد",
"no_members": "عضو قابل استفاده‌ای نیست: متعادل‌کننده از اشتراک JSON حذف شد",
"inbound_without_clients": "اینباند هیچ کلاینتی ندارد، بنابراین به هیچ اشتراکی نمیرسد",
"hosts_excluded_from_json": "همهٔ هاست‌های فعال این اینباند از قالب JSON حذف شده‌اند"
},
"weights": "وزن اعضا",
"weightsHelp": "فقط برای LeastLoad: وزن کمتر بیشتر انتخاب می‌شود؛ عضوی که مقداری نداشته باشد وزن ۱ دارد.",
"enabled": "فعال",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "Posisi dalam daftar langganan, berselang-seling dengan urutan inbound; jika sama, penyeimbang berada setelah inbound.",
"inbounds": "Inbound",
"inboundsCount": "{count} Inbound",
"problems": "Masalah",
"problemsCount": "{count} masalah",
"problem": {
"unknown_inbound": "Inbound tidak ada lagi",
"disabled_inbound": "Inbound dinonaktifkan",
"json_incapable_protocol": "Protokol tidak memiliki outbound JSON, jadi tidak bisa menjadi anggota",
"no_members": "Tidak ada anggota yang dapat digunakan: penyeimbang dihilangkan dari langganan JSON",
"inbound_without_clients": "Inbound tidak memiliki klien, sehingga tidak masuk ke langganan mana pun",
"hosts_excluded_from_json": "Semua host yang aktif pada inbound ini dikecualikan dari format JSON"
},
"weights": "Bobot anggota",
"weightsHelp": "Hanya untuk LeastLoad: bobot lebih rendah lebih sering dipilih; anggota tanpa nilai berbobot 1.",
"enabled": "Aktif",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "サブスクリプション一覧内の位置。インバウンドの順序と交互に並び、同番号の場合はインバウンドの後ろになります。",
"inbounds": "インバウンド",
"inboundsCount": "{count} インバウンド",
"problems": "問題",
"problemsCount": "{count} 件の問題",
"problem": {
"unknown_inbound": "インバウンドは存在しません",
"disabled_inbound": "インバウンドは無効です",
"json_incapable_protocol": "プロトコルに JSON アウトバウンドがないため、メンバーにできません",
"no_members": "使用可能なメンバーがありません: バランサーは JSON サブスクリプションから除外されます",
"inbound_without_clients": "インバウンドにクライアントがないため、どのサブスクリプションにも届きません",
"hosts_excluded_from_json": "このインバウンドの有効なホストはすべて JSON 形式から除外されています"
},
"weights": "メンバーの重み",
"weightsHelp": "LeastLoad のみ:値が小さいほど選ばれやすくなります。未指定のメンバーは重み 1 です。",
"enabled": "有効",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "Posição na lista da assinatura, intercalada com a ordem dos inbounds; em caso de empate, o balanceador vem depois do inbound.",
"inbounds": "Inbounds",
"inboundsCount": "{count} Inbounds",
"problems": "Problemas",
"problemsCount": "{count} problema(s)",
"problem": {
"unknown_inbound": "O inbound não existe mais",
"disabled_inbound": "O inbound está desativado",
"json_incapable_protocol": "O protocolo não tem outbound JSON, então não pode ser membro",
"no_members": "Nenhum membro utilizável: o balanceador é omitido da assinatura JSON",
"inbound_without_clients": "O inbound não tem clientes, então não chega a nenhuma assinatura",
"hosts_excluded_from_json": "Todos os hosts habilitados deste inbound estão excluídos do formato JSON"
},
"weights": "Pesos dos membros",
"weightsHelp": "Apenas para LeastLoad: peso menor é escolhido com mais frequência; membros sem valor têm peso 1.",
"enabled": "Ativado",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "Позиция в списке подписки, чередуется с порядком инбаундов; при равных номерах балансировщик идёт после инбаунда.",
"inbounds": "Инбаунды",
"inboundsCount": "{count} Инбаунды",
"problems": "Проблемы",
"problemsCount": "Проблем: {count}",
"problem": {
"unknown_inbound": "Инбаунд больше не существует",
"disabled_inbound": "Инбаунд выключен",
"json_incapable_protocol": "У протокола нет JSON-аутбаунда, участником он быть не может",
"no_members": "Нет рабочего участника: балансер исключается из JSON-подписки",
"inbound_without_clients": "У инбаунда нет клиентов, поэтому он не попадает ни в одну подписку",
"hosts_excluded_from_json": "Все включённые хосты этого инбаунда исключены из JSON-формата"
},
"weights": "Веса участников",
"weightsHelp": "Только для LeastLoad: чем меньше вес, тем чаще выбирается участник; без значения вес равен 1.",
"enabled": "Включён",
+10
View File
@@ -1857,6 +1857,16 @@
"sortOrderHelp": "Pozícia v zozname odberu, spoločne s poradím vstupov. Pri rovnakom čísle nasleduje vyvažovanie po vstupe.",
"inbounds": "Vstupy",
"inboundsCount": "Počet vstupov: {count}",
"problems": "Problémy",
"problemsCount": "{count} problém(ov)",
"problem": {
"unknown_inbound": "Inbound už neexistuje",
"disabled_inbound": "Inbound je vypnutý",
"json_incapable_protocol": "Protokol nemá JSON outbound, preto nemôže byť členom",
"no_members": "Žiadny použiteľný člen: balancer je vynechaný z JSON odberu",
"inbound_without_clients": "Inbound nemá žiadnych klientov, preto sa nedostane do žiadneho odberu",
"hosts_excluded_from_json": "Všetky povolené hosty tohto inboundu sú vylúčené z formátu JSON"
},
"weights": "Váhy členov",
"weightsHelp": "Iba pre LeastLoad: nižšia váha znamená častejší výber. Bez zadanej hodnoty má člen váhu 1.",
"enabled": "Zapnuté",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "Abonelik listesindeki konumu, inbound sırası ile iç içe yerleşir; eşit numarada dengeleyici inbound'dan sonra gelir.",
"inbounds": "Inbound'lar",
"inboundsCount": "{count} Inbound'lar",
"problems": "Sorunlar",
"problemsCount": "{count} sorun",
"problem": {
"unknown_inbound": "Inbound artık mevcut değil",
"disabled_inbound": "Inbound devre dışı",
"json_incapable_protocol": "Protokolün JSON outbound’u yok, bu yüzden üye olamaz",
"no_members": "Kullanılabilir üye yok: dengeleyici JSON aboneliğinden çıkarıldı",
"inbound_without_clients": "Inbound’un istemcisi yok, bu yüzden hiçbir aboneliğe ulaşmıyor",
"hosts_excluded_from_json": "Bu inbound’un tüm etkin host’ları JSON biçiminden hariç tutuldu"
},
"weights": "Üye ağırlıkları",
"weightsHelp": "Yalnızca LeastLoad için: daha düşük ağırlık daha sık seçilir; değeri olmayan üyelerin ağırlığı 1’dir.",
"enabled": "Etkin",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "Позиція у списку підписки, чергується з порядком інбаундів; за однакового номера йде після інбаунда.",
"inbounds": "Інбаунди",
"inboundsCount": "{count} Інбаунди",
"problems": "Проблеми",
"problemsCount": "Проблем: {count}",
"problem": {
"unknown_inbound": "Інбаунд більше не існує",
"disabled_inbound": "Інбаунд вимкнено",
"json_incapable_protocol": "Протокол не має JSON-аутбаунду, тому не може бути учасником",
"no_members": "Немає робочого учасника: балансер виключено з JSON-підписки",
"inbound_without_clients": "В інбаунда немає клієнтів, тому він не потрапляє в жодну підписку",
"hosts_excluded_from_json": "Усі увімкнені хости цього інбаунда виключені з JSON-формату"
},
"weights": "Ваги учасників",
"weightsHelp": "Лише для LeastLoad: чим менша вага, тим частіше обирається учасник; без значення вага дорівнює 1.",
"enabled": "Увімкнено",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "Vị trí trong danh sách đăng ký, xen kẽ với thứ tự inbound; khi cùng số, bộ cân bằng đứng sau inbound.",
"inbounds": "Inbound",
"inboundsCount": "{count} Inbound",
"problems": "Vấn đề",
"problemsCount": "{count} vấn đề",
"problem": {
"unknown_inbound": "Inbound không còn tồn tại",
"disabled_inbound": "Inbound đang bị tắt",
"json_incapable_protocol": "Giao thức không có outbound JSON nên không thể là thành viên",
"no_members": "Không có thành viên khả dụng: bộ cân bằng bị bỏ khỏi đăng ký JSON",
"inbound_without_clients": "Inbound không có ứng dụng khách nên không xuất hiện trong đăng ký nào",
"hosts_excluded_from_json": "Tất cả máy chủ được bật của inbound này đều bị loại khỏi định dạng JSON"
},
"weights": "Trọng số thành viên",
"weightsHelp": "Chỉ dành cho LeastLoad: trọng số nhỏ hơn được chọn thường xuyên hơn; thành viên không có giá trị mang trọng số 1.",
"enabled": "Đã bật",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "在订阅列表中的位置,与入站顺序交错排列;序号相同时排在入站之后。",
"inbounds": "入站",
"inboundsCount": "{count} 入站",
"problems": "问题",
"problemsCount": "{count} 个问题",
"problem": {
"unknown_inbound": "入站已不存在",
"disabled_inbound": "入站已禁用",
"json_incapable_protocol": "协议没有 JSON 出站,因此不能作为成员",
"no_members": "没有可用的成员:负载均衡器已从 JSON 订阅中省略",
"inbound_without_clients": "入站没有客户端,因此不会出现在任何订阅中",
"hosts_excluded_from_json": "此入站的所有已启用主机都已从 JSON 格式中排除"
},
"weights": "成员权重",
"weightsHelp": "仅适用于 LeastLoad:权重越小越常被选中;未设置的成员权重为 1。",
"enabled": "启用",
+10
View File
@@ -1736,6 +1736,16 @@
"sortOrderHelp": "在訂閱列表中的位置,與入站順序交錯排列;序號相同時排在入站之後。",
"inbounds": "入站",
"inboundsCount": "{count} 入站",
"problems": "問題",
"problemsCount": "{count} 個問題",
"problem": {
"unknown_inbound": "入站已不存在",
"disabled_inbound": "入站已停用",
"json_incapable_protocol": "協定沒有 JSON 出站,因此不能作為成員",
"no_members": "沒有可用的成員:負載平衡器已從 JSON 訂閱中省略",
"inbound_without_clients": "入站沒有用戶端,因此不會出現在任何訂閱中",
"hosts_excluded_from_json": "此入站的所有已啟用主機都已從 JSON 格式中排除"
},
"weights": "成員權重",
"weightsHelp": "僅適用於 LeastLoad:權重越小越常被選中;未設定的成員權重為 1。",
"enabled": "啟用",