feat: cahining + stats
This commit is contained in:
28 files changed
+898
-72
No files matched your search
@@ -22,6 +22,8 @@
|
||||
inboundsEnabled,
|
||||
inboundsLinksFile,
|
||||
inboundsStatsFile,
|
||||
inboundsXray,
|
||||
inboundsApi,
|
||||
inboundsSubscriptionsFile,
|
||||
inboundsSubscriptionsBaseUrl,
|
||||
zapretAutoEnabled,
|
||||
@@ -62,6 +64,8 @@ let
|
||||
INBOUNDS_ENABLED = inboundsEnabled;
|
||||
INBOUNDS_LINKS_FILE = inboundsLinksFile;
|
||||
INBOUNDS_STATS_FILE = inboundsStatsFile;
|
||||
INBOUNDS_XRAY = inboundsXray;
|
||||
INBOUNDS_API = inboundsApi;
|
||||
INBOUNDS_SUBS_FILE = inboundsSubscriptionsFile;
|
||||
INBOUNDS_SUB_BASE_URL = inboundsSubscriptionsBaseUrl;
|
||||
ZAPRET_AUTO_ENABLED = zapretAutoEnabled;
|
||||
|
||||
+75
-21
@@ -100,7 +100,9 @@ A group without a verb shows its status or list.
|
||||
client share link, or the client's outbound JSON
|
||||
inbounds link <tag> --server-json the server's inbound JSON (sudo)
|
||||
inbounds sub [user] [--qr] subscription users, or one user's URL
|
||||
inbounds stats [days] traffic per user (sudo, or userControl)
|
||||
inbounds stats [days] [--by user|inbound|outbound]
|
||||
traffic per user, listener or exit (sudo, or userControl)
|
||||
inbounds online who is connected now, and when the rest were last seen
|
||||
"""
|
||||
|
||||
ROUTE_MODES = ["whitelist", "blacklist", "all-proxy", "all-bypass"]
|
||||
@@ -430,9 +432,11 @@ COMPLETE = {
|
||||
"list": "server inbounds",
|
||||
"link": "client share link",
|
||||
"sub": "subscription users, or one user's URL",
|
||||
"stats": "traffic per user",
|
||||
"stats": "traffic per user, listener or exit",
|
||||
"online": "who is connected now",
|
||||
}
|
||||
},
|
||||
"inbounds stats": {"flags": {"--by": "user, inbound or outbound"}},
|
||||
"inbounds link": {
|
||||
"args": _inbound_link_choices,
|
||||
"flags": {"--qr": "print a QR code", "--json": "the client's outbound JSON", "--server-json": "the server's inbound JSON"},
|
||||
@@ -2408,11 +2412,21 @@ def _today():
|
||||
return datetime.date.today()
|
||||
|
||||
|
||||
def _inbound_stats(days):
|
||||
"""Per-user traffic over the last `days` days, newest first, then totals."""
|
||||
STATS_KINDS = ("user", "inbound", "outbound")
|
||||
|
||||
|
||||
def _inbound_stats(*args):
|
||||
"""Traffic over the last `days` days by user, inbound or outbound, newest first, then totals."""
|
||||
days, kind, rest = "7", "user", list(args)
|
||||
if "--by" in rest:
|
||||
i = rest.index("--by")
|
||||
kind = rest[i + 1] if i + 1 < len(rest) else ""
|
||||
del rest[i : i + 2]
|
||||
if rest:
|
||||
days = rest.pop(0)
|
||||
if rest or kind not in STATS_KINDS or not re.fullmatch(r"[1-9][0-9]*", days):
|
||||
usage("inbounds stats [days] [--by user|inbound|outbound]")
|
||||
path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json")
|
||||
if not re.fullmatch(r"[1-9][0-9]*", days):
|
||||
usage("inbounds stats [days]")
|
||||
# Collect what XRay counted since the last run first; root and userControl
|
||||
# members may, anyone else reads what the timer last wrote.
|
||||
systemctl("--no-ask-password", "start", "proxy-suite-inbound-stats.service", quiet=True)
|
||||
@@ -2420,32 +2434,70 @@ def _inbound_stats(days):
|
||||
die("No traffic recorded yet - the collector runs every 5 minutes.")
|
||||
if not readable(path):
|
||||
die(f"Cannot read {path} - enable userControl, or run with sudo.")
|
||||
stats = read_json(path)
|
||||
since = (_today() - datetime.timedelta(days=int(days) - 1)).isoformat()
|
||||
print(f"Traffic through the inbounds since {since}, by user:")
|
||||
print(f"Traffic through the inbounds since {since}, by {kind}:")
|
||||
|
||||
records = [
|
||||
(day, user, (c or {}).get("down") or 0, (c or {}).get("up") or 0)
|
||||
for day, users in (read_json(path).get("days") or {}).items()
|
||||
(day, name, (c or {}).get("down") or 0, (c or {}).get("up") or 0)
|
||||
for day, kinds in (stats.get("days") or {}).items()
|
||||
if day >= since
|
||||
for user, c in users.items()
|
||||
for name, c in ((kinds or {}).get(kind) or {}).items()
|
||||
]
|
||||
if not records:
|
||||
print(" (nothing recorded)")
|
||||
return
|
||||
row = " {:<12} {:<20} {:>10} {:>10}"
|
||||
print(row.format("DAY", "USER", "DOWN", "UP"))
|
||||
# Newest day first, users in order within a day.
|
||||
for day, user, down, up in sorted(sorted(records, key=lambda r: r[1]), key=lambda r: r[0], reverse=True):
|
||||
print(row.format(day, user, _human_bytes(down), _human_bytes(up)))
|
||||
print(row.format("DAY", kind.upper(), "DOWN", "UP"))
|
||||
# Newest day first, names in order within a day.
|
||||
for day, name, down, up in sorted(sorted(records, key=lambda r: r[1]), key=lambda r: r[0], reverse=True):
|
||||
print(row.format(day, name, _human_bytes(down), _human_bytes(up)))
|
||||
totals = {}
|
||||
for _, user, down, up in records:
|
||||
d, u = totals.get(user, (0, 0))
|
||||
totals[user] = (d + down, u + up)
|
||||
for _, name, down, up in records:
|
||||
d, u = totals.get(name, (0, 0))
|
||||
totals[name] = (d + down, u + up)
|
||||
total = " {:<33} {:>10} {:>10}"
|
||||
print()
|
||||
print(total.format("TOTAL", "DOWN", "UP"))
|
||||
for user, (down, up) in sorted(totals.items()):
|
||||
print(total.format(user, _human_bytes(down), _human_bytes(up)))
|
||||
for name, (down, up) in sorted(totals.items()):
|
||||
print(total.format(name, _human_bytes(down), _human_bytes(up)))
|
||||
|
||||
|
||||
def _inbound_online():
|
||||
"""Users connected right now with their addresses, then when the others were last seen."""
|
||||
status, out = _run(
|
||||
[env("INBOUNDS_XRAY", "xray"), "api", "statsonlineiplist", f"--server={env('INBOUNDS_API', '127.0.0.1:18536')}", "-all"],
|
||||
capture=True,
|
||||
quiet=True,
|
||||
)
|
||||
if status != 0:
|
||||
die("The inbounds' stats API is not answering - is proxy-suite-inbounds running?")
|
||||
try:
|
||||
online = {_s(u.get("email")): u.get("ips") or [] for u in json.loads(out or "{}").get("users") or []}
|
||||
except (ValueError, AttributeError):
|
||||
die("Unexpected answer from the inbounds' stats API.")
|
||||
# As the timer last wrote it: the API already told who is online now.
|
||||
path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json")
|
||||
seen = (read_json(path).get("seen") or {}) if readable(path) else {}
|
||||
# Users nobody has seen yet, when the links say who exists.
|
||||
path = env("INBOUNDS_LINKS_FILE")
|
||||
known = {_s(x.get("user")) for x in read_json(path) if x.get("user")} if readable(path) else set()
|
||||
|
||||
def when(ts):
|
||||
return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
row = " {:<20} {:<24} {}"
|
||||
print(row.format("USER", "STATE", "ADDRESSES"))
|
||||
for user in sorted(set(online) | set(seen) | known):
|
||||
ips = online.get(user)
|
||||
if ips:
|
||||
print(row.format(user, "online", ", ".join(_s(i.get("ip")) for i in ips)))
|
||||
elif user in seen:
|
||||
print(row.format(user, f"seen {when(seen[user])}", ""))
|
||||
else:
|
||||
print(row.format(user, "never seen", ""))
|
||||
sys.stdout.flush()
|
||||
print("A user counts as online while a connection is open; one relayed through a local web server shows as never seen.", file=sys.stderr)
|
||||
|
||||
|
||||
def _inbound_subscriptions(*args):
|
||||
@@ -2505,11 +2557,13 @@ def cmd_inbounds(verb="list", *args):
|
||||
else:
|
||||
_emit(_inbound_link_for(*rest), verb == "qr" or "--qr" in args)
|
||||
elif verb == "stats":
|
||||
_inbound_stats(args[0] if args else "7")
|
||||
_inbound_stats(*args)
|
||||
elif verb == "online":
|
||||
_inbound_online()
|
||||
elif verb == "sub":
|
||||
_inbound_subscriptions(*args)
|
||||
else:
|
||||
usage("inbounds [list] | link <tag> [user] [--qr] | sub [user] [--qr] | stats [days]")
|
||||
usage("inbounds [list] | link <tag> [user] [--qr] | sub [user] [--qr] | stats [days] [--by user|inbound|outbound] | online")
|
||||
|
||||
|
||||
# --- main ---------------------------------------------------------------------
|
||||
|
||||
@@ -44,6 +44,37 @@ def portable_outbound(ob):
|
||||
return ob
|
||||
|
||||
|
||||
def _hop(ob):
|
||||
"""The outbound this one chains through: detour on sing-box, dialerProxy on XRay."""
|
||||
return ob.get("detour") or ((ob.get("streamSettings") or {}).get("sockopt") or {}).get("dialerProxy")
|
||||
|
||||
|
||||
def _dropped(exits, keep):
|
||||
"""Exits that stay behind, and why: all but `keep` and the hops it chains through,
|
||||
loopback hops, and whatever chains through something left behind."""
|
||||
hops = {o["tag"]: _hop(o) for o in exits}
|
||||
chain, tag = set(), keep
|
||||
while tag and tag not in chain:
|
||||
chain.add(tag)
|
||||
tag = hops.get(tag)
|
||||
dropped, warnings = set(), []
|
||||
for o in exits:
|
||||
if keep and o["tag"] not in chain:
|
||||
dropped.add(o["tag"])
|
||||
elif _loopback(o):
|
||||
dropped.add(o["tag"])
|
||||
warnings.append(f"left out {o['tag']}: this host reaches it through a local hop")
|
||||
grew = True
|
||||
while grew:
|
||||
grew = False
|
||||
for tag, hop in hops.items():
|
||||
if tag not in dropped and hop in dropped:
|
||||
dropped.add(tag)
|
||||
warnings.append(f"left out {tag}: it chains through {hop}")
|
||||
grew = True
|
||||
return dropped, warnings
|
||||
|
||||
|
||||
def _backend_tag(tags, only, prefix=""):
|
||||
"""The tag `only` has in the backend: as given, prefixed by the XRay wrapper, or the
|
||||
outbound collapsed into "proxy"."""
|
||||
@@ -55,24 +86,18 @@ def _backend_tag(tags, only, prefix=""):
|
||||
|
||||
def portable_sing_box(cfg, only=None):
|
||||
cfg = copy.deepcopy(cfg)
|
||||
warnings = []
|
||||
obs = cfg.get("outbounds") or []
|
||||
exits = [o for o in obs if o.get("type") not in SING_BOX_SYSTEM]
|
||||
keep = _backend_tag({o["tag"] for o in exits}, only) if only else None
|
||||
|
||||
dropped = set()
|
||||
for o in exits:
|
||||
if keep and o["tag"] != keep:
|
||||
dropped.add(o["tag"])
|
||||
elif _loopback(o):
|
||||
dropped.add(o["tag"])
|
||||
warnings.append(f"left out {o['tag']}: this host reaches it through a local hop")
|
||||
dropped, warnings = _dropped(exits, keep)
|
||||
dropped |= {o["tag"] for o in obs if o["tag"].startswith("proxy-suite-test")}
|
||||
|
||||
obs = [portable_outbound(o) for o in obs if o["tag"] not in dropped]
|
||||
for o in obs:
|
||||
if o.get("type") in GROUPS:
|
||||
o["outbounds"] = [t for t in o.get("outbounds") or [] if t not in dropped]
|
||||
# Not the hops `keep` chains through: they stay only to be chained through.
|
||||
o["outbounds"] = [t for t in o.get("outbounds") or [] if t not in dropped and (not keep or t == keep)]
|
||||
if o.get("default") in dropped:
|
||||
o.pop("default")
|
||||
tags = {o["tag"] for o in obs}
|
||||
@@ -132,18 +157,11 @@ def portable_sing_box(cfg, only=None):
|
||||
|
||||
def portable_xray(cfg, only=None):
|
||||
cfg = copy.deepcopy(cfg)
|
||||
warnings = []
|
||||
obs = cfg.get("outbounds") or []
|
||||
exits = [o for o in obs if o.get("protocol") not in XRAY_SYSTEM]
|
||||
keep = _backend_tag({o["tag"] for o in exits}, only, "proxy-suite-ob-") if only else None
|
||||
|
||||
dropped = set()
|
||||
for o in exits:
|
||||
if keep and o["tag"] != keep:
|
||||
dropped.add(o["tag"])
|
||||
elif _loopback(o):
|
||||
dropped.add(o["tag"])
|
||||
warnings.append(f"left out {o['tag']}: this host reaches it through a local hop")
|
||||
dropped, warnings = _dropped(exits, keep)
|
||||
obs = [portable_outbound(o) for o in obs if o["tag"] not in dropped]
|
||||
remaining = [o["tag"] for o in obs if o.get("protocol") not in XRAY_SYSTEM]
|
||||
if not remaining:
|
||||
@@ -172,6 +190,10 @@ def portable_xray(cfg, only=None):
|
||||
rule["outboundTag"] = keep or remaining[0]
|
||||
rules.append(rule)
|
||||
routing["rules"] = rules
|
||||
if keep:
|
||||
# The selector is a tag prefix, which would also pick the hops `keep` chains through.
|
||||
for balancer in routing.get("balancers") or []:
|
||||
balancer["selector"] = [keep]
|
||||
for key in ("api", "stats", "policy"):
|
||||
cfg.pop(key, None)
|
||||
return cfg, warnings
|
||||
|
||||
@@ -432,6 +432,7 @@ TABS = [
|
||||
Action("J", "client's outbound JSON", lambda r, *_: _link(r, "--json"), when=ROW, mode="dialog"),
|
||||
Action("V", "server's inbound JSON", lambda r, *_: ["inbounds", "link", r["tag"], "--server-json"], when=ROW, mode="dialog"),
|
||||
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
|
||||
Action("o", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
|
||||
@@ -351,13 +351,19 @@ class InboundsTest(EnvTest):
|
||||
"stats.json",
|
||||
{
|
||||
"days": {
|
||||
"2026-09-11": {"fufsob": {"down": 6000000, "up": 4000}, "phone": {"up": 0}},
|
||||
"2026-09-10": {"fufsob": {"down": 1073741824, "up": 1048576}},
|
||||
"2026-09-01": {"fufsob": {"down": 1, "up": 1}},
|
||||
"2026-09-11": {
|
||||
"user": {"fufsob": {"down": 6000000, "up": 4000}, "phone": {"up": 0}},
|
||||
"outbound": {"direct": {"down": 7, "up": 8}},
|
||||
},
|
||||
"2026-09-10": {"user": {"fufsob": {"down": 1073741824, "up": 1048576}}},
|
||||
"2026-09-01": {"user": {"fufsob": {"down": 1, "up": 1}}},
|
||||
}
|
||||
},
|
||||
)
|
||||
out = ok(ctl._inbound_stats, "2")
|
||||
self.assertNotIn("direct", out)
|
||||
self.assertRegex(ok(ctl._inbound_stats, "--by", "outbound"), r"(?m)^ 2026-09-11 +direct +7 B +8 B$")
|
||||
self.assertNotEqual(run(ctl._inbound_stats, "--by", "listener")[0], 0)
|
||||
# Newest day first, sizes readable, then totals over the period.
|
||||
self.assertLess(out.index(" 2026-09-11"), out.index(" 2026-09-10"))
|
||||
self.assertNotIn("2026-09-01", out)
|
||||
@@ -372,6 +378,19 @@ class InboundsTest(EnvTest):
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("No traffic recorded yet", err)
|
||||
|
||||
def test_online(self):
|
||||
answer = {"users": [{"email": "fufsob", "ips": [{"ip": "203.0.113.7", "lastSeen": 1789471207}]}]}
|
||||
self.patch("_run", lambda *a, **kw: (0, json.dumps(answer)))
|
||||
os.environ["INBOUNDS_STATS_FILE"] = self.write("stats.json", {"seen": {"phone": 1789135690}})
|
||||
os.environ["INBOUNDS_LINKS_FILE"] = self.write("links.json", [{"tag": "a", "user": "fufsob"}, {"tag": "a", "user": "teri"}])
|
||||
out = ok(ctl._inbound_online)
|
||||
self.assertRegex(out, r"(?m)^ fufsob +online +203\.0\.113\.7$")
|
||||
self.assertRegex(out, r"(?m)^ phone +seen 2026-09-1\d \d\d:\d\d")
|
||||
self.assertRegex(out, r"(?m)^ teri +never seen")
|
||||
# XRay not running is an error, not an empty table.
|
||||
self.patch("_run", lambda *a, **kw: (1, ""))
|
||||
self.assertNotEqual(run(ctl._inbound_online)[0], 0)
|
||||
|
||||
def test_subscriptions(self):
|
||||
os.environ["INBOUNDS_SUBS_FILE"] = self.write("subs.json", [{"user": "fufsob", "token": "aaa"}, {"user": "teri", "token": "bbb"}])
|
||||
os.environ["INBOUNDS_SUB_BASE_URL"] = "https://vpn.example/sub/"
|
||||
|
||||
@@ -120,6 +120,20 @@ class SingBoxTest(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
export.portable(sing_box_config(), only="nope")
|
||||
|
||||
def test_chains(self):
|
||||
base = sing_box_config()
|
||||
base["outbounds"][1]["detour"] = "vps"
|
||||
base["outbounds"].insert(4, {"type": "trojan", "tag": "via-warp", "server": "nl.example.com", "server_port": 443, "password": "x", "detour": "warp"})
|
||||
base["outbounds"][5]["outbounds"].append("via-warp")
|
||||
# One server takes its hop along, but not into the group.
|
||||
cfg, _ = export.portable(base, only="sub-de")
|
||||
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["vps", "sub-de", "proxy", "direct", "block"])
|
||||
self.assertEqual(cfg["outbounds"][2]["outbounds"], ["sub-de"])
|
||||
# Chained through a hop that stays behind: stays behind too.
|
||||
cfg, warnings = export.portable(base)
|
||||
self.assertNotIn("via-warp", [o["tag"] for o in cfg["outbounds"]])
|
||||
self.assertIn("left out via-warp: it chains through warp", warnings)
|
||||
|
||||
def test_collapsed_proxy(self):
|
||||
base = sing_box_config()
|
||||
base["outbounds"] = [{**base["outbounds"][0], "tag": "proxy"}, base["outbounds"][1], *base["outbounds"][6:]]
|
||||
@@ -164,6 +178,13 @@ class XrayTest(unittest.TestCase):
|
||||
cfg, _ = export.portable(xray_config(), only="de")
|
||||
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["proxy-suite-ob-de", "direct", "block"])
|
||||
|
||||
def test_chains(self):
|
||||
base = xray_config()
|
||||
base["outbounds"][1]["streamSettings"] = {"sockopt": {"dialerProxy": "proxy-suite-ob-vps"}}
|
||||
cfg, _ = export.portable(base, only="de")
|
||||
self.assertEqual([o["tag"] for o in cfg["outbounds"]], ["proxy-suite-ob-vps", "proxy-suite-ob-de", "direct", "block"])
|
||||
self.assertEqual(cfg["routing"]["balancers"][0]["selector"], ["proxy-suite-ob-de"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user