publishing: MQTT works in satellite mode + Redis publishes per-client status blob
- Move MQTT init above the satellite early-return in Reflector::initialize so satellite-mode reflectors publish to MQTT (client connect/disconnect, talker events, full status, etc.) just like full reflectors. - Add reflector-sat (SATELLITE_OF=reflector-a) to the default test compose so satellite mode is exercised end-to-end. New test_31 verifies MQTT client-connect/disconnect events under the satellite's own topic prefix. - Add RedisStore::pushClientStatus and Reflector::publishClientStatus to write the per-client status JSON (qth, rx siglev/sql_open/enabled/active, monitoredTGs, selected TG, ...) to live:client:<callsign>.status. Hooked from publishRxUpdate, handleNodeInfo, setMonitoredTGs, and setTg. - New Redis test_live_client_status_blob sends a synthetic MsgNodeInfoV2 with qth+rx and asserts the parsed blob contains the expected fields. 31/31 trunk + 10/10 twin + 14/14 redis pass.
This commit is contained in:
1 parent
6b7a1f0306
commit
688a62ec5b
10 files changed
+299
-33
No files matched your search
+7
-4
@@ -5,7 +5,7 @@
|
||||
The integration tests verify the trunk protocol, satellite links, twin (HA-pair) protocol, Redis-backed config store, and end-to-end audio routing by spinning up reflector meshes in Docker Compose and connecting fake peers and clients from a Python test harness.
|
||||
|
||||
`run_tests.sh` runs in **two phases**:
|
||||
1. A 3-reflector trunk mesh exercising `test_trunk.py` (30 tests).
|
||||
1. A 3-reflector trunk mesh + a satellite-mode reflector exercising `test_trunk.py` (31 tests).
|
||||
2. A 4-reflector twin topology exercising `test_twin.py` (10 tests).
|
||||
|
||||
A separate harness (`run_redis_tests.sh`) runs `test_redis.py` (13 tests) against a single-reflector + Redis stack. See [Redis Integration Tests](#redis-integration-tests) below.
|
||||
@@ -22,7 +22,7 @@ bash run_tests.sh
|
||||
This will:
|
||||
1. Generate the default configs and `docker-compose.test.yml` from `topology.py`
|
||||
2. Build and start the 3-reflector mesh
|
||||
3. Run 30 automated trunk/satellite/MQTT tests (`test_trunk.py`)
|
||||
3. Run 31 automated trunk/satellite/MQTT tests (`test_trunk.py`)
|
||||
4. Enter an interactive prompt to manually test any TG number
|
||||
5. Tear down the default mesh
|
||||
6. Regenerate with `--topology twin` (4-reflector twin topology)
|
||||
@@ -58,7 +58,7 @@ Two fake trunk peers connect from the test harness:
|
||||
Two V2 clients are configured on every reflector:
|
||||
- **N0TEST** / **N0SEND** (group `TestGroup`, password `testpass`)
|
||||
|
||||
A satellite server is enabled on reflector-a (port 5303, secret `sat_secret`).
|
||||
A satellite server is enabled on reflector-a (port 5303, secret `sat_secret`). A real satellite-mode reflector (`reflector-sat`, `SATELLITE_OF=reflector-a`) also runs in the compose so tests can verify satellite-mode behavior end-to-end (e.g. that MQTT publishing still works).
|
||||
|
||||
All test configs have `TRUNK_DEBUG=1` enabled for verbose trunk logging during test runs.
|
||||
|
||||
@@ -69,6 +69,7 @@ All test configs have `TRUNK_DEBUG=1` enabled for verbose trunk logging during t
|
||||
| a | 15300 | 15302 | 18080| 15303 |
|
||||
| b | 25300 | 25302 | 28080| — |
|
||||
| c | 35300 | 35302 | 38080| — |
|
||||
| sat | 55300 | — | 58080| — |
|
||||
|
||||
Internal ports inside Docker are always 5300, 5302, 8080, 5303.
|
||||
|
||||
@@ -113,7 +114,7 @@ Internal port for `[TWIN]` is always 5304; satellite is 5303.
|
||||
|------|---------|
|
||||
| `topology.py` | Single source of truth — prefixes, ports, secrets, cluster TGs, test clients. Contains both the default mesh (`REFLECTORS`) and the `TWIN_REFLECTORS` / `TWIN_TRUNKS` definitions. |
|
||||
| `generate_configs.py` | Generates `configs/*.conf` and `docker-compose.test.yml` from topology. Supports `--topology default` (implicit) and `--topology twin`. |
|
||||
| `test_trunk.py` | Test harness: fake trunk peers, satellite peer, V2 client, 30 test cases, interactive loop. |
|
||||
| `test_trunk.py` | Test harness: fake trunk peers, satellite peer, V2 client, 31 test cases, interactive loop. |
|
||||
| `test_twin.py` | TWIN-protocol tests (10 cases) using the twin topology. Reuses `ClientPeer` and `SatellitePeer` from `test_trunk.py`. |
|
||||
| `run_tests.sh` | Orchestrator: generate → build → trunk tests → teardown → regenerate twin → build → twin tests → teardown. |
|
||||
| `configs/` | Generated reflector config files (do not edit manually) |
|
||||
@@ -187,6 +188,7 @@ Simulates a V2 SvxLink client. Performs the full TCP authentication handshake (P
|
||||
| 28 | MQTT client connect/disconnect | V2 client connect publishes `client/<callsign>/connected` (with `tg`, `ip`); disconnect publishes `client/<callsign>/disconnected` |
|
||||
| 29 | MQTT full status | Periodic retained `status` message arrives and contains `nodes` and `trunks` keys |
|
||||
| 30 | MQTT local nodes | Client connect triggers retained `nodes/local` message listing the client's callsign with `timestamp` |
|
||||
| 31 | MQTT works in satellite mode | A satellite-mode reflector (`reflector-sat`, `SATELLITE_OF=reflector-a`) publishes `client/<callsign>/connected` and `disconnected` events under its own topic prefix |
|
||||
|
||||
### Per-Trunk Filters and Mapping (jayReflector additions)
|
||||
|
||||
@@ -250,6 +252,7 @@ Each test writes directly to Redis via `redis-cli` inside the container, publish
|
||||
| 4 | Allow change triggers reload | Adding an allow-list entry produces a matching `Reloaded filters` line |
|
||||
| 5 | `live:client` appears on auth | On V2 authentication, `live:client:<callsign>` hash is populated with `connected_at`, `ip`, `tg`, `codecs` |
|
||||
| 6 | `live:client` disappears on disconnect | After forceful TCP close the hash is removed within ~5 s |
|
||||
| 6b | `live:client` rich status blob | After the client sends `MsgNodeInfo`, `live:client:<callsign>.status` holds the full per-client JSON (qth, rx params, monitoredTGs) and `updated_at` |
|
||||
| 7 | Outage + resync | Stopping Redis keeps existing clients connected; on restart the reflector logs `config.changed: all` and accepts newly-written users |
|
||||
| 8 | `--import-conf-to-redis` idempotent | Running the importer twice against the same `.conf` produces identical keyspace dumps |
|
||||
| 9 | Peer node list populates + diffs | Inbound `MsgTrunkNodeList` creates `live:peer_node:<section>:<callsign>` hashes; a shrunk follow-up list DELs dropped callsigns and updates mutated fields (e.g. `tg`) |
|
||||
|
||||
@@ -126,6 +126,57 @@ def generate_reflector_conf(name: str) -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def generate_satellite_node_conf() -> str:
|
||||
"""Generate svxreflector.conf for a satellite-mode reflector that
|
||||
connects to the primary reflector as a satellite peer."""
|
||||
sat = T.SATELLITE_NODE
|
||||
parent = T.sat_node_parent()
|
||||
parent_svc = T.service_name(parent)
|
||||
parent_prefix = T.prefix_str(T.REFLECTORS[parent]["prefix"])
|
||||
|
||||
lines = [
|
||||
"[GLOBAL]",
|
||||
'TIMESTAMP_FORMAT="%c"',
|
||||
f"LISTEN_PORT={T.INTERNAL_CLIENT_PORT}",
|
||||
"TG_FOR_V1_CLIENTS=999",
|
||||
f"LOCAL_PREFIX={parent_prefix}",
|
||||
f"HTTP_SRV_PORT={T.INTERNAL_HTTP_PORT}",
|
||||
f"SATELLITE_OF={parent_svc}",
|
||||
f"SATELLITE_PORT={T.SATELLITE['listen_port']}",
|
||||
f"SATELLITE_SECRET={T.SATELLITE['secret']}",
|
||||
f"SATELLITE_ID={sat['id']}",
|
||||
"",
|
||||
"[SERVER_CERT]",
|
||||
f"COMMON_NAME={T.sat_node_service_name()}",
|
||||
"",
|
||||
"[USERS]",
|
||||
]
|
||||
groups_seen = set()
|
||||
for client in T.TEST_CLIENTS:
|
||||
lines.append(f"{client['callsign']}={client['group']}")
|
||||
groups_seen.add(client['group'])
|
||||
lines += [
|
||||
"",
|
||||
"[PASSWORDS]",
|
||||
]
|
||||
for client in T.TEST_CLIENTS:
|
||||
if client['group'] in groups_seen:
|
||||
lines.append(f"{client['group']}={client['password']}")
|
||||
groups_seen.discard(client['group'])
|
||||
lines += [
|
||||
"",
|
||||
"[MQTT]",
|
||||
f"HOST={T.MQTT['host']}",
|
||||
f"PORT={T.MQTT['port']}",
|
||||
f"USERNAME={T.MQTT['username']}",
|
||||
f"PASSWORD={T.MQTT['password']}",
|
||||
f"TOPIC_PREFIX=svxreflector/{sat['name']}",
|
||||
"STATUS_INTERVAL=1000",
|
||||
"",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def generate_docker_compose() -> str:
|
||||
"""Generate docker-compose.test.yml content."""
|
||||
services = []
|
||||
@@ -174,6 +225,30 @@ def generate_docker_compose() -> str:
|
||||
networks:
|
||||
- trunk_mesh{depends_on_line}""")
|
||||
|
||||
# Satellite-mode reflector — joins the primary as a satellite. Used
|
||||
# to verify satellite-mode behavior (MQTT publishing, V2 client server).
|
||||
sat_svc = T.sat_node_service_name()
|
||||
sat_vol = f"pki-{T.SATELLITE_NODE['name']}"
|
||||
volumes.append(sat_vol)
|
||||
services.append(f""" {sat_svc}:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: Dockerfile
|
||||
volumes:
|
||||
- ./configs/{sat_svc}.conf:/etc/svxlink/svxreflector.conf:ro
|
||||
- {sat_vol}:/var/lib/svxlink/pki
|
||||
ports:
|
||||
- "{T.sat_node_mapped_client_port()}:{T.INTERNAL_CLIENT_PORT}/tcp"
|
||||
- "{T.sat_node_mapped_client_port()}:{T.INTERNAL_CLIENT_PORT}/udp"
|
||||
- "{T.sat_node_mapped_http_port()}:{T.INTERNAL_HTTP_PORT}/tcp"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "bash -c '(echo > /dev/tcp/localhost/{T.INTERNAL_HTTP_PORT}) 2>/dev/null'"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 15
|
||||
networks:
|
||||
- trunk_mesh""")
|
||||
|
||||
# Mosquitto broker for MQTT testing
|
||||
services.append(""" mosquitto:
|
||||
image: eclipse-mosquitto:2
|
||||
@@ -496,6 +571,13 @@ def main():
|
||||
f.write(content)
|
||||
print(f" wrote {os.path.relpath(path, script_dir)}")
|
||||
|
||||
# Satellite-mode reflector config
|
||||
sat_path = os.path.join(configs_dir,
|
||||
f"{T.sat_node_service_name()}.conf")
|
||||
with open(sat_path, "w") as f:
|
||||
f.write(generate_satellite_node_conf())
|
||||
print(f" wrote {os.path.relpath(sat_path, script_dir)}")
|
||||
|
||||
# Generate docker-compose
|
||||
compose_path = os.path.join(script_dir, "docker-compose.test.yml")
|
||||
with open(compose_path, "w") as f:
|
||||
|
||||
+56
-1
@@ -14,7 +14,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import topology_redis as T
|
||||
from test_trunk import ClientPeer, TrunkPeer
|
||||
from test_trunk import ClientPeer, TrunkPeer, send_frame, pack_string
|
||||
|
||||
HOST = "127.0.0.1"
|
||||
|
||||
@@ -230,6 +230,61 @@ class RedisLiveStateTest(unittest.TestCase):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def test_live_client_status_blob(self):
|
||||
"""After a V2 client sends MsgNodeInfo (qth + rx + monitoredTGs),
|
||||
the rich status blob lands in live:client:<callsign>.status as a
|
||||
serialized JSON string containing qth, rx params, and monitoredTGs."""
|
||||
import json as _json
|
||||
import struct as _struct
|
||||
MSG_NODE_INFO_V2 = 111
|
||||
|
||||
peer = ClientPeer()
|
||||
peer.connect(HOST, R1_CLIENT_PORT)
|
||||
try:
|
||||
peer.authenticate(callsign="N0TEST", password="testpass")
|
||||
self._wait_for_hash(k("live:client:N0TEST"), present=True)
|
||||
|
||||
node_info = {
|
||||
"swInfo": "test-client/1.0",
|
||||
"qth": [{
|
||||
"name": "Test QTH",
|
||||
"lat": 45.5,
|
||||
"lon": 9.2,
|
||||
"rx": {"A": {"name": "TestRx"}},
|
||||
"tx": {"A": {"name": "TestTx"}},
|
||||
}],
|
||||
}
|
||||
payload = _struct.pack("!H", MSG_NODE_INFO_V2)
|
||||
payload += pack_string(_json.dumps(node_info))
|
||||
send_frame(peer.tcp, payload)
|
||||
|
||||
# Wait for status field to appear and parse as JSON
|
||||
deadline = time.time() + 3.0
|
||||
blob = ""
|
||||
while time.time() < deadline:
|
||||
blob = redis_cli("HGET", k("live:client:N0TEST"), "status")
|
||||
if blob:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
self.assertNotEqual(blob, "",
|
||||
"status field never appeared on live:client:N0TEST")
|
||||
|
||||
status = _json.loads(blob)
|
||||
self.assertIn("qth", status)
|
||||
self.assertEqual(status["qth"][0]["name"], "Test QTH")
|
||||
self.assertAlmostEqual(status["qth"][0]["lat"], 45.5)
|
||||
self.assertIn("rx", status["qth"][0])
|
||||
self.assertIn("A", status["qth"][0]["rx"])
|
||||
# Reflector populates default rx params after parsing NodeInfo
|
||||
self.assertIn("siglev", status["qth"][0]["rx"]["A"])
|
||||
self.assertIn("sql_open", status["qth"][0]["rx"]["A"])
|
||||
self.assertIn("monitoredTGs", status)
|
||||
finally:
|
||||
try:
|
||||
peer.tcp.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def test_live_client_hash_disappears_on_disconnect(self):
|
||||
peer = ClientPeer()
|
||||
peer.connect(HOST, R1_CLIENT_PORT)
|
||||
|
||||
@@ -1872,6 +1872,69 @@ class TestTrunkIntegration(unittest.TestCase):
|
||||
mc.loop_stop()
|
||||
mc.disconnect()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Test 31: MQTT works in satellite mode
|
||||
# ------------------------------------------------------------------
|
||||
def test_31_mqtt_satellite_client_events(self):
|
||||
"""A satellite-mode reflector publishes MQTT client connect and
|
||||
disconnect events under its own topic prefix, just like a full
|
||||
reflector. Verifies that the MQTT init runs before the satellite
|
||||
early-return in Reflector::initialize()."""
|
||||
sat_name = T.SATELLITE_NODE["name"]
|
||||
sat_topic = f"svxreflector/{sat_name}/client/{CLIENT_CALLSIGN}"
|
||||
received = []
|
||||
sub_event = threading.Event()
|
||||
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
client.subscribe(f"{sat_topic}/#")
|
||||
sub_event.set()
|
||||
|
||||
def on_message(client, userdata, msg):
|
||||
try:
|
||||
payload = json.loads(msg.payload)
|
||||
except (ValueError, json.JSONDecodeError):
|
||||
payload = msg.payload
|
||||
received.append((msg.topic, payload))
|
||||
|
||||
mc = mqtt_client.Client()
|
||||
mc.on_connect = on_connect
|
||||
mc.on_message = on_message
|
||||
mc.connect(HOST, 11883, 60)
|
||||
mc.loop_start()
|
||||
|
||||
try:
|
||||
self.assertTrue(sub_event.wait(timeout=5),
|
||||
"MQTT subscribe timed out")
|
||||
time.sleep(0.5)
|
||||
|
||||
client = ClientPeer()
|
||||
client.connect(HOST, T.sat_node_mapped_client_port())
|
||||
client.authenticate(callsign=CLIENT_CALLSIGN,
|
||||
password=CLIENT_PASSWORD)
|
||||
time.sleep(2)
|
||||
|
||||
connected_topic = f"{sat_topic}/connected"
|
||||
conn_events = [r for r in received if r[0] == connected_topic]
|
||||
self.assertTrue(len(conn_events) > 0,
|
||||
f"Expected MQTT connected event from satellite, "
|
||||
f"got topics: {[r[0] for r in received]}")
|
||||
payload = conn_events[0][1]
|
||||
self.assertIn("tg", payload)
|
||||
self.assertIn("ip", payload)
|
||||
|
||||
received.clear()
|
||||
client.close()
|
||||
time.sleep(2)
|
||||
|
||||
disconnected_topic = f"{sat_topic}/disconnected"
|
||||
disc_events = [r for r in received if r[0] == disconnected_topic]
|
||||
self.assertTrue(len(disc_events) > 0,
|
||||
f"Expected MQTT disconnected event from satellite, "
|
||||
f"got topics: {[r[0] for r in received]}")
|
||||
finally:
|
||||
mc.loop_stop()
|
||||
mc.disconnect()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Custom test runner with clean, readable output
|
||||
|
||||
@@ -61,6 +61,15 @@ SATELLITE = {
|
||||
"listen_port": 5303,
|
||||
}
|
||||
|
||||
# A real satellite-mode reflector — runs as a satellite of the primary
|
||||
# reflector. Used to verify that satellite mode preserves features like
|
||||
# MQTT publishing and the V2 client server.
|
||||
SATELLITE_NODE = {
|
||||
"name": "sat",
|
||||
"id": "SAT_NODE",
|
||||
"port_base": 55000,
|
||||
}
|
||||
|
||||
# Redis broker — used by reflectors flagged `redis: True`.
|
||||
# Each reflector uses its own DB index to avoid pollution between tests.
|
||||
REDIS = {
|
||||
@@ -206,6 +215,19 @@ def service_name(name: str) -> str:
|
||||
def mapped_satellite_port(name: str) -> int:
|
||||
return REFLECTORS[name]["trunk_port_base"] + 303
|
||||
|
||||
def sat_node_service_name() -> str:
|
||||
return f"reflector-{SATELLITE_NODE['name']}"
|
||||
|
||||
def sat_node_parent() -> str:
|
||||
"""Parent reflector that the satellite-mode node attaches to."""
|
||||
return sorted(REFLECTORS)[0]
|
||||
|
||||
def sat_node_mapped_client_port() -> int:
|
||||
return SATELLITE_NODE["port_base"] + 300
|
||||
|
||||
def sat_node_mapped_http_port() -> int:
|
||||
return SATELLITE_NODE["port_base"] + 3080
|
||||
|
||||
def trunk_section_name(name_a: str, name_b: str = "") -> str:
|
||||
"""Shared trunk section name for a link between two reflectors.
|
||||
|
||||
|
||||
Reference in new issue
Block a user