Add independent one-second host WAN telemetry MIT source; preserve existing platform/history
This commit is contained in:
@@ -0,0 +1,358 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-second physical WAN byte samples; independent of Xray/config/billing.
|
||||
|
||||
Linux /proc/net/dev RX means bytes into the server's default physical WAN
|
||||
interface. TX means bytes out. These are host-interface counters, not per-user
|
||||
proxy usage, application payload, or Tailscale logical-interface counters.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import deque
|
||||
import copy
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import signal
|
||||
import ssl
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
VERSION = "toplc-host-traffic/1.0.0"
|
||||
ENDPOINT = "https://vpn.example.invalid/api/v1/node/host-traffic/"
|
||||
MAX_COUNTER = 2**63 - 1
|
||||
MAX_SEQUENCE = 2**53 - 1
|
||||
MAX_BATCH_BYTES = 64 * 1024
|
||||
SAMPLE_SECONDS = 1.0
|
||||
UPLOAD_SECONDS = 5.0
|
||||
QUEUE_CAPACITY = 60
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Credentials:
|
||||
node_slug: str
|
||||
token: str = field(repr=False)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Snapshot:
|
||||
boot_id: str
|
||||
interface: str
|
||||
rx_bytes: int
|
||||
tx_bytes: int
|
||||
monotonic_ns: int
|
||||
observed_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Envelope:
|
||||
boot_id: str
|
||||
interface: str
|
||||
sample: dict
|
||||
|
||||
|
||||
def load_credentials(path: Path) -> Credentials:
|
||||
# Read only these two data values; never source/evaluate an env file or copy
|
||||
# Reality credentials into os.environ, output, state, or an upload payload.
|
||||
wanted = {}
|
||||
for line in Path(path).read_text(encoding="utf-8").splitlines():
|
||||
key, separator, value = line.partition("=")
|
||||
key = key.strip()
|
||||
if not separator or key not in {"NODE_SLUG", "NODE_TOKEN"}:
|
||||
continue
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
|
||||
value = value[1:-1]
|
||||
if key in wanted:
|
||||
raise ValueError("Duplicate node credential field")
|
||||
wanted[key] = value
|
||||
slug, token = wanted.get("NODE_SLUG", ""), wanted.get("NODE_TOKEN", "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{1,120}", slug):
|
||||
raise ValueError("Invalid or missing node slug")
|
||||
if not re.fullmatch(r"[A-Za-z0-9._~+/-]{1,512}=*", token):
|
||||
raise ValueError("Invalid or missing node token")
|
||||
return Credentials(slug, token)
|
||||
|
||||
|
||||
class ProcWanReader:
|
||||
EXCLUDED = ("lo", "tailscale", "docker", "veth", "br-", "virbr", "tun", "tap", "wg")
|
||||
|
||||
def __init__(self, proc: Path = Path("/proc"), sysfs: Path = Path("/sys")):
|
||||
self.proc, self.sysfs = Path(proc), Path(sysfs)
|
||||
|
||||
def physical(self, name: str) -> bool:
|
||||
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", name) or name.startswith(self.EXCLUDED):
|
||||
return False
|
||||
path = self.sysfs / "class/net" / name
|
||||
try:
|
||||
return (path / "device").exists() and (path / "type").read_text().strip() == "1"
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def default_interface(self) -> str:
|
||||
routes = []
|
||||
try:
|
||||
for line in (self.proc / "net/route").read_text().splitlines()[1:]:
|
||||
fields = line.split()
|
||||
if len(fields) >= 8 and fields[1] == "00000000" and fields[7] == "00000000":
|
||||
if int(fields[3], 16) & 1 and self.physical(fields[0]):
|
||||
routes.append((int(fields[6]), fields[0]))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if not routes:
|
||||
try:
|
||||
for line in (self.proc / "net/ipv6_route").read_text().splitlines():
|
||||
fields = line.split()
|
||||
if len(fields) >= 10 and fields[0] == "0" * 32 and fields[1] == "00":
|
||||
if int(fields[8], 16) & 1 and self.physical(fields[9]):
|
||||
routes.append((int(fields[5], 16), fields[9]))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if not routes:
|
||||
raise OSError("No default physical WAN interface available")
|
||||
return min(routes)[1]
|
||||
|
||||
def read(self) -> Snapshot:
|
||||
interface = self.default_interface()
|
||||
boot_id = str(uuid.UUID((self.proc / "sys/kernel/random/boot_id").read_text().strip()))
|
||||
for line in (self.proc / "net/dev").read_text().splitlines():
|
||||
name, separator, counters = line.partition(":")
|
||||
if separator and name.strip() == interface:
|
||||
values = counters.split()
|
||||
if len(values) < 16:
|
||||
raise OSError("Incomplete physical WAN counters")
|
||||
return Snapshot(boot_id, interface, int(values[0]), int(values[8]),
|
||||
time.monotonic_ns(), datetime.now(timezone.utc).isoformat())
|
||||
raise OSError("Default physical WAN interface counters unavailable")
|
||||
|
||||
|
||||
class CounterTracker:
|
||||
def __init__(self):
|
||||
self.previous = None
|
||||
self.counter_epoch = str(uuid.uuid4())
|
||||
self.sequence = 0
|
||||
self.missing = 0
|
||||
|
||||
def note_missing(self, count: int = 1):
|
||||
self.sequence += count
|
||||
self.missing += count
|
||||
|
||||
def observe(self, snapshot: Snapshot) -> Envelope:
|
||||
for value in (snapshot.rx_bytes, snapshot.tx_bytes):
|
||||
if type(value) is not int or not 0 <= value <= MAX_COUNTER:
|
||||
raise ValueError("WAN counter outside signed-64-bit contract")
|
||||
if type(snapshot.monotonic_ns) is not int or snapshot.monotonic_ns < 1:
|
||||
raise ValueError("Positive monotonic timestamp required")
|
||||
boot_id = str(uuid.UUID(snapshot.boot_id))
|
||||
previous = self.previous
|
||||
elapsed = 0.0 if previous is None else (snapshot.monotonic_ns - previous.monotonic_ns) / 1e9
|
||||
quality, rx_rate, tx_rate = "baseline", None, None
|
||||
if previous is not None:
|
||||
if boot_id != str(uuid.UUID(previous.boot_id)):
|
||||
quality, elapsed = "boot_changed", 0.0
|
||||
elif snapshot.interface != previous.interface:
|
||||
quality = "interface_changed"
|
||||
elif snapshot.rx_bytes < previous.rx_bytes or snapshot.tx_bytes < previous.tx_bytes:
|
||||
quality = "reset"
|
||||
elif not 0.5 <= elapsed <= 3.0:
|
||||
quality = "gap"
|
||||
else:
|
||||
quality = "ok"
|
||||
rx_rate = (snapshot.rx_bytes - previous.rx_bytes) / elapsed
|
||||
tx_rate = (snapshot.tx_bytes - previous.tx_bytes) / elapsed
|
||||
if max(rx_rate, tx_rate) > 1e12:
|
||||
quality, rx_rate, tx_rate = "gap", None, None
|
||||
if quality in {"boot_changed", "interface_changed", "reset"}:
|
||||
self.counter_epoch = str(uuid.uuid4())
|
||||
elif quality == "gap" and elapsed <= 0:
|
||||
self.counter_epoch = str(uuid.uuid4())
|
||||
self.sequence += 1
|
||||
if self.sequence > MAX_SEQUENCE:
|
||||
# Practically unreachable (>285M years at 1 Hz); still no key reuse.
|
||||
self.counter_epoch, self.sequence = str(uuid.uuid4()), 1
|
||||
quality, rx_rate, tx_rate = "baseline", None, None
|
||||
row = {"sequence": self.sequence, "observed_at": snapshot.observed_at,
|
||||
"monotonic_ns": snapshot.monotonic_ns, "counter_epoch": self.counter_epoch,
|
||||
"interval_seconds": max(0.0, elapsed), "rx_bytes": snapshot.rx_bytes,
|
||||
"tx_bytes": snapshot.tx_bytes, "rx_bytes_per_second": rx_rate,
|
||||
"tx_bytes_per_second": tx_rate, "quality": quality,
|
||||
"gap_before": bool(self.missing or quality not in {"baseline", "ok"}),
|
||||
"dropped_samples_before": 0}
|
||||
self.previous, self.missing = snapshot, 0
|
||||
return Envelope(boot_id, snapshot.interface, row)
|
||||
|
||||
|
||||
class BoundedSampleQueue:
|
||||
def __init__(self, capacity: int = QUEUE_CAPACITY):
|
||||
if type(capacity) is not int or not 1 <= capacity <= QUEUE_CAPACITY:
|
||||
raise ValueError("Queue capacity outside contract")
|
||||
self.capacity, self.rows, self.lock = capacity, deque(), threading.Lock()
|
||||
|
||||
def put(self, envelope: Envelope):
|
||||
# Never mutate an already queued/transmitted record: an HTTP timeout may
|
||||
# hide a committed batch, and retry bytes must remain idempotent.
|
||||
row = copy.deepcopy(envelope.sample)
|
||||
with self.lock:
|
||||
if len(self.rows) >= self.capacity:
|
||||
dropped = self.rows.popleft()
|
||||
row["gap_before"] = True
|
||||
row["dropped_samples_before"] += 1 + dropped.sample["dropped_samples_before"]
|
||||
self.rows.append(Envelope(envelope.boot_id, envelope.interface, row))
|
||||
|
||||
def batch(self, limit: int = QUEUE_CAPACITY) -> list[Envelope]:
|
||||
with self.lock:
|
||||
if not self.rows:
|
||||
return []
|
||||
group = self.rows[0].boot_id, self.rows[0].interface
|
||||
result = []
|
||||
for row in self.rows:
|
||||
if len(result) >= min(limit, QUEUE_CAPACITY) or (row.boot_id, row.interface) != group:
|
||||
break
|
||||
result.append(copy.deepcopy(row))
|
||||
return result
|
||||
|
||||
def acknowledge(self, batch: list[Envelope]):
|
||||
keys = {(row.sample["counter_epoch"], row.sample["sequence"]) for row in batch}
|
||||
with self.lock:
|
||||
self.rows = deque(row for row in self.rows
|
||||
if (row.sample["counter_epoch"], row.sample["sequence"]) not in keys)
|
||||
|
||||
|
||||
def build_payload(batch: list[Envelope], node_slug: str) -> dict:
|
||||
if not 1 <= len(batch) <= QUEUE_CAPACITY:
|
||||
raise ValueError("Empty or oversized upload batch")
|
||||
first = batch[0]
|
||||
if any((row.boot_id, row.interface) != (first.boot_id, first.interface) for row in batch):
|
||||
raise ValueError("Mixed interface or boot in upload batch")
|
||||
return {"contract": 1, "node_slug": node_slug, "boot_id": first.boot_id,
|
||||
"interface": first.interface, "kind": "server_host_interface",
|
||||
"counter_semantics": "linux_proc_net_dev_interface_bytes",
|
||||
"samples": [copy.deepcopy(row.sample) for row in batch]}
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise urllib.error.HTTPError(newurl, code, "Host traffic redirects are refused", headers, fp)
|
||||
|
||||
|
||||
class HttpTransport:
|
||||
def __init__(self, endpoint: str = ENDPOINT):
|
||||
parsed = urllib.parse.urlsplit(endpoint)
|
||||
if (parsed.scheme != "https" or parsed.hostname != "vpn.example.invalid"
|
||||
or parsed.port not in {None, 443} or parsed.username or parsed.password
|
||||
or parsed.path != "/api/v1/node/host-traffic/" or parsed.query or parsed.fragment):
|
||||
raise ValueError("Untrusted host traffic endpoint")
|
||||
self.endpoint = endpoint
|
||||
self.ssl_context = ssl.create_default_context()
|
||||
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
urllib.request.HTTPSHandler(context=self.ssl_context), NoRedirect())
|
||||
|
||||
def send(self, payload: dict, credentials: Credentials):
|
||||
body = json.dumps(payload, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
||||
if len(body) > MAX_BATCH_BYTES:
|
||||
raise ValueError("Host traffic batch exceeds 64 KiB")
|
||||
request = urllib.request.Request(self.endpoint, data=body, method="POST", headers={
|
||||
"Authorization": "Bearer " + credentials.token, "X-Node-Slug": credentials.node_slug,
|
||||
"X-Agent-Version": VERSION, "User-Agent": VERSION, "Content-Type": "application/json"})
|
||||
with self.opener.open(request, timeout=8) as response:
|
||||
if not 200 <= response.status < 300:
|
||||
raise OSError("Host traffic batch was not committed")
|
||||
response.read(4096) # Body is not logged; HTTP 2xx acknowledges durable whole batch.
|
||||
|
||||
|
||||
class Uploader(threading.Thread):
|
||||
def __init__(self, queue: BoundedSampleQueue, credentials: Credentials, transport,
|
||||
stop: threading.Event, interval: float = UPLOAD_SECONDS, log=None):
|
||||
super().__init__(name="host-traffic-uploader", daemon=True)
|
||||
self.queue, self.credentials, self.transport, self.stop = queue, credentials, transport, stop
|
||||
self.interval = interval
|
||||
self.log = log or (lambda text: print(text, file=sys.stderr, flush=True))
|
||||
self.last_error_log = -1e30
|
||||
|
||||
def upload_once(self) -> bool:
|
||||
batch = self.queue.batch()
|
||||
if not batch:
|
||||
return True
|
||||
try:
|
||||
self.transport.send(build_payload(batch, self.credentials.node_slug), self.credentials)
|
||||
self.queue.acknowledge(batch)
|
||||
return True
|
||||
except Exception as error:
|
||||
# Never include request, headers, response body, exception text, or
|
||||
# credential objects. Failures are bounded and cannot block sampling.
|
||||
now = time.monotonic()
|
||||
if now - self.last_error_log >= 60:
|
||||
status = error.code if isinstance(error, urllib.error.HTTPError) else "none"
|
||||
self.log("host-traffic upload failed: type=" + type(error).__name__ + ",status=" + str(status))
|
||||
self.last_error_log = now
|
||||
return False
|
||||
|
||||
def run(self):
|
||||
while not self.stop.wait(self.interval):
|
||||
self.upload_once()
|
||||
|
||||
|
||||
def run_sampler(reader, queue: BoundedSampleQueue, tracker: CounterTracker,
|
||||
stop: threading.Event, log=None):
|
||||
log = log or (lambda text: print(text, file=sys.stderr, flush=True))
|
||||
deadline, last_error_log = time.monotonic(), -1e30
|
||||
while not stop.is_set():
|
||||
if stop.wait(max(0.0, deadline - time.monotonic())):
|
||||
break
|
||||
try:
|
||||
queue.put(tracker.observe(reader.read()))
|
||||
except (OSError, ValueError):
|
||||
tracker.note_missing()
|
||||
now = time.monotonic()
|
||||
if now - last_error_log >= 60:
|
||||
log("host-traffic sample unavailable; next valid sample will mark a gap")
|
||||
last_error_log = now
|
||||
deadline += SAMPLE_SECONDS
|
||||
now = time.monotonic()
|
||||
if deadline <= now:
|
||||
skipped = int((now - deadline) // SAMPLE_SECONDS) + 1
|
||||
tracker.note_missing(skipped)
|
||||
deadline += skipped * SAMPLE_SECONDS
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--node-env", type=Path, default=Path("/opt/toplc-vpn-node/node.env"))
|
||||
parser.add_argument("--check-config", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
credentials = load_credentials(args.node_env)
|
||||
reader = ProcWanReader()
|
||||
if args.check_config:
|
||||
snapshot = reader.read()
|
||||
print(json.dumps({"version": VERSION, "node_slug": credentials.node_slug,
|
||||
"interface": snapshot.interface, "kind": "server_host_interface",
|
||||
"counter_semantics": "linux_proc_net_dev_interface_bytes", "configuration_valid": True,
|
||||
"network_requested": False, "token_printed": False}))
|
||||
return 0
|
||||
stop = threading.Event()
|
||||
for name in (signal.SIGTERM, signal.SIGINT):
|
||||
signal.signal(name, lambda *_: stop.set())
|
||||
queue, tracker = BoundedSampleQueue(), CounterTracker()
|
||||
uploader = Uploader(queue, credentials, HttpTransport(), stop)
|
||||
uploader.start()
|
||||
try:
|
||||
run_sampler(reader, queue, tracker, stop)
|
||||
finally:
|
||||
stop.set()
|
||||
uploader.join(timeout=9)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OSError, ValueError):
|
||||
print("host-traffic startup refused: invalid or unreadable configuration", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user