Merge feature/redis-config-store: Redis-backed config store

Adds an optional Redis-backed config store the reflector consults when
[REDIS] is present in svxreflector.conf. When absent, behavior is
byte-identical to master.

When enabled, Redis becomes the source of truth for:
  - [USERS] / [PASSWORDS] (callsign -> password-group -> password)
  - CLUSTER_TGS
  - per-trunk BLACKLIST_TGS / ALLOW_TGS / TG_MAP
  - trunk peer definitions themselves (host/port/secret/remote_prefix/
    peer_id), addable/removable at runtime via pub/sub — no restart

The reflector subscribes to <KEY_PREFIX>:config.changed and reacts per
scope (users, cluster, trunk:<section>, all). Live state (live:client:*,
live:talker:*, live:trunk:*) is pushed through a bounded queue drained
every 75 ms with 60 s TTLs refreshed every 30 s — no Redis call ever
happens on the audio path. Two hiredis async contexts: one pub/sub
subscriber, one for writes. Reconnect with exponential backoff and a
full reload on resume.

Migration tool: svxreflector --import-conf-to-redis [--dry-run]
copies .conf sections into Redis. Idempotent.

Tests: 10 new integration tests (parallel Redis harness with up/test/
down subcommands, separate docker-compose.redis.yml). Legacy trunk
suite fixed: 27/27 pass (was 23/27) — three distinct pre-existing bugs
resolved (missing COMMAND_PTY in generator, statusJson filter dropping
TG_MAP remapped TGs, u32 vs u16 mismatch in Python NodeList parser).

Redis PTY mute plumbing scoped out; mute is local-only and exposed in
/status JSON as a per-trunk 'muted' array. Dashboards drive mutes via
PTY directly.
This commit is contained in:
Audric committed 2026-04-15 16:02:03 +02:00
commit db9dcf6917
25 files changed
+2680 -54

No files matched your search

+7
View File
@@ -28,6 +28,13 @@ tests/configs/
tests/docker-compose.test.yml tests/docker-compose.test.yml
tests/__pycache__/ tests/__pycache__/
# Redis test generated files (regenerated by tests/generate_redis_configs.py)
tests/configs-redis/
tests/docker-compose.redis.yml
# Superpowers workflow artifacts (local only — not for publication)
docs/superpowers/
# Editor and IDE # Editor and IDE
.vscode/ .vscode/
.idea/ .idea/
+2
View File
@@ -11,6 +11,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libopus-dev \ libopus-dev \
libgsm1-dev \ libgsm1-dev \
libmosquitto-dev \ libmosquitto-dev \
libhiredis-dev \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
WORKDIR /src WORKDIR /src
@@ -30,6 +31,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libopus0 \ libopus0 \
libgsm1 \ libgsm1 \
libmosquitto1 \ libmosquitto1 \
libhiredis-dev \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
COPY --from=builder /src/build/bin/svxreflector /usr/bin/svxreflector COPY --from=builder /src/build/bin/svxreflector /usr/bin/svxreflector
+2
View File
@@ -450,6 +450,8 @@ The PTY path is set by `COMMAND_PTY` in `[GLOBAL]` (default
example (25 countries, full mesh, DMR MCC-based TG numbering) example (25 countries, full mesh, DMR MCC-based TG numbering)
- [`docs/MQTT.md`](docs/MQTT.md) — MQTT publishing: topic structure, payload - [`docs/MQTT.md`](docs/MQTT.md) — MQTT publishing: topic structure, payload
format, configuration reference, and TLS setup format, configuration reference, and TLS setup
- [`docs/REDIS.md`](docs/REDIS.md) — Redis-backed config store: schema,
dashboard operations, pub/sub, migration from .conf
- [`docs/MESSAGING_IDEAS.md`](docs/MESSAGING_IDEAS.md) — ideas for consuming - [`docs/MESSAGING_IDEAS.md`](docs/MESSAGING_IDEAS.md) — ideas for consuming
MQTT events via Telegram, SMS, Discord, webhooks, dashboards, and more MQTT events via Telegram, SMS, Discord, webhooks, dashboards, and more
- [`docs/DESIGN_SATELLITE_AND_CLUSTER.md`](docs/DESIGN_SATELLITE_AND_CLUSTER.md) — design - [`docs/DESIGN_SATELLITE_AND_CLUSTER.md`](docs/DESIGN_SATELLITE_AND_CLUSTER.md) — design
+484
View File
@@ -0,0 +1,484 @@
# Redis-backed Config Store
GeuReflector can optionally use a Redis server as the source of truth for user
credentials, password groups, cluster TGs, and per-trunk dynamic settings
(blacklists, allow-lists, TG maps). This lets a web dashboard push
config changes to a running reflector without file edits or restarts.
Everything else — ports, certificates, `LOCAL_PREFIX`, trunk peer addresses and
secrets, `[SATELLITE]`, `[MQTT]` — stays in `.conf`. Redis does not replace the
config file; it extends it for the mutable subset.
If `[REDIS]` is absent from `svxreflector.conf`, behavior is identical to today
and there is zero overhead.
---
## Enabling Redis
Add a `[REDIS]` section to `svxreflector.conf` and restart:
```ini
[REDIS]
HOST=127.0.0.1
PORT=6379
PASSWORD=
DB=0
KEY_PREFIX=
```
`UNIX_SOCKET` and `HOST`+`PORT` are mutually exclusive — if `UNIX_SOCKET` is
set it takes precedence:
```ini
[REDIS]
UNIX_SOCKET=/var/run/redis/redis.sock
DB=0
KEY_PREFIX=refl1
```
### Configuration reference
| Field | Default | Description |
|-------|---------|-------------|
| `HOST` | `127.0.0.1` | Redis server hostname or IP |
| `PORT` | `6379` | Redis server TCP port |
| `PASSWORD` | *(empty)* | `AUTH` password; omit or leave blank if not set |
| `DB` | `0` | Redis logical database index |
| `KEY_PREFIX` | *(empty)* | Namespace prefix; when set, all keys become `<prefix>:<key>` |
| `UNIX_SOCKET` | *(empty)* | Path to Redis UNIX socket; takes precedence over `HOST`/`PORT` |
| `TLS_ENABLED` | `0` | Enable TLS (`1`) or not (`0`) |
| `TLS_CA_CERT` | *(empty)* | Path to CA certificate file |
| `TLS_CLIENT_CERT` | *(empty)* | Path to client certificate (mutual TLS only) |
| `TLS_CLIENT_KEY` | *(empty)* | Path to client private key (mutual TLS only) |
Use `KEY_PREFIX` when multiple reflectors share one Redis instance:
```ini
[REDIS]
HOST=redis.example.com
PORT=6379
KEY_PREFIX=refl-italy-1
```
With `KEY_PREFIX=refl-italy-1`, the key `user:SM0ABC` is stored as
`refl-italy-1:user:SM0ABC`.
---
## Override semantics
When `[REDIS]` is present, Redis **fully overrides** the following:
- `[USERS]` — callsign → password-group mapping
- `[PASSWORDS]` — password-group → plaintext password
- `CLUSTER_TGS` in `[GLOBAL]`
- Per-trunk `BLACKLIST_TGS`, `ALLOW_TGS`, `TG_MAP`
- Trunk peer definitions (host, port, secret, remote_prefix, peer_id) — can be added/removed at runtime without restarting
There is no merging. Entries in `.conf` for these sections are silently ignored.
The reflector logs a warning for each overridden section at startup:
```
WARN: [USERS] in svxreflector.conf is ignored because [REDIS] is configured.
Run --import-conf-to-redis to migrate.
```
To move existing `.conf` users and settings into Redis without data loss, run
the importer (see [Migration](#migration)).
---
## Key schema reference
All keys listed below are prefixed with `<KEY_PREFIX>:` when `KEY_PREFIX` is
set.
### Configuration keys (dashboard writes, reflector reads)
| Key | Redis type | Contents |
|-----|-----------|----------|
| `user:<callsign>` | HASH | `{ group, enabled }` |
| `group:<name>` | HASH | `{ password }` |
| `cluster:tgs` | SET | TG numbers as decimal strings |
| `trunk:<section>:peer` | HASH | `{ host, port, secret, remote_prefix, peer_id }` — runtime-addable trunk peer definition |
| `trunk:<section>:blacklist` | SET | TG patterns: exact (`666`), prefix (`24*`), range (`100-199`) |
| `trunk:<section>:allow` | SET | Same syntax as blacklist |
| `trunk:<section>:tgmap` | HASH | `{ peer_tg: local_tg }` decimal string pairs |
`<section>` is the `[TRUNK_x]` section name from `svxreflector.conf` (e.g.
`TRUNK_1_2`).
The `enabled` field in `user:*` is `"1"` (allowed) or `"0"` (blocked). A
missing `enabled` field is treated as enabled. A user whose group does not have
a matching `group:*` key cannot authenticate; a warning is logged at reload.
### Live-state keys (reflector writes, dashboard reads)
| Key | Redis type | Contents |
|-----|-----------|----------|
| `live:talker:<tg>` | HASH | `{ callsign, started_at, source }` |
| `live:client:<callsign>` | HASH | `{ connected_at, ip, codecs, tg }` |
| `live:trunk:<section>` | HASH | `{ state, last_hb, peer_id }` |
All `live:*` keys carry a 60-second TTL, refreshed every ~30 s by a heartbeat
timer. If the reflector exits uncleanly, stale entries expire automatically
within 60 s.
`source` in `live:talker` is `"local"` for a directly connected client or
`"trunk"` for a remote talker received via trunk.
---
## Pub/sub channels
Two channels are used. Neither carries deltas — the reflector always re-reads
the full scope from Redis on receipt.
| Channel | Direction | Payload |
|---------|-----------|---------|
| `config.changed` | dashboard → reflector | scope token (see table below) |
| `live.changed` | reflector → dashboard | same scope tokens (optional) |
### Scope tokens
| Token | Reflector action |
|-------|-----------------|
| `users` | Re-scan `user:*` and `group:*`, rebuild the auth map |
| `cluster` | Re-read `cluster:tgs`, update the in-memory cluster TG set |
| `trunk:<section>` | Call `reloadConfig()` for that trunk link |
| `all` | All of the above (escape hatch; also sent automatically on Redis reconnect) |
Every write to a configuration key must be followed by a `PUBLISH` to
`config.changed` for the change to take effect immediately. Without the
publish, the reflector picks up the change only at the next scheduled reload
(or never, if there is no scheduled reload configured).
---
## Dashboard operations — cookbook
All examples use plain `redis-cli`. Substitute `redis-cli -p <port> -a <pass>`
as needed. If `KEY_PREFIX=refl1`, prepend `refl1:` to every key.
### Users
**Add a user:**
```bash
redis-cli HSET user:SM0ABC group operators enabled 1
redis-cli PUBLISH config.changed users
```
**Disable a user (reject logins, keep record):**
```bash
redis-cli HSET user:SM0ABC enabled 0
redis-cli PUBLISH config.changed users
```
**Re-enable:**
```bash
redis-cli HSET user:SM0ABC enabled 1
redis-cli PUBLISH config.changed users
```
**Delete a user:**
```bash
redis-cli DEL user:SM0ABC
redis-cli PUBLISH config.changed users
```
**List all users and their group:**
```bash
redis-cli --scan --pattern 'user:*' | while read k; do
echo -n "$k "; redis-cli HGETALL "$k"
done
```
### Password groups
**Create a group / change password:**
```bash
redis-cli HSET group:operators password "a strong passphrase"
redis-cli PUBLISH config.changed users
```
**Move a user to a different group:**
```bash
redis-cli HSET user:SM0ABC group admins
redis-cli PUBLISH config.changed users
```
**List groups:**
```bash
redis-cli --scan --pattern 'group:*'
```
### Cluster TGs
**Add a cluster TG:**
```bash
redis-cli SADD cluster:tgs 222
redis-cli PUBLISH config.changed cluster
```
**Remove a cluster TG:**
```bash
redis-cli SREM cluster:tgs 222
redis-cli PUBLISH config.changed cluster
```
**List current cluster TGs:**
```bash
redis-cli SMEMBERS cluster:tgs
```
### Per-trunk filters
Replace `TRUNK_1_2` with your actual `[TRUNK_x]` section name.
**Blacklist a TG (never carry in either direction):**
```bash
redis-cli SADD trunk:TRUNK_1_2:blacklist 666
redis-cli PUBLISH config.changed trunk:TRUNK_1_2
```
**Remove from blacklist:**
```bash
redis-cli SREM trunk:TRUNK_1_2:blacklist 666
redis-cli PUBLISH config.changed trunk:TRUNK_1_2
```
**Set an allow-list (only these TGs exchanged on this link):**
```bash
redis-cli SADD trunk:TRUNK_1_2:allow "24*"
redis-cli SADD trunk:TRUNK_1_2:allow 2624123
redis-cli PUBLISH config.changed trunk:TRUNK_1_2
```
**Remove from allow-list:**
```bash
redis-cli SREM trunk:TRUNK_1_2:allow "24*"
redis-cli PUBLISH config.changed trunk:TRUNK_1_2
```
**Add a TG map entry (peer TG 1 → local TG 2624123):**
```bash
redis-cli HSET trunk:TRUNK_1_2:tgmap 1 2624123
redis-cli PUBLISH config.changed trunk:TRUNK_1_2
```
**Remove a TG map entry:**
```bash
redis-cli HDEL trunk:TRUNK_1_2:tgmap 1
redis-cli PUBLISH config.changed trunk:TRUNK_1_2
```
**View current filters for a trunk:**
```bash
redis-cli SMEMBERS trunk:TRUNK_1_2:blacklist
redis-cli SMEMBERS trunk:TRUNK_1_2:allow
redis-cli HGETALL trunk:TRUNK_1_2:tgmap
```
### Add a trunk peer at runtime
```bash
redis-cli HSET trunk:TRUNK_AB:peer \
host reflector-b.example.com \
port 5302 \
secret shared_trunk_secret \
remote_prefix 2 \
peer_id my-peer-id
redis-cli PUBLISH config.changed trunk:TRUNK_AB
```
The reflector creates a new `TrunkLink` and starts the outbound handshake.
Fields:
- `host` (required)
- `port` (optional, default `5302`)
- `secret` (required) — the pre-shared trunk secret, identical on both ends
- `remote_prefix` (required) — comma-separated TG prefix(es) owned by the peer
- `peer_id` (optional, default: section name)
### Remove a trunk peer at runtime
```bash
redis-cli DEL trunk:TRUNK_AB:peer
redis-cli PUBLISH config.changed trunk:TRUNK_AB
```
The reflector tears down the TrunkLink cleanly, clearing any trunk
talker state it held. Only Redis-managed trunks can be removed this
way; peers defined statically in svxreflector.conf survive.
### Mute management (not in Redis)
Mutes are managed via the reflector's command PTY (`/dev/shm/reflector_ctrl`),
not through Redis. A dashboard issues mute commands by writing directly to
the PTY (e.g., `TRUNK MUTE TRUNK_1_2 ON4ABC`). Current mute state is exposed
in the `/status` JSON under each trunk's `muted` array — poll that endpoint
from the dashboard UI if you need to display current mute state.
---
## Live state
The reflector pushes live-state updates to Redis on every significant event:
talker start/stop, client connect/disconnect, trunk state change.
Updates are **not** written directly on the audio code path. Instead, each
event pushes a small command record onto a bounded in-memory FIFO
(`RedisLiveQueue`). A drain timer on the main event loop (every ~50–100 ms)
pops the queue and pipelines the resulting `HSET`/`DEL`/`EXPIRE` calls via
the async hiredis context. This keeps the audio path latency-free even when
Redis is slow or momentarily stalled.
After each drain cycle, the reflector publishes `live.changed <scope>` once
per changed scope if anything was written. Dashboards may subscribe to
`live.changed` for push notifications, or may simply poll `live:*` keys on a
timer.
**If the queue fills** (default capacity: 1 000 entries), the oldest entry is
dropped and a counter (`dropped_live_writes`) is incremented. This metric is
visible in the `/status` JSON (see [Monitoring](#monitoring)).
**On Redis outage:** new live-state events continue to queue in memory up to
the capacity limit, then are dropped. The reflector keeps running and carries
audio normally. See [Failure modes](#failure-modes).
---
## Migration
To import existing `.conf` credentials and settings into Redis, run:
```bash
svxreflector --import-conf-to-redis --config /etc/svxlink/svxreflector.conf
```
Add `--dry-run` to print the Redis commands that would be issued without
contacting Redis:
```bash
svxreflector --import-conf-to-redis --dry-run --config /etc/svxlink/svxreflector.conf
```
**What is imported:**
| `.conf` source | Redis destination |
|---------------|------------------|
| `[USERS]` entries | `user:<callsign>` hashes |
| `[PASSWORDS]` entries | `group:<name>` hashes |
| `CLUSTER_TGS` | `cluster:tgs` set |
| `BLACKLIST_TGS` per `[TRUNK_x]` | `trunk:<section>:blacklist` sets |
| `ALLOW_TGS` per `[TRUNK_x]` | `trunk:<section>:allow` sets |
| `TG_MAP` per `[TRUNK_x]` | `trunk:<section>:tgmap` hashes |
**What is NOT imported:** bootstrap settings (`HOST`, `PORT`, `SECRET`,
`REMOTE_PREFIX`, `LOCAL_PREFIX`, certificate sections, `[SATELLITE]`,
`[MQTT]`, `[REDIS]`). These remain in `.conf`.
The importer is idempotent: it uses `HSET` and `SADD`, not `SETNX`. Running
it twice produces the same result. Re-running after adding new `.conf` entries
will add them without removing existing Redis-only records.
After the import succeeds, remove (or leave in place — they will be ignored)
the `[USERS]`, `[PASSWORDS]`, and `CLUSTER_TGS` entries from `.conf`.
---
## Static vs Redis-managed trunks
Trunk peers defined in `svxreflector.conf` as `[TRUNK_*]` sections are
treated as immutable at runtime — a `config.changed trunk:<section>`
event with no matching Redis peer hash is treated as a filter-reload
only (the existing behavior), never as a remove. Only trunks that were
added from Redis hashes can be dynamically destroyed.
---
## Failure modes
| Condition | Behavior |
|-----------|----------|
| `[REDIS]` configured, Redis unreachable at startup | Log error, exit non-zero. No silent fallback to `.conf`. |
| Mid-flight Redis disconnect | Keep running on last-known in-memory config. Async context reconnects with exponential backoff (1 s → 30 s cap). On reconnect: re-subscribe to `config.changed`, trigger an internal `all` reload. |
| Bad pub/sub payload | Log and continue. The handler never propagates exceptions. |
| Live-state queue full | Drop oldest entry, increment `dropped_live_writes`, log once per minute. Audio is unaffected. |
| Dangling group reference (`user.group` → missing `group:*`) | User cannot authenticate. Warning logged at reload time. |
**Mid-flight outage summary:** the reflector continues to serve clients and
carry audio using the configuration snapshot taken at the last successful
Redis sync. New `config.changed` events during the outage are silently missed
(pub/sub is not buffered). On reconnect the internal `all` reload re-reads the
full current state, picking up any changes made while the connection was down.
---
## Monitoring
The `/status` JSON endpoint (enabled via `HTTP_SRV_PORT` in `[GLOBAL]`)
includes a `redis` object when `[REDIS]` is configured:
```json
{
"nodes": { ... },
"trunks": { ... },
"redis": {
"live_queue_size": 3,
"dropped_live_writes": 0
}
}
```
| Field | Description |
|-------|-------------|
| `live_queue_size` | Current number of pending live-state writes in the drain queue |
| `dropped_live_writes` | Cumulative count of live-state writes dropped due to queue overflow |
A non-zero `dropped_live_writes` indicates the drain timer is falling behind.
Possible causes: Redis latency spike, very high event rate, or a queue
capacity that is too small for the load. The audio path is never affected.
---
## Minimal working example
The following transcript sets up one user, adds a cluster TG, and confirms
live state. Assumes the reflector is running with `[REDIS]` pointing at
`127.0.0.1:6379`, no `KEY_PREFIX`, and at least one trunk section named
`TRUNK_1_2`.
```bash
# 1. Create a password group and a user
redis-cli HSET group:admins password "s3cur3p@ss"
redis-cli HSET user:ON4ABC group admins enabled 1
redis-cli PUBLISH config.changed users
# → (integer) 1
# 2. Verify the user can now authenticate
# (connect a SvxLink node as ON4ABC with password "s3cur3p@ss" — it should succeed)
# 3. Add a cluster TG
redis-cli SADD cluster:tgs 9990
redis-cli PUBLISH config.changed cluster
# → (integer) 1
# 4. Start a transmission on TG 9990 from any connected node, then check
# live state (within ~100 ms of TX start):
redis-cli HGETALL live:talker:9990
# 1) "callsign"
# 2) "SM0XYZ"
# 3) "started_at"
# 4) "1713200000"
# 5) "source"
# 6) "local"
# 5. Check /status for Redis metrics
curl -s http://localhost:8080/status | python3 -m json.tool | grep -A4 '"redis"'
# "redis": {
# "live_queue_size": 0,
# "dropped_live_writes": 0
# }
```
+7 -1
View File
@@ -24,13 +24,19 @@ pkg_check_modules(MOSQUITTO REQUIRED libmosquitto)
include_directories(${MOSQUITTO_INCLUDE_DIRS}) include_directories(${MOSQUITTO_INCLUDE_DIRS})
set(LIBS ${LIBS} ${MOSQUITTO_LIBRARIES}) set(LIBS ${LIBS} ${MOSQUITTO_LIBRARIES})
# Find hiredis library (Redis C client)
pkg_check_modules(HIREDIS REQUIRED hiredis)
include_directories(${HIREDIS_INCLUDE_DIRS})
set(LIBS ${LIBS} ${HIREDIS_LIBRARIES})
# Add project libraries # Add project libraries
set(LIBS asynccpp asyncaudio asynccore svxmisc ${LIBS}) set(LIBS asynccpp asyncaudio asynccore svxmisc ${LIBS})
# Build the executable # Build the executable
add_executable(svxreflector add_executable(svxreflector
svxreflector.cpp Reflector.cpp ReflectorClient.cpp TGHandler.cpp TrunkLink.cpp svxreflector.cpp Reflector.cpp ReflectorClient.cpp TGHandler.cpp TrunkLink.cpp
SatelliteLink.cpp SatelliteClient.cpp MqttPublisher.cpp SatelliteLink.cpp SatelliteClient.cpp MqttPublisher.cpp RedisStore.cpp
RedisAsyncAdapter.cpp RedisLiveQueue.cpp
) )
target_link_libraries(svxreflector ${LIBS}) target_link_libraries(svxreflector ${LIBS})
set_target_properties(svxreflector PROPERTIES set_target_properties(svxreflector PROPERTIES
@@ -0,0 +1,60 @@
#include "RedisAsyncAdapter.h"
#include <hiredis/hiredis.h>
#include <hiredis/async.h>
#include <AsyncFdWatch.h>
namespace {
struct AdapterData
{
redisAsyncContext* ac;
Async::FdWatch* rd = nullptr;
Async::FdWatch* wr = nullptr;
};
void adapterAddRead(void* priv) {
auto* d = static_cast<AdapterData*>(priv);
if (d->rd) d->rd->setEnabled(true);
}
void adapterDelRead(void* priv) {
auto* d = static_cast<AdapterData*>(priv);
if (d->rd) d->rd->setEnabled(false);
}
void adapterAddWrite(void* priv) {
auto* d = static_cast<AdapterData*>(priv);
if (d->wr) d->wr->setEnabled(true);
}
void adapterDelWrite(void* priv) {
auto* d = static_cast<AdapterData*>(priv);
if (d->wr) d->wr->setEnabled(false);
}
void adapterCleanup(void* priv) {
auto* d = static_cast<AdapterData*>(priv);
delete d->rd;
delete d->wr;
delete d;
}
} // namespace
bool RedisAsyncAdapter::attach(redisAsyncContext* ac) {
if (!ac || ac->ev.data != nullptr) return false;
auto* d = new AdapterData;
d->ac = ac;
int fd = ac->c.fd;
d->rd = new Async::FdWatch(fd, Async::FdWatch::FD_WATCH_RD);
d->wr = new Async::FdWatch(fd, Async::FdWatch::FD_WATCH_WR);
d->rd->setEnabled(false);
d->wr->setEnabled(false);
d->rd->activity.connect(
[ac](Async::FdWatch*){ redisAsyncHandleRead(ac); });
d->wr->activity.connect(
[ac](Async::FdWatch*){ redisAsyncHandleWrite(ac); });
ac->ev.data = d;
ac->ev.addRead = adapterAddRead;
ac->ev.delRead = adapterDelRead;
ac->ev.addWrite = adapterAddWrite;
ac->ev.delWrite = adapterDelWrite;
ac->ev.cleanup = adapterCleanup;
return true;
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef REDIS_ASYNC_ADAPTER_INCLUDED
#define REDIS_ASYNC_ADAPTER_INCLUDED
struct redisAsyncContext;
class RedisAsyncAdapter
{
public:
// Attach hiredis async callbacks to the Async event loop via FdWatch.
// Returns false if the context is already attached or invalid.
// The adapter cleans itself up when hiredis invokes ev.cleanup
// (on disconnect/free).
static bool attach(redisAsyncContext* ac);
};
#endif /* REDIS_ASYNC_ADAPTER_INCLUDED */
+22
View File
@@ -0,0 +1,22 @@
#include "RedisLiveQueue.h"
RedisLiveQueue::RedisLiveQueue(size_t max_pending) : m_max(max_pending) {}
bool RedisLiveQueue::push(Op op) {
if (m_q.size() >= m_max) {
m_q.pop_front();
++m_dropped;
}
m_q.push_back(std::move(op));
return true;
}
size_t RedisLiveQueue::drain(std::vector<Op>& out) {
size_t n = m_q.size();
out.reserve(out.size() + n);
while (!m_q.empty()) {
out.push_back(std::move(m_q.front()));
m_q.pop_front();
}
return n;
}
+40
View File
@@ -0,0 +1,40 @@
#ifndef REDIS_LIVE_QUEUE_INCLUDED
#define REDIS_LIVE_QUEUE_INCLUDED
#include <string>
#include <vector>
#include <deque>
#include <cstdint>
#include <cstddef>
class RedisLiveQueue
{
public:
enum class OpType { HSET, DEL, EXPIRE };
struct Op {
OpType op;
std::string key;
std::vector<std::pair<std::string, std::string>> fields; // HSET
int ttl_s = 0; // EXPIRE
};
explicit RedisLiveQueue(size_t max_pending = 4096);
// Push. On overflow, drops the oldest entry and increments the
// dropped counter. Always returns true (push never fails).
bool push(Op op);
// Drain everything currently queued into `out`. Returns count moved.
size_t drain(std::vector<Op>& out);
uint64_t droppedCount(void) const { return m_dropped; }
size_t size(void) const { return m_q.size(); }
private:
std::deque<Op> m_q;
size_t m_max;
uint64_t m_dropped = 0;
};
#endif /* REDIS_LIVE_QUEUE_INCLUDED */
+512
View File
@@ -0,0 +1,512 @@
#include "RedisStore.h"
#include <hiredis/hiredis.h>
#include <hiredis/async.h>
#include "RedisAsyncAdapter.h"
#include <AsyncTimer.h>
#include "RedisLiveQueue.h"
#include <iostream>
#include <ctime>
namespace {
void onPubSubMessageThunk(redisAsyncContext* /*ac*/, void* reply, void* priv) {
auto* self = static_cast<RedisStore*>(priv);
auto* r = static_cast<redisReply*>(reply);
if (!r || r->type != REDIS_REPLY_ARRAY || r->elements < 3) return;
if (r->element[0]->type == REDIS_REPLY_STRING &&
std::string(r->element[0]->str, r->element[0]->len) == "message") {
std::string payload(r->element[2]->str, r->element[2]->len);
self->configChanged.emit(payload);
}
}
void onAsyncDisconnectThunk(const redisAsyncContext* ac, int status) {
auto* self = static_cast<RedisStore*>(ac->data);
if (self) self->onAsyncDisconnect(status);
}
void onAsyncWriteDisconnectThunk(const redisAsyncContext* ac, int status) {
auto* self = static_cast<RedisStore*>(ac->data);
if (self) self->onAsyncWriteDisconnect(status);
}
} // namespace
RedisStore::RedisStore(const Config& cfg) : m_cfg(cfg) {}
RedisStore::~RedisStore() {
m_shutting_down = true;
delete m_reconnect_timer; m_reconnect_timer = nullptr;
delete m_heartbeat_timer; m_heartbeat_timer = nullptr;
delete m_drain_timer; m_drain_timer = nullptr;
delete m_live_queue; m_live_queue = nullptr;
if (m_async_write) { redisAsyncFree(m_async_write); m_async_write = nullptr; }
if (m_async) { redisAsyncFree(m_async); m_async = nullptr; }
if (m_sync) { redisFree(m_sync); m_sync = nullptr; }
}
bool RedisStore::connectSync(void) {
struct timeval tv = { 5, 0 };
if (!m_cfg.unix_socket.empty()) {
m_sync = redisConnectUnixWithTimeout(m_cfg.unix_socket.c_str(), tv);
} else {
m_sync = redisConnectWithTimeout(m_cfg.host.c_str(), m_cfg.port, tv);
}
if (!m_sync || m_sync->err) {
std::cerr << "*** ERROR: Redis sync connect failed: "
<< (m_sync ? m_sync->errstr : "alloc failed") << std::endl;
if (m_sync) { redisFree(m_sync); m_sync = nullptr; }
return false;
}
if (!m_cfg.password.empty()) {
redisReply* r = (redisReply*)redisCommand(m_sync, "AUTH %s", m_cfg.password.c_str());
if (!r || r->type == REDIS_REPLY_ERROR) {
std::cerr << "*** ERROR: Redis AUTH failed" << std::endl;
if (r) freeReplyObject(r);
redisFree(m_sync); m_sync = nullptr;
return false;
}
freeReplyObject(r);
}
if (m_cfg.db != 0) {
redisReply* r = (redisReply*)redisCommand(m_sync, "SELECT %d", m_cfg.db);
if (!r || r->type == REDIS_REPLY_ERROR) {
std::cerr << "*** ERROR: Redis SELECT failed" << std::endl;
if (r) freeReplyObject(r);
redisFree(m_sync); m_sync = nullptr;
return false;
}
freeReplyObject(r);
}
return true;
}
bool RedisStore::connect(void) {
if (!connectSync()) return false;
if (!connectAsync()) return false;
subscribe();
if (!connectAsyncWrite()) return false;
m_live_queue = new RedisLiveQueue(4096);
m_drain_timer = new Async::Timer(75, Async::Timer::TYPE_PERIODIC);
m_drain_timer->expired.connect(
sigc::mem_fun(*this, &RedisStore::drainLiveQueue));
m_heartbeat_timer = new Async::Timer(30000, Async::Timer::TYPE_PERIODIC);
m_heartbeat_timer->expired.connect(
sigc::mem_fun(*this, &RedisStore::refreshLiveExpire));
std::cout << "RedisStore: connected sync+async, subscribed to "
<< channelName() << std::endl;
return true;
}
bool RedisStore::isReady(void) const { return m_sync != nullptr; }
std::string RedisStore::lookupUserKey(const std::string& callsign) {
if (!m_sync) return "";
std::string user_key = keyFor("user:" + callsign);
redisReply* r = (redisReply*)redisCommand(m_sync,
"HMGET %s group enabled", user_key.c_str());
if (!r || r->type != REDIS_REPLY_ARRAY || r->elements != 2) {
if (r) freeReplyObject(r);
return "";
}
if (r->element[0]->type != REDIS_REPLY_STRING) {
freeReplyObject(r);
return "";
}
std::string group(r->element[0]->str, r->element[0]->len);
bool enabled = true;
if (r->element[1]->type == REDIS_REPLY_STRING) {
enabled = std::string(r->element[1]->str, r->element[1]->len) != "0";
}
freeReplyObject(r);
if (!enabled) {
std::cout << "RedisStore: user " << callsign << " disabled" << std::endl;
return "";
}
std::string group_key = keyFor("group:" + group);
r = (redisReply*)redisCommand(m_sync, "HGET %s password", group_key.c_str());
if (!r || r->type != REDIS_REPLY_STRING) {
if (r) freeReplyObject(r);
std::cout << "*** WARNING: group " << group << " missing password" << std::endl;
return "";
}
std::string pw(r->str, r->len);
freeReplyObject(r);
return pw;
}
std::map<std::string, std::string> RedisStore::loadAllUsers(void) { return {}; }
bool RedisStore::isUserEnabled(const std::string&) { return true; }
std::set<uint32_t> RedisStore::loadClusterTgs(void) {
std::set<uint32_t> out;
if (!m_sync) return out;
std::string k = keyFor("cluster:tgs");
redisReply* r = (redisReply*)redisCommand(m_sync, "SMEMBERS %s", k.c_str());
if (r && r->type == REDIS_REPLY_ARRAY) {
for (size_t i = 0; i < r->elements; ++i) {
if (r->element[i]->type == REDIS_REPLY_STRING) {
try { out.insert(std::stoul(std::string(r->element[i]->str, r->element[i]->len))); }
catch (...) {}
}
}
}
if (r) freeReplyObject(r);
return out;
}
std::string RedisStore::loadTrunkFilter(const std::string& section,
const std::string& field) {
if (!m_sync) return "";
std::string k = keyFor("trunk:" + section + ":" + field);
redisReply* r = (redisReply*)redisCommand(m_sync, "SMEMBERS %s", k.c_str());
std::string out;
if (r && r->type == REDIS_REPLY_ARRAY) {
for (size_t i = 0; i < r->elements; ++i) {
if (r->element[i]->type == REDIS_REPLY_STRING) {
if (!out.empty()) out += ",";
out.append(r->element[i]->str, r->element[i]->len);
}
}
}
if (r) freeReplyObject(r);
return out;
}
std::map<uint32_t, uint32_t> RedisStore::loadTrunkTgMap(const std::string& section) {
std::map<uint32_t, uint32_t> out;
if (!m_sync) return out;
std::string k = keyFor("trunk:" + section + ":tgmap");
redisReply* r = (redisReply*)redisCommand(m_sync, "HGETALL %s", k.c_str());
if (r && r->type == REDIS_REPLY_ARRAY) {
for (size_t i = 0; i + 1 < r->elements; i += 2) {
try {
uint32_t peer = std::stoul(std::string(r->element[i]->str, r->element[i]->len));
uint32_t local = std::stoul(std::string(r->element[i+1]->str, r->element[i+1]->len));
out[peer] = local;
} catch (...) {}
}
}
if (r) freeReplyObject(r);
return out;
}
std::map<std::string, RedisStore::TrunkPeerConfig>
RedisStore::loadTrunkPeers(void)
{
std::map<std::string, TrunkPeerConfig> out;
if (!m_sync) return out;
std::string pattern = keyFor("trunk:*:peer");
redisReply* r = (redisReply*)redisCommand(m_sync, "KEYS %s", pattern.c_str());
if (!r || r->type != REDIS_REPLY_ARRAY) {
if (r) freeReplyObject(r);
return out;
}
std::vector<std::string> matched_keys;
for (size_t i = 0; i < r->elements; ++i) {
if (r->element[i]->type == REDIS_REPLY_STRING) {
matched_keys.emplace_back(r->element[i]->str, r->element[i]->len);
}
}
freeReplyObject(r);
// Extract section name: strip "<keyprefix>:trunk:" prefix and ":peer" suffix.
std::string left = keyFor("trunk:");
const std::string right = ":peer";
for (const std::string& key : matched_keys) {
if (key.size() < left.size() + right.size()) continue;
if (key.substr(0, left.size()) != left) continue;
if (key.substr(key.size() - right.size()) != right) continue;
std::string section = key.substr(left.size(),
key.size() - left.size() - right.size());
if (section.empty()) continue;
redisReply* h = (redisReply*)redisCommand(m_sync, "HGETALL %s", key.c_str());
if (!h || h->type != REDIS_REPLY_ARRAY) {
if (h) freeReplyObject(h);
continue;
}
TrunkPeerConfig cfg;
for (size_t i = 0; i + 1 < h->elements; i += 2) {
std::string field(h->element[i]->str, h->element[i]->len);
std::string value(h->element[i+1]->str, h->element[i+1]->len);
if (field == "host") cfg.host = value;
else if (field == "port") cfg.port = value;
else if (field == "secret") cfg.secret = value;
else if (field == "remote_prefix") cfg.remote_prefix = value;
else if (field == "peer_id") cfg.peer_id = value;
}
freeReplyObject(h);
// Require host + secret + remote_prefix
if (cfg.host.empty() || cfg.secret.empty() || cfg.remote_prefix.empty()) {
std::cerr << "*** WARN: RedisStore: trunk peer " << section
<< " missing required fields (host/secret/remote_prefix); "
<< "skipping" << std::endl;
continue;
}
out[section] = std::move(cfg);
}
return out;
}
void RedisStore::publishConfigChanged(const std::string& scope) {
if (!m_sync) return;
std::string ch = channelName();
redisReply* r = (redisReply*)redisCommand(m_sync, "PUBLISH %s %s",
ch.c_str(), scope.c_str());
if (r) freeReplyObject(r);
}
void RedisStore::pushLiveTalker(uint32_t tg, const std::string& callsign,
const std::string& source) {
if (!m_live_queue) return;
RedisLiveQueue::Op op;
op.op = RedisLiveQueue::OpType::HSET;
op.key = keyFor("live:talker:" + std::to_string(tg));
m_live_keys.insert(op.key);
op.fields = {
{"callsign", callsign},
{"started_at", std::to_string(std::time(nullptr))},
{"source", source}
};
op.ttl_s = 60;
m_live_queue->push(std::move(op));
}
void RedisStore::clearLiveTalker(uint32_t tg) {
if (!m_live_queue) return;
RedisLiveQueue::Op op;
op.op = RedisLiveQueue::OpType::DEL;
op.key = keyFor("live:talker:" + std::to_string(tg));
m_live_keys.erase(op.key);
m_live_queue->push(std::move(op));
}
void RedisStore::pushLiveClient(const std::string& callsign,
const std::string& ip,
const std::string& codecs,
uint32_t current_tg) {
if (!m_live_queue) return;
RedisLiveQueue::Op op;
op.op = RedisLiveQueue::OpType::HSET;
op.key = keyFor("live:client:" + callsign);
m_live_keys.insert(op.key);
op.fields = {
{"connected_at", std::to_string(std::time(nullptr))},
{"ip", ip},
{"codecs", codecs},
{"tg", std::to_string(current_tg)}
};
op.ttl_s = 60;
m_live_queue->push(std::move(op));
}
void RedisStore::clearLiveClient(const std::string& callsign) {
if (!m_live_queue) return;
RedisLiveQueue::Op op;
op.op = RedisLiveQueue::OpType::DEL;
op.key = keyFor("live:client:" + callsign);
m_live_keys.erase(op.key);
m_live_queue->push(std::move(op));
}
void RedisStore::pushLiveTrunk(const std::string& section,
const std::string& state,
const std::string& peer_id) {
if (!m_live_queue) return;
RedisLiveQueue::Op op;
op.op = RedisLiveQueue::OpType::HSET;
op.key = keyFor("live:trunk:" + section);
m_live_keys.insert(op.key);
op.fields = {
{"state", state},
{"peer_id", peer_id},
{"last_hb", std::to_string(std::time(nullptr))}
};
op.ttl_s = 60;
m_live_queue->push(std::move(op));
}
size_t RedisStore::liveQueueSize(void) const {
return m_live_queue ? m_live_queue->size() : 0;
}
bool RedisStore::connectAsync(void) {
if (!m_cfg.unix_socket.empty()) {
m_async = redisAsyncConnectUnix(m_cfg.unix_socket.c_str());
} else {
m_async = redisAsyncConnect(m_cfg.host.c_str(), m_cfg.port);
}
if (!m_async || m_async->err) {
std::cerr << "*** ERROR: Redis async connect failed: "
<< (m_async ? m_async->errstr : "alloc failed") << std::endl;
if (m_async) { redisAsyncFree(m_async); m_async = nullptr; }
return false;
}
m_async->data = this;
if (!RedisAsyncAdapter::attach(m_async)) {
redisAsyncFree(m_async); m_async = nullptr;
return false;
}
redisAsyncSetDisconnectCallback(m_async, onAsyncDisconnectThunk);
if (!m_cfg.password.empty()) {
redisAsyncCommand(m_async, nullptr, nullptr, "AUTH %s", m_cfg.password.c_str());
}
if (m_cfg.db != 0) {
redisAsyncCommand(m_async, nullptr, nullptr, "SELECT %d", m_cfg.db);
}
return true;
}
bool RedisStore::connectAsyncWrite(void) {
if (!m_cfg.unix_socket.empty()) {
m_async_write = redisAsyncConnectUnix(m_cfg.unix_socket.c_str());
} else {
m_async_write = redisAsyncConnect(m_cfg.host.c_str(), m_cfg.port);
}
if (!m_async_write || m_async_write->err) {
std::cerr << "*** ERROR: Redis async-write connect failed: "
<< (m_async_write ? m_async_write->errstr : "alloc failed")
<< std::endl;
if (m_async_write) { redisAsyncFree(m_async_write); m_async_write = nullptr; }
return false;
}
m_async_write->data = this;
if (!RedisAsyncAdapter::attach(m_async_write)) {
redisAsyncFree(m_async_write); m_async_write = nullptr;
return false;
}
redisAsyncSetDisconnectCallback(m_async_write, onAsyncWriteDisconnectThunk);
if (!m_cfg.password.empty()) {
redisAsyncCommand(m_async_write, nullptr, nullptr, "AUTH %s", m_cfg.password.c_str());
}
if (m_cfg.db != 0) {
redisAsyncCommand(m_async_write, nullptr, nullptr, "SELECT %d", m_cfg.db);
}
return true;
}
void RedisStore::subscribe(void) {
if (!m_async) return;
std::string ch = channelName();
redisAsyncCommand(m_async, onPubSubMessageThunk, this,
"SUBSCRIBE %s", ch.c_str());
}
void RedisStore::onAsyncDisconnect(int /*status*/) {
if (m_shutting_down) return;
std::cerr << "*** WARN: Redis async disconnect" << std::endl;
// hiredis will free the context after this returns — just null out.
m_async = nullptr;
scheduleReconnect();
}
void RedisStore::onAsyncWriteDisconnect(int /*status*/) {
if (m_shutting_down) return;
std::cerr << "*** WARN: Redis async-write disconnect" << std::endl;
m_async_write = nullptr;
scheduleReconnect();
}
void RedisStore::scheduleReconnect(void) {
if (m_shutting_down) return;
delete m_reconnect_timer;
m_reconnect_timer = new Async::Timer(m_reconnect_backoff_s * 1000,
Async::Timer::TYPE_ONESHOT);
m_reconnect_timer->expired.connect([this](Async::Timer*) {
if (m_shutting_down) return;
// Reconnect sub context if needed.
if (!m_async && !connectAsync()) {
m_reconnect_backoff_s = std::min(m_reconnect_backoff_s * 2, 30);
scheduleReconnect();
return;
}
if (!m_async_write && !connectAsyncWrite()) {
m_reconnect_backoff_s = std::min(m_reconnect_backoff_s * 2, 30);
scheduleReconnect();
return;
}
// If sub was freshly reconnected, re-subscribe.
subscribe();
// Rebuild sync context too — its TCP socket is likely dead.
if (m_sync) { redisFree(m_sync); m_sync = nullptr; }
if (!connectSync()) {
std::cerr << "*** WARN: Redis sync reconnect failed" << std::endl;
// async is up but sync isn't — schedule another retry so we fix sync.
m_reconnect_backoff_s = std::min(m_reconnect_backoff_s * 2, 30);
scheduleReconnect();
return;
}
std::cout << "RedisStore: reconnected, re-subscribing and requesting "
"full reload" << std::endl;
m_reconnect_backoff_s = 1;
configChanged.emit("all");
});
}
void RedisStore::onPubSubMessage(const std::string&, const std::string&) {}
void RedisStore::drainLiveQueue(Async::Timer*) {
if (!m_async_write || !m_live_queue) return;
std::vector<RedisLiveQueue::Op> ops;
m_live_queue->drain(ops);
if (ops.empty()) return;
for (auto& op : ops) {
switch (op.op) {
case RedisLiveQueue::OpType::HSET: {
std::vector<const char*> argv;
std::vector<size_t> argl;
argv.push_back("HSET"); argl.push_back(4);
argv.push_back(op.key.c_str()); argl.push_back(op.key.size());
for (auto& kv : op.fields) {
argv.push_back(kv.first.c_str()); argl.push_back(kv.first.size());
argv.push_back(kv.second.c_str()); argl.push_back(kv.second.size());
}
redisAsyncCommandArgv(m_async_write, nullptr, nullptr,
static_cast<int>(argv.size()),
argv.data(), argl.data());
if (op.ttl_s > 0) {
redisAsyncCommand(m_async_write, nullptr, nullptr,
"EXPIRE %s %d", op.key.c_str(), op.ttl_s);
}
break;
}
case RedisLiveQueue::OpType::DEL:
redisAsyncCommand(m_async_write, nullptr, nullptr,
"DEL %s", op.key.c_str());
break;
case RedisLiveQueue::OpType::EXPIRE:
redisAsyncCommand(m_async_write, nullptr, nullptr,
"EXPIRE %s %d", op.key.c_str(), op.ttl_s);
break;
}
}
// Notify dashboards once per drain cycle.
std::string ch = keyFor("live.changed");
redisAsyncCommand(m_async_write, nullptr, nullptr,
"PUBLISH %s tick", ch.c_str());
}
void RedisStore::refreshLiveExpire(Async::Timer*) {
if (!m_live_queue) return;
for (const std::string& k : m_live_keys) {
RedisLiveQueue::Op op;
op.op = RedisLiveQueue::OpType::EXPIRE;
op.key = k;
op.ttl_s = 60;
m_live_queue->push(std::move(op));
}
}
std::string RedisStore::keyFor(const std::string& suffix) const {
if (m_cfg.key_prefix.empty()) return suffix;
return m_cfg.key_prefix + ":" + suffix;
}
std::string RedisStore::channelName(void) const {
return keyFor("config.changed");
}
+119
View File
@@ -0,0 +1,119 @@
#ifndef REDIS_STORE_INCLUDED
#define REDIS_STORE_INCLUDED
#include <sigc++/sigc++.h>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <cstdint>
struct redisContext;
struct redisAsyncContext;
namespace Async { class Config; class Timer; }
class RedisAsyncAdapter;
class RedisLiveQueue;
class RedisStore : public sigc::trackable
{
public:
struct Config
{
std::string host;
uint16_t port = 6379;
std::string password;
int db = 0;
std::string key_prefix;
std::string unix_socket;
bool tls_enabled = false;
std::string tls_ca_cert;
std::string tls_client_cert;
std::string tls_client_key;
};
struct TrunkPeerConfig
{
std::string host;
std::string port;
std::string secret;
std::string remote_prefix;
std::string peer_id;
};
explicit RedisStore(const Config& cfg);
~RedisStore();
// Synchronous startup connect. Returns false on failure (caller exits).
bool connect(void);
bool isReady(void) const;
// Emitted when a config.changed message arrives from Redis. The
// string payload identifies the scope: "users", "cluster",
// "trunk:<section>", or "all".
sigc::signal<void, std::string> configChanged;
// Schema accessors (sync). Empty results on Redis errors are logged
// and treated as "no entries".
std::string lookupUserKey(const std::string& callsign);
std::map<std::string, std::string> loadAllUsers(void);
bool isUserEnabled(const std::string& callsign);
std::set<uint32_t> loadClusterTgs(void);
std::string loadTrunkFilter(const std::string& section,
const std::string& field); // "blacklist"|"allow"
std::map<uint32_t, uint32_t> loadTrunkTgMap(const std::string& section);
std::map<std::string, TrunkPeerConfig> loadTrunkPeers(void);
// Publish a config.changed scope token (sync).
void publishConfigChanged(const std::string& scope);
// Live-state push (non-blocking; enqueues onto live queue).
void pushLiveTalker(uint32_t tg, const std::string& callsign,
const std::string& source);
void clearLiveTalker(uint32_t tg);
void pushLiveClient(const std::string& callsign,
const std::string& ip,
const std::string& codecs,
uint32_t current_tg);
void clearLiveClient(const std::string& callsign);
void pushLiveTrunk(const std::string& section,
const std::string& state,
const std::string& peer_id);
uint64_t droppedLiveWrites(void) const { return m_dropped_live_writes; }
size_t liveQueueSize(void) const;
void onAsyncDisconnect(int status);
void onAsyncWriteDisconnect(int status);
private:
Config m_cfg;
redisContext* m_sync = nullptr;
redisAsyncContext* m_async = nullptr; // pub/sub subscriber only
redisAsyncContext* m_async_write = nullptr; // live-state writes (HSET/DEL)
RedisAsyncAdapter* m_adapter = nullptr;
RedisLiveQueue* m_live_queue = nullptr;
Async::Timer* m_drain_timer = nullptr;
Async::Timer* m_reconnect_timer = nullptr;
Async::Timer* m_heartbeat_timer = nullptr;
int m_reconnect_backoff_s = 1;
bool m_shutting_down = false;
uint64_t m_dropped_live_writes = 0;
std::set<std::string> m_live_keys;
bool connectSync(void);
bool connectAsync(void);
bool connectAsyncWrite(void);
void subscribe(void);
void scheduleReconnect(void);
void onPubSubMessage(const std::string& channel, const std::string& payload);
void drainLiveQueue(Async::Timer*);
void refreshLiveExpire(Async::Timer*);
std::string keyFor(const std::string& suffix) const;
std::string channelName(void) const;
};
#endif /* REDIS_STORE_INCLUDED */
+280 -25
View File
@@ -31,6 +31,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/ ****************************************************************************/
#include <cassert> #include <cassert>
#include <list>
#include <sstream> #include <sstream>
#include <unistd.h> #include <unistd.h>
#include <algorithm> #include <algorithm>
@@ -69,6 +70,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "ReflectorClient.h" #include "ReflectorClient.h"
#include "TGHandler.h" #include "TGHandler.h"
#include "TrunkLink.h" #include "TrunkLink.h"
#include "RedisStore.h"
#include <version/SVXREFLECTOR.h> #include <version/SVXREFLECTOR.h>
@@ -298,6 +300,8 @@ Reflector::~Reflector(void)
m_srv = 0; m_srv = 0;
delete m_cmd_pty; delete m_cmd_pty;
m_cmd_pty = 0; m_cmd_pty = 0;
delete m_redis;
m_redis = nullptr;
for (auto* link : m_trunk_links) for (auto* link : m_trunk_links)
{ {
delete link; delete link;
@@ -417,36 +421,57 @@ bool Reflector::initialize(Async::Config &cfg)
mem_fun(*this, &Reflector::ctrlPtyDataReceived)); mem_fun(*this, &Reflector::ctrlPtyDataReceived));
} }
// Optional [REDIS] section — when present, Redis becomes the source
// of truth for users/passwords/cluster/trunk dynamic settings.
{
std::string redis_host;
std::string redis_unix;
m_cfg->getValue("REDIS", "HOST", redis_host);
m_cfg->getValue("REDIS", "UNIX_SOCKET", redis_unix);
if (!redis_host.empty() || !redis_unix.empty())
{
RedisStore::Config rcfg;
rcfg.host = redis_host;
rcfg.unix_socket = redis_unix;
std::string port_s; m_cfg->getValue("REDIS", "PORT", port_s);
if (!port_s.empty()) rcfg.port = static_cast<uint16_t>(std::stoul(port_s));
m_cfg->getValue("REDIS", "PASSWORD", rcfg.password);
std::string db_s; m_cfg->getValue("REDIS", "DB", db_s);
if (!db_s.empty()) rcfg.db = std::stoi(db_s);
m_cfg->getValue("REDIS", "KEY_PREFIX", rcfg.key_prefix);
std::string tls_s; m_cfg->getValue("REDIS", "TLS_ENABLED", tls_s);
rcfg.tls_enabled = (tls_s == "1");
m_cfg->getValue("REDIS", "TLS_CA_CERT", rcfg.tls_ca_cert);
m_cfg->getValue("REDIS", "TLS_CLIENT_CERT", rcfg.tls_client_cert);
m_cfg->getValue("REDIS", "TLS_CLIENT_KEY", rcfg.tls_client_key);
m_redis = new RedisStore(rcfg);
if (!m_redis->connect()) {
std::cerr << "*** ERROR: [REDIS] is configured but Redis is unreachable. "
<< "Aborting startup." << std::endl;
return false;
}
auto warn_if_nonempty = [this](const char* section) {
std::list<std::string> keys = m_cfg->listSection(section);
if (!keys.empty()) {
std::cerr << "WARN: [" << section << "] in svxreflector.conf is "
"ignored because [REDIS] is configured. "
<< "Run --import-conf-to-redis to migrate." << std::endl;
}
};
warn_if_nonempty("USERS");
warn_if_nonempty("PASSWORDS");
m_redis->configChanged.connect(
sigc::mem_fun(*this, &Reflector::onRedisConfigChanged));
}
}
m_cfg->getValue("GLOBAL", "ACCEPT_CERT_EMAIL", m_accept_cert_email); m_cfg->getValue("GLOBAL", "ACCEPT_CERT_EMAIL", m_accept_cert_email);
m_cfg->valueUpdated.connect(sigc::mem_fun(*this, &Reflector::cfgUpdated)); m_cfg->valueUpdated.connect(sigc::mem_fun(*this, &Reflector::cfgUpdated));
// Parse CLUSTER_TGS — comma-separated list of TG numbers broadcast to all peers // Parse CLUSTER_TGS — comma-separated list of TG numbers broadcast to all peers
std::string cluster_tgs_str; reloadClusterTgs();
if (cfg.getValue("GLOBAL", "CLUSTER_TGS", cluster_tgs_str))
{
std::istringstream ctss(cluster_tgs_str);
std::string token;
while (std::getline(ctss, token, ','))
{
token.erase(0, token.find_first_not_of(" \t"));
token.erase(token.find_last_not_of(" \t") + 1);
if (!token.empty())
{
uint32_t tg = static_cast<uint32_t>(std::stoul(token));
m_cluster_tgs.insert(tg);
}
}
if (!m_cluster_tgs.empty())
{
std::cout << "Cluster TGs:";
for (uint32_t tg : m_cluster_tgs)
{
std::cout << " " << tg;
}
std::cout << std::endl;
}
}
// Satellite mode: connect to parent instead of joining the trunk mesh // Satellite mode: connect to parent instead of joining the trunk mesh
std::string satellite_of; std::string satellite_of;
@@ -1056,6 +1081,10 @@ void Reflector::clientDisconnected(Async::FramedTcpConnection *con,
{ {
m_mqtt->onClientDisconnected(client->callsign()); m_mqtt->onClientDisconnected(client->callsign());
} }
if (m_redis != nullptr)
{
m_redis->clearLiveClient(client->callsign());
}
scheduleNodeListUpdate(); scheduleNodeListUpdate();
} }
//Application::app().runTask([=]{ delete client; }); //Application::app().runTask([=]{ delete client; });
@@ -1521,6 +1550,10 @@ void Reflector::onTalkerUpdated(uint32_t tg, ReflectorClient* old_talker,
{ {
m_mqtt->onTalkerStop(tg, old_talker->callsign(), false); m_mqtt->onTalkerStop(tg, old_talker->callsign(), false);
} }
if (m_redis != nullptr)
{
m_redis->clearLiveTalker(tg);
}
} }
if (new_talker != 0) if (new_talker != 0)
{ {
@@ -1540,6 +1573,10 @@ void Reflector::onTalkerUpdated(uint32_t tg, ReflectorClient* old_talker,
{ {
m_mqtt->onTalkerStart(tg, new_talker->callsign(), false); m_mqtt->onTalkerStart(tg, new_talker->callsign(), false);
} }
if (m_redis != nullptr)
{
m_redis->pushLiveTalker(tg, new_talker->callsign(), "local");
}
} }
// In satellite mode, forward to parent instead of trunk peers // In satellite mode, forward to parent instead of trunk peers
@@ -1726,6 +1763,15 @@ void Reflector::refreshStatus(void)
m_status["satellite_server"] = sat_srv; m_status["satellite_server"] = sat_srv;
} }
} }
if (m_redis != nullptr)
{
Json::Value redis_status(Json::objectValue);
redis_status["live_queue_size"] =
static_cast<Json::UInt>(m_redis->liveQueueSize());
redis_status["dropped_live_writes"] =
static_cast<Json::UInt64>(m_redis->droppedLiveWrites());
m_status["redis"] = redis_status;
}
} /* Reflector::refreshStatus */ } /* Reflector::refreshStatus */
@@ -1989,6 +2035,7 @@ void Reflector::ctrlPtyDataReceived(const void *buf, size_t count)
} }
if (subcmd == "MUTE") link->muteCallsign(callsign); if (subcmd == "MUTE") link->muteCallsign(callsign);
else link->unmuteCallsign(callsign); else link->unmuteCallsign(callsign);
m_cmd_pty->write(section + ": " + subcmd + " " + callsign + "\n"); m_cmd_pty->write(section + ": " + subcmd + " " + callsign + "\n");
} }
else if (subcmd == "RELOAD") else if (subcmd == "RELOAD")
@@ -2121,6 +2168,38 @@ void Reflector::initTrunkLinks(void)
} }
} }
// If Redis is configured, load trunk peer definitions from Redis and
// synthesize them into m_cfg so the existing trunk initialization
// loop picks them up. Warn if the .conf ALSO has [TRUNK_*] sections
// (they are ignored per the Redis-overrides rule).
if (m_redis != nullptr) {
std::list<std::string> conf_sections = m_cfg->listSections();
bool conf_has_trunk = false;
for (const std::string& s : conf_sections) {
if (s.size() >= 6 && s.substr(0, 6) == "TRUNK_") { conf_has_trunk = true; break; }
}
if (conf_has_trunk) {
std::cerr << "WARN: [TRUNK_*] sections in svxreflector.conf are "
"ignored because [REDIS] is configured. Run "
"--import-conf-to-redis to migrate." << std::endl;
}
auto peers = m_redis->loadTrunkPeers();
for (const auto& kv : peers) {
const std::string& section = kv.first;
const auto& p = kv.second;
m_cfg->setValue(section, "HOST", p.host);
if (!p.port.empty()) m_cfg->setValue(section, "PORT", p.port);
m_cfg->setValue(section, "SECRET", p.secret);
m_cfg->setValue(section, "REMOTE_PREFIX", p.remote_prefix);
if (!p.peer_id.empty())
m_cfg->setValue(section, "PEER_ID", p.peer_id);
m_redis_trunk_sections.insert(section);
}
std::cout << "Redis: loaded " << peers.size() << " trunk peer(s)"
<< std::endl;
}
// First pass: collect all remote prefixes so we can do longest-prefix-match // First pass: collect all remote prefixes so we can do longest-prefix-match
std::vector<std::string> trunk_sections; std::vector<std::string> trunk_sections;
for (const auto& section : m_cfg->listSections()) for (const auto& section : m_cfg->listSections())
@@ -2650,6 +2729,10 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg,
{ {
m_mqtt->onTalkerStop(tg, old_cs, true); m_mqtt->onTalkerStop(tg, old_cs, true);
} }
if (m_redis != nullptr)
{
m_redis->clearLiveTalker(tg);
}
} }
if (!new_cs.empty()) if (!new_cs.empty())
{ {
@@ -2664,6 +2747,10 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg,
{ {
m_mqtt->onTalkerStart(tg, new_cs, true); m_mqtt->onTalkerStart(tg, new_cs, true);
} }
if (m_redis != nullptr)
{
m_redis->pushLiveTalker(tg, new_cs, "trunk");
}
} }
// Forward trunk talker events to connected satellites // Forward trunk talker events to connected satellites
@@ -2681,6 +2768,166 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg,
} /* Reflector::onTrunkTalkerUpdated */ } /* Reflector::onTrunkTalkerUpdated */
void Reflector::reloadClusterTgs(void)
{
m_cluster_tgs.clear();
if (m_redis) {
m_cluster_tgs = m_redis->loadClusterTgs();
} else {
std::string cluster_tgs_str;
if (m_cfg->getValue("GLOBAL", "CLUSTER_TGS", cluster_tgs_str))
{
std::istringstream ctss(cluster_tgs_str);
std::string token;
while (std::getline(ctss, token, ','))
{
token.erase(0, token.find_first_not_of(" \t"));
token.erase(token.find_last_not_of(" \t") + 1);
if (!token.empty())
{
try {
m_cluster_tgs.insert(static_cast<uint32_t>(std::stoul(token)));
} catch (...) { /* skip malformed */ }
}
}
}
}
if (!m_cluster_tgs.empty())
{
std::cout << "Cluster TGs:";
for (uint32_t tg : m_cluster_tgs)
{
std::cout << " " << tg;
}
std::cout << std::endl;
}
}
std::vector<std::string> Reflector::collectAllTrunkPrefixes(void) const
{
std::vector<std::string> all;
for (const auto* link : m_trunk_links) {
for (const std::string& p : link->remotePrefix()) all.push_back(p);
}
return all;
}
bool Reflector::addTrunkLink(const std::string& section)
{
if (m_redis == nullptr) {
std::cerr << "*** addTrunkLink called without Redis — refusing"
<< std::endl;
return false;
}
// Already present?
for (const auto* link : m_trunk_links) {
if (link->section() == section) return true;
}
auto peers = m_redis->loadTrunkPeers();
auto it = peers.find(section);
if (it == peers.end()) {
std::cerr << "*** addTrunkLink(" << section
<< "): peer hash not found in Redis" << std::endl;
return false;
}
const auto& p = it->second;
// Synthesize the config section (same shape as startup).
m_cfg->setValue(section, "HOST", p.host);
if (!p.port.empty()) m_cfg->setValue(section, "PORT", p.port);
m_cfg->setValue(section, "SECRET", p.secret);
m_cfg->setValue(section, "REMOTE_PREFIX", p.remote_prefix);
if (!p.peer_id.empty()) m_cfg->setValue(section, "PEER_ID", p.peer_id);
auto* link = new TrunkLink(this, *m_cfg, section);
if (!link->initialize()) {
std::cerr << "*** addTrunkLink(" << section
<< "): TrunkLink::initialize() failed" << std::endl;
delete link;
return false;
}
m_trunk_links.push_back(link);
m_redis_trunk_sections.insert(section);
// Rebroadcast the full prefix set to every link (including the new one).
auto all_prefixes = collectAllTrunkPrefixes();
for (auto* l : m_trunk_links) l->setAllPrefixes(all_prefixes);
std::cout << "Added trunk link: " << section << " (" << p.host
<< ":" << (p.port.empty() ? "5302" : p.port) << ")" << std::endl;
return true;
}
bool Reflector::removeTrunkLink(const std::string& section)
{
auto it = std::find_if(m_trunk_links.begin(), m_trunk_links.end(),
[&](TrunkLink* l) { return l->section() == section; });
if (it == m_trunk_links.end()) return false;
TrunkLink* dead = *it;
m_trunk_links.erase(it);
m_redis_trunk_sections.erase(section);
delete dead; // destructor clears trunk talker state via TGHandler
// Rebroadcast the remaining prefix set so peers drop the removed one.
auto all_prefixes = collectAllTrunkPrefixes();
for (auto* l : m_trunk_links) l->setAllPrefixes(all_prefixes);
std::cout << "Removed trunk link: " << section << std::endl;
return true;
}
void Reflector::onRedisConfigChanged(std::string scope)
{
std::cout << "Redis config.changed: " << scope << std::endl;
if (scope == "users" || scope == "all") {
// Auth lookups are stateless (per-connect). Nothing to invalidate on
// existing connections — they are already authenticated. New
// connections will re-query Redis automatically.
}
if (scope == "cluster" || scope == "all") {
reloadClusterTgs();
}
if (scope.rfind("trunk:", 0) == 0 || scope == "all") {
std::string section = (scope == "all") ? "" : scope.substr(6);
if (section.empty()) {
// Full sweep — reload filters on every existing link; don't try
// to add/remove here (startup already did that).
for (auto* link : m_trunk_links) link->reloadConfig();
} else {
// Per-section: check Redis for peer presence vs local state.
auto peers = m_redis ? m_redis->loadTrunkPeers()
: std::map<std::string, RedisStore::TrunkPeerConfig>{};
bool peer_in_redis = peers.find(section) != peers.end();
TrunkLink* existing = nullptr;
for (auto* l : m_trunk_links) {
if (l->section() == section) { existing = l; break; }
}
bool redis_managed = m_redis_trunk_sections.count(section) > 0;
if (peer_in_redis && existing == nullptr) {
addTrunkLink(section);
} else if (!peer_in_redis && existing != nullptr && redis_managed) {
// Only remove links that were originally created from Redis; conf-based
// links (e.g. TRUNK_TEST in tests) use reloadConfig() instead.
removeTrunkLink(section);
} else if (existing != nullptr) {
existing->reloadConfig();
} else {
// neither — log and ignore
std::cout << "Redis: trunk:" << section
<< " event but peer not in Redis and no local link"
<< std::endl;
}
}
}
}
void Reflector::publishRxUpdate(ReflectorClient* client) void Reflector::publishRxUpdate(ReflectorClient* client)
{ {
if (m_mqtt != nullptr && !client->callsign().empty()) if (m_mqtt != nullptr && !client->callsign().empty())
@@ -2697,6 +2944,10 @@ void Reflector::onClientAuthenticated(const std::string& callsign,
{ {
m_mqtt->onClientConnected(callsign, tg, ip); m_mqtt->onClientConnected(callsign, tg, ip);
} }
if (m_redis != nullptr)
{
m_redis->pushLiveClient(callsign, ip, "", tg);
}
scheduleNodeListUpdate(); scheduleNodeListUpdate();
} /* Reflector::onClientAuthenticated */ } /* Reflector::onClientAuthenticated */
@@ -2763,6 +3014,10 @@ void Reflector::onTrunkStateChanged(const std::string& section,
m_mqtt->onTrunkDown(topic_id, direction); m_mqtt->onTrunkDown(topic_id, direction);
} }
} }
if (m_redis != nullptr)
{
m_redis->pushLiveTrunk(section, up ? "up" : "down", peer_id);
}
} /* Reflector::onTrunkStateChanged */ } /* Reflector::onTrunkStateChanged */
+10
View File
@@ -86,6 +86,7 @@ namespace Async
class ReflectorMsg; class ReflectorMsg;
class ReflectorUdpMsg; class ReflectorUdpMsg;
class RedisStore;
/**************************************************************************** /****************************************************************************
@@ -244,6 +245,8 @@ class Reflector : public sigc::trackable
bool isClusterTG(uint32_t tg) const { return m_cluster_tgs.count(tg) > 0; } bool isClusterTG(uint32_t tg) const { return m_cluster_tgs.count(tg) > 0; }
bool isSatelliteMode(void) const { return m_is_satellite; } bool isSatelliteMode(void) const { return m_is_satellite; }
RedisStore* redisStore(void) const { return m_redis; }
// Callbacks for SatelliteLink to forward satellite events to trunk peers // Callbacks for SatelliteLink to forward satellite events to trunk peers
void forwardSatelliteAudioToTrunks(uint32_t tg, void forwardSatelliteAudioToTrunks(uint32_t tg,
const std::string& callsign); const std::string& callsign);
@@ -316,6 +319,7 @@ class Reflector : public sigc::trackable
Json::Value m_status; Json::Value m_status;
std::vector<TrunkLink*> m_trunk_links; std::vector<TrunkLink*> m_trunk_links;
std::set<std::string> m_redis_trunk_sections; // sections loaded from Redis
std::set<uint32_t> m_cluster_tgs; std::set<uint32_t> m_cluster_tgs;
bool m_trunk_debug = false; bool m_trunk_debug = false;
Async::Timer m_nodelist_timer; Async::Timer m_nodelist_timer;
@@ -338,6 +342,7 @@ class Reflector : public sigc::trackable
// MQTT publishing // MQTT publishing
MqttPublisher* m_mqtt = nullptr; MqttPublisher* m_mqtt = nullptr;
RedisStore* m_redis = nullptr;
Async::Timer m_mqtt_status_timer; Async::Timer m_mqtt_status_timer;
Reflector(const Reflector&); Reflector(const Reflector&);
@@ -362,6 +367,11 @@ class Reflector : public sigc::trackable
void cfgUpdated(const std::string& section, const std::string& tag); void cfgUpdated(const std::string& section, const std::string& tag);
void onTrunkTalkerUpdated(uint32_t tg, std::string old_cs, void onTrunkTalkerUpdated(uint32_t tg, std::string old_cs,
std::string new_cs); std::string new_cs);
void onRedisConfigChanged(std::string scope);
void reloadClusterTgs(void);
bool addTrunkLink(const std::string& section);
bool removeTrunkLink(const std::string& section);
std::vector<std::string> collectAllTrunkPrefixes(void) const;
void refreshStatus(void); void refreshStatus(void);
void initTrunkLinks(void); void initTrunkLinks(void);
void initTrunkServer(void); void initTrunkServer(void);
@@ -63,6 +63,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "ReflectorClient.h" #include "ReflectorClient.h"
#include "Reflector.h" #include "Reflector.h"
#include "TGHandler.h" #include "TGHandler.h"
#include "RedisStore.h"
/**************************************************************************** /****************************************************************************
@@ -1290,6 +1291,14 @@ void ReflectorClient::handleHeartbeat(Async::Timer *t)
std::string ReflectorClient::lookupUserKey(const std::string& callsign) std::string ReflectorClient::lookupUserKey(const std::string& callsign)
{ {
if (m_reflector->redisStore() != nullptr) {
std::string key = m_reflector->redisStore()->lookupUserKey(callsign);
if (key.empty()) {
cout << "*** WARNING: Redis lookup failed for user \""
<< callsign << "\"" << endl;
}
return key;
}
string auth_group; string auth_group;
if (!m_cfg->getValue("USERS", callsign, auth_group) || auth_group.empty()) if (!m_cfg->getValue("USERS", callsign, auth_group) || auth_group.empty())
{ {
+52 -23
View File
@@ -60,6 +60,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "Reflector.h" #include "Reflector.h"
#include "TGHandler.h" #include "TGHandler.h"
#include "ReflectorClient.h" #include "ReflectorClient.h"
#include "RedisStore.h"
#include <json/json.h> #include <json/json.h>
@@ -371,18 +372,26 @@ Json::Value TrunkLink::statusJson(void) const
for (const auto& p : m_remote_prefix) remote_arr.append(p); for (const auto& p : m_remote_prefix) remote_arr.append(p);
obj["remote_prefix"] = remote_arr; obj["remote_prefix"] = remote_arr;
// active_talkers: TGs held by trunk that match remote prefix or are cluster TGs // active_talkers: per-peer active TGs (already post-TG_MAP remap).
// We use m_peer_active_tgs directly instead of filtering the global
// trunk-talker map by isSharedTG, because a TG_MAP entry can remap a
// peer-owned wire TG to a local-owned TG that no longer matches the
// peer's remote prefix — that TG must still appear in this peer's view.
Json::Value talkers(Json::objectValue); Json::Value talkers(Json::objectValue);
const auto& trunk_map = TGHandler::instance()->trunkTalkersSnapshot(); for (uint32_t tg : m_peer_active_tgs)
for (auto& kv : trunk_map)
{ {
if (isSharedTG(kv.first) || m_reflector->isClusterTG(kv.first)) const std::string cs = TGHandler::instance()->trunkTalkerForTG(tg);
if (!cs.empty())
{ {
talkers[std::to_string(kv.first)] = kv.second; talkers[std::to_string(tg)] = cs;
} }
} }
obj["active_talkers"] = talkers; obj["active_talkers"] = talkers;
Json::Value muted_arr(Json::arrayValue);
for (const auto& cs : m_muted_callsigns) muted_arr.append(cs);
obj["muted"] = muted_arr;
return obj; return obj;
} /* TrunkLink::statusJson */ } /* TrunkLink::statusJson */
@@ -1098,34 +1107,53 @@ void TrunkLink::reloadConfig(void)
m_tg_map_in.clear(); m_tg_map_in.clear();
m_tg_map_out.clear(); m_tg_map_out.clear();
RedisStore* rs = m_reflector->redisStore();
std::string blacklist_str; std::string blacklist_str;
if (m_cfg.getValue(m_section, "BLACKLIST_TGS", blacklist_str) if (rs) {
&& !blacklist_str.empty()) blacklist_str = rs->loadTrunkFilter(m_section, "blacklist");
} else {
m_cfg.getValue(m_section, "BLACKLIST_TGS", blacklist_str);
}
if (!blacklist_str.empty())
{ {
m_blacklist_filter = TgFilter::parse(blacklist_str); m_blacklist_filter = TgFilter::parse(blacklist_str);
} }
std::string allow_str; std::string allow_str;
if (m_cfg.getValue(m_section, "ALLOW_TGS", allow_str) && !allow_str.empty()) if (rs) {
allow_str = rs->loadTrunkFilter(m_section, "allow");
} else {
m_cfg.getValue(m_section, "ALLOW_TGS", allow_str);
}
if (!allow_str.empty())
{ {
m_allow_filter = TgFilter::parse(allow_str); m_allow_filter = TgFilter::parse(allow_str);
} }
std::string tgmap_str; if (rs) {
if (m_cfg.getValue(m_section, "TG_MAP", tgmap_str) && !tgmap_str.empty()) auto tgmap = rs->loadTrunkTgMap(m_section);
{ for (auto& kv : tgmap) {
std::istringstream ms(tgmap_str); m_tg_map_in[kv.first] = kv.second;
std::string pair; m_tg_map_out[kv.second] = kv.first;
while (std::getline(ms, pair, ',')) }
} else {
std::string tgmap_str;
if (m_cfg.getValue(m_section, "TG_MAP", tgmap_str) && !tgmap_str.empty())
{ {
auto colon = pair.find(':'); std::istringstream ms(tgmap_str);
if (colon == std::string::npos) continue; std::string pair;
try { while (std::getline(ms, pair, ','))
uint32_t peer_tg = std::stoul(pair.substr(0, colon)); {
uint32_t local_tg = std::stoul(pair.substr(colon + 1)); auto colon = pair.find(':');
m_tg_map_in[peer_tg] = local_tg; if (colon == std::string::npos) continue;
m_tg_map_out[local_tg] = peer_tg; try {
} catch (...) { /* skip malformed */ } uint32_t peer_tg = std::stoul(pair.substr(0, colon));
uint32_t local_tg = std::stoul(pair.substr(colon + 1));
m_tg_map_in[peer_tg] = local_tg;
m_tg_map_out[local_tg] = peer_tg;
} catch (...) { /* skip malformed */ }
}
} }
} }
@@ -1134,7 +1162,8 @@ void TrunkLink::reloadConfig(void)
" blacklist=" + m_blacklist_filter.toString()) " blacklist=" + m_blacklist_filter.toString())
<< (m_allow_filter.empty() ? "" : << (m_allow_filter.empty() ? "" :
" allow=" + m_allow_filter.toString()) " allow=" + m_allow_filter.toString())
<< " tg_map_entries=" << m_tg_map_in.size() << endl; << " tg_map_entries=" << m_tg_map_in.size()
<< endl;
} /* TrunkLink::reloadConfig */ } /* TrunkLink::reloadConfig */
+4
View File
@@ -154,6 +154,10 @@ class TrunkLink : public sigc::trackable
{ {
return m_muted_callsigns.count(callsign) > 0; return m_muted_callsigns.count(callsign) > 0;
} }
const std::set<std::string>& mutedCallsigns(void) const
{
return m_muted_callsigns;
}
// Re-parse BLACKLIST_TGS, ALLOW_TGS and TG_MAP from current config // Re-parse BLACKLIST_TGS, ALLOW_TGS and TG_MAP from current config
void reloadConfig(void); void reloadConfig(void);
// One-line summary for TRUNK STATUS // One-line summary for TRUNK STATUS
@@ -157,3 +157,22 @@ CERT_CA_HOOK=@SVX_SHARE_INSTALL_DIR@/ca-hook.py
#TLS_CLIENT_CERT=/path/to/client.crt #TLS_CLIENT_CERT=/path/to/client.crt
#TLS_CLIENT_KEY=/path/to/client.key #TLS_CLIENT_KEY=/path/to/client.key
#
# Redis-backed config store. Optional — omit this section to use the
# config-file-only behavior. When this section is present, [USERS],
# [PASSWORDS], CLUSTER_TGS, and per-trunk BLACKLIST_TGS / ALLOW_TGS /
# TG_MAP / mute lists are read from Redis instead of this file. Use
# `svxreflector --import-conf-to-redis` once to migrate existing entries.
#
#[REDIS]
#HOST=127.0.0.1
#PORT=6379
#PASSWORD=
#DB=0
#KEY_PREFIX=
#UNIX_SOCKET= # if set, takes precedence over HOST/PORT
#TLS_ENABLED=0
#TLS_CA_CERT=
#TLS_CLIENT_CERT=
#TLS_CLIENT_KEY=
+215
View File
@@ -77,6 +77,8 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "version/SVXREFLECTOR.h" #include "version/SVXREFLECTOR.h"
#include "Reflector.h" #include "Reflector.h"
#include <hiredis/hiredis.h>
#include "RedisStore.h"
/**************************************************************************** /****************************************************************************
@@ -144,6 +146,211 @@ namespace {
LogWriter logwriter; LogWriter logwriter;
}; };
static int import_to_redis = 0;
static int dry_run = 0;
/****************************************************************************
*
* Local helper: import [USERS]/[PASSWORDS] from conf into Redis
*
****************************************************************************/
static bool runImportConfToRedis(Async::Config& cfg, bool dry_run)
{
RedisStore::Config rcfg;
cfg.getValue("REDIS", "HOST", rcfg.host);
std::string port_s; cfg.getValue("REDIS", "PORT", port_s);
if (!port_s.empty()) rcfg.port = static_cast<uint16_t>(std::stoul(port_s));
cfg.getValue("REDIS", "PASSWORD", rcfg.password);
std::string db_s; cfg.getValue("REDIS", "DB", db_s);
if (!db_s.empty()) rcfg.db = std::stoi(db_s);
cfg.getValue("REDIS", "KEY_PREFIX", rcfg.key_prefix);
cfg.getValue("REDIS", "UNIX_SOCKET", rcfg.unix_socket);
if (rcfg.host.empty() && rcfg.unix_socket.empty()) {
std::cerr << "*** ERROR: --import-conf-to-redis requires [REDIS] in conf"
<< std::endl;
return false;
}
redisContext* ctx = nullptr;
if (!dry_run) {
struct timeval tv = { 5, 0 };
ctx = rcfg.unix_socket.empty()
? redisConnectWithTimeout(rcfg.host.c_str(), rcfg.port, tv)
: redisConnectUnixWithTimeout(rcfg.unix_socket.c_str(), tv);
if (!ctx || ctx->err) {
std::cerr << "*** ERROR: import: Redis connect failed: "
<< (ctx ? ctx->errstr : "alloc failed") << std::endl;
if (ctx) redisFree(ctx);
return false;
}
if (!rcfg.password.empty()) {
redisReply* r = (redisReply*)redisCommand(ctx, "AUTH %s", rcfg.password.c_str());
if (r) freeReplyObject(r);
}
if (rcfg.db != 0) {
redisReply* r = (redisReply*)redisCommand(ctx, "SELECT %d", rcfg.db);
if (r) freeReplyObject(r);
}
}
auto kf = [&](const std::string& s) {
return rcfg.key_prefix.empty() ? s : rcfg.key_prefix + ":" + s;
};
size_t users = 0, groups = 0;
for (auto& cs : cfg.listSection("USERS")) {
std::string group;
if (!cfg.getValue("USERS", cs, group) || group.empty()) continue;
std::string ukey = kf("user:" + cs);
if (dry_run) {
std::cout << "[dry-run] HSET " << ukey << " group " << group
<< " enabled 1" << std::endl;
} else {
redisReply* r = (redisReply*)redisCommand(ctx,
"HSET %s group %s enabled 1", ukey.c_str(), group.c_str());
if (r) freeReplyObject(r);
}
++users;
}
for (auto& g : cfg.listSection("PASSWORDS")) {
std::string pw;
if (!cfg.getValue("PASSWORDS", g, pw) || pw.empty()) continue;
std::string gkey = kf("group:" + g);
if (dry_run) {
std::cout << "[dry-run] HSET " << gkey << " password <REDACTED>"
<< std::endl;
} else {
redisReply* r = (redisReply*)redisCommand(ctx,
"HSET %s password %s", gkey.c_str(), pw.c_str());
if (r) freeReplyObject(r);
}
++groups;
}
size_t cluster_n = 0;
std::string cluster_str;
if (cfg.getValue("GLOBAL", "CLUSTER_TGS", cluster_str))
{
std::istringstream ss(cluster_str);
std::string tok;
std::string ck = kf("cluster:tgs");
while (std::getline(ss, tok, ','))
{
tok.erase(0, tok.find_first_not_of(" \t"));
tok.erase(tok.find_last_not_of(" \t") + 1);
if (tok.empty()) continue;
if (dry_run) {
std::cout << "[dry-run] SADD " << ck << " " << tok << std::endl;
} else {
redisReply* r = (redisReply*)redisCommand(ctx, "SADD %s %s",
ck.c_str(), tok.c_str());
if (r) freeReplyObject(r);
}
++cluster_n;
}
}
size_t trunks_n = 0;
std::list<std::string> sections = cfg.listSections();
for (auto& sec : sections)
{
if (sec.rfind("TRUNK_", 0) != 0) continue;
++trunks_n;
std::string trunk_label = sec.substr(6); // "TRUNK_AB" → "AB"
// Import the peer definition hash.
std::string host, port_s_peer, secret, remote_prefix, peer_id;
cfg.getValue(sec, "HOST", host);
cfg.getValue(sec, "PORT", port_s_peer);
cfg.getValue(sec, "SECRET", secret);
cfg.getValue(sec, "REMOTE_PREFIX", remote_prefix);
cfg.getValue(sec, "PEER_ID", peer_id);
if (!host.empty() && !secret.empty() && !remote_prefix.empty())
{
std::string pk = kf("trunk:" + trunk_label + ":peer");
auto setField = [&](const char* field, const std::string& value) {
if (value.empty()) return;
if (dry_run) {
std::cout << "[dry-run] HSET " << pk << " " << field
<< " " << (std::string(field) == "secret" ? "<REDACTED>" : value)
<< std::endl;
} else {
redisReply* r = (redisReply*)redisCommand(ctx, "HSET %s %s %s",
pk.c_str(), field, value.c_str());
if (r) freeReplyObject(r);
}
};
setField("host", host);
setField("port", port_s_peer);
setField("secret", secret);
setField("remote_prefix", remote_prefix);
setField("peer_id", peer_id);
}
auto importSet = [&](const std::string& field, const std::string& subkey) {
std::string s;
if (!cfg.getValue(sec, field, s) || s.empty()) return;
std::string k = kf("trunk:" + trunk_label + ":" + subkey);
std::istringstream ss(s);
std::string tok;
while (std::getline(ss, tok, ','))
{
tok.erase(0, tok.find_first_not_of(" \t"));
tok.erase(tok.find_last_not_of(" \t") + 1);
if (tok.empty()) continue;
if (dry_run) {
std::cout << "[dry-run] SADD " << k << " " << tok << std::endl;
} else {
redisReply* r = (redisReply*)redisCommand(ctx, "SADD %s %s",
k.c_str(), tok.c_str());
if (r) freeReplyObject(r);
}
}
};
importSet("BLACKLIST_TGS", "blacklist");
importSet("ALLOW_TGS", "allow");
std::string tgmap_str;
if (cfg.getValue(sec, "TG_MAP", tgmap_str) && !tgmap_str.empty())
{
std::string k = kf("trunk:" + trunk_label + ":tgmap");
std::istringstream ss(tgmap_str);
std::string pair;
while (std::getline(ss, pair, ','))
{
auto colon = pair.find(':');
if (colon == std::string::npos) continue;
std::string peer = pair.substr(0, colon);
std::string local = pair.substr(colon + 1);
// Trim whitespace
peer.erase(0, peer.find_first_not_of(" \t"));
peer.erase(peer.find_last_not_of(" \t") + 1);
local.erase(0, local.find_first_not_of(" \t"));
local.erase(local.find_last_not_of(" \t") + 1);
if (dry_run) {
std::cout << "[dry-run] HSET " << k << " " << peer
<< " " << local << std::endl;
} else {
redisReply* r = (redisReply*)redisCommand(ctx, "HSET %s %s %s",
k.c_str(), peer.c_str(), local.c_str());
if (r) freeReplyObject(r);
}
}
}
}
std::cout << "Imported " << users << " users, " << groups << " groups, "
<< cluster_n << " cluster TGs, " << trunks_n << " trunks."
<< std::endl;
if (ctx) redisFree(ctx);
return true;
}
/**************************************************************************** /****************************************************************************
* *
@@ -388,6 +595,10 @@ int main(int argc, const char *argv[])
stdin_watch->activity.connect(sigc::ptr_fun(&stdinHandler)); stdin_watch->activity.connect(sigc::ptr_fun(&stdinHandler));
} }
if (import_to_redis) {
return runImportConfToRedis(cfg, dry_run != 0) ? 0 : 1;
}
Reflector ref; Reflector ref;
if (ref.initialize(cfg)) if (ref.initialize(cfg))
{ {
@@ -453,6 +664,10 @@ static void parse_arguments(int argc, const char **argv)
"Start " PROGRAM_NAME " as a daemon", NULL}, "Start " PROGRAM_NAME " as a daemon", NULL},
{"version", 0, POPT_ARG_NONE, &print_version, 0, {"version", 0, POPT_ARG_NONE, &print_version, 0,
"Print the application version string", NULL}, "Print the application version string", NULL},
{"import-conf-to-redis", 0, POPT_ARG_NONE, &import_to_redis, 0,
"Import [USERS]/[PASSWORDS] from .conf into Redis, then exit", NULL},
{"dry-run", 0, POPT_ARG_NONE, &dry_run, 0,
"With --import-conf-to-redis: print commands without executing", NULL},
{NULL, 0, 0, NULL, 0} {NULL, 0, 0, NULL, 0}
}; };
int err; int err;
+35 -1
View File
@@ -24,6 +24,7 @@ def generate_reflector_conf(name: str) -> str:
f"CLUSTER_TGS={cluster_str}", f"CLUSTER_TGS={cluster_str}",
f"TRUNK_LISTEN_PORT={T.INTERNAL_TRUNK_PORT}", f"TRUNK_LISTEN_PORT={T.INTERNAL_TRUNK_PORT}",
f"HTTP_SRV_PORT={T.INTERNAL_HTTP_PORT}", f"HTTP_SRV_PORT={T.INTERNAL_HTTP_PORT}",
"COMMAND_PTY=/dev/shm/reflector_ctrl",
"TRUNK_DEBUG=1", "TRUNK_DEBUG=1",
"", "",
"[SERVER_CERT]", "[SERVER_CERT]",
@@ -109,6 +110,16 @@ def generate_reflector_conf(name: str) -> str:
lines.append(f"MQTT_NAME={T.MQTT_NAMES[name]}") lines.append(f"MQTT_NAME={T.MQTT_NAMES[name]}")
lines.append("") lines.append("")
if r.get("redis"):
lines += [
"[REDIS]",
f"HOST={T.REDIS['host']}",
f"PORT={T.REDIS['port']}",
f"DB={T.redis_db_index(name)}",
f"KEY_PREFIX={T.service_name(name)}",
"",
]
return "\n".join(lines) return "\n".join(lines)
@@ -133,6 +144,13 @@ def generate_docker_compose() -> str:
sat_port = T.mapped_satellite_port(name) sat_port = T.mapped_satellite_port(name)
sat_port_line = f'\n - "{sat_port}:{T.SATELLITE["listen_port"]}/tcp"' sat_port_line = f'\n - "{sat_port}:{T.SATELLITE["listen_port"]}/tcp"'
depends_on_line = ""
if T.REFLECTORS[name].get("redis"):
depends_on_line = """
depends_on:
redis:
condition: service_healthy"""
services.append(f""" {svc}: services.append(f""" {svc}:
build: build:
context: .. context: ..
@@ -151,7 +169,7 @@ def generate_docker_compose() -> str:
timeout: 2s timeout: 2s
retries: 15 retries: 15
networks: networks:
- trunk_mesh""") - trunk_mesh{depends_on_line}""")
# Mosquitto broker for MQTT testing # Mosquitto broker for MQTT testing
services.append(""" mosquitto: services.append(""" mosquitto:
@@ -167,6 +185,22 @@ def generate_docker_compose() -> str:
networks: networks:
- trunk_mesh""") - trunk_mesh""")
# Redis used by any reflector flagged `redis: True`.
any_redis = any(r.get("redis") for r in T.REFLECTORS.values())
if any_redis:
services.append(""" redis:
image: redis:7-alpine
command: ["redis-server", "--save", "", "--appendonly", "no"]
ports:
- "16379:6379/tcp"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 2s
timeout: 2s
retries: 10
networks:
- trunk_mesh""")
services_block = "\n\n".join(services) services_block = "\n\n".join(services)
volumes_block = "\n".join(f" {v}:" for v in volumes) volumes_block = "\n".join(f" {v}:" for v in volumes)
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Generate Redis-test config files and docker-compose.redis.yml from
topology_redis.py.
Run: python3 generate_redis_configs.py
"""
import os
import topology_redis as T
def generate_reflector_conf(name: str) -> str:
r = T.REFLECTORS[name]
lines = [
"[GLOBAL]",
'TIMESTAMP_FORMAT="%c"',
f"LISTEN_PORT={T.INTERNAL_CLIENT_PORT}",
"TG_FOR_V1_CLIENTS=999",
f"LOCAL_PREFIX={','.join(r['prefix'])}",
f"HTTP_SRV_PORT={T.INTERNAL_HTTP_PORT}",
"COMMAND_PTY=/dev/shm/reflector_ctrl",
"",
"[SERVER_CERT]",
f"COMMON_NAME={T.service_name(name)}",
"",
# Intentionally NO [USERS] or [PASSWORDS] — they would be ignored
# anyway when [REDIS] is present. Tests HSET users into Redis
# directly.
"[REDIS]",
f"HOST={T.REDIS['host']}",
f"PORT={T.REDIS['port']}",
f"DB={T.redis_db_index(name)}",
f"KEY_PREFIX={T.service_name(name)}",
"",
f"[{T.TRUNK_TEST['section']}]",
f"HOST={T.TRUNK_TEST['host']}",
f"PORT={T.TRUNK_TEST['port']}",
f"SECRET={T.TRUNK_TEST['secret']}",
f"REMOTE_PREFIX={T.TRUNK_TEST['remote_prefix']}",
"",
]
return "\n".join(lines)
def generate_docker_compose() -> str:
services = []
volumes = []
for name in sorted(T.REFLECTORS):
svc = T.service_name(name)
client_port = T.mapped_client_port(name)
http_port = T.mapped_http_port(name)
vol = f"pki-redis-{name}"
volumes.append(vol)
services.append(f""" {svc}:
build:
context: ..
dockerfile: Dockerfile
volumes:
- ./configs-redis/{svc}.conf:/etc/svxlink/svxreflector.conf:ro
- {vol}:/var/lib/svxlink/pki
ports:
- "{client_port}:{T.INTERNAL_CLIENT_PORT}/tcp"
- "{client_port}:{T.INTERNAL_CLIENT_PORT}/udp"
- "{http_port}:{T.INTERNAL_HTTP_PORT}/tcp"
depends_on:
redis:
condition: service_healthy
healthcheck:
test: ["CMD-SHELL", "bash -c '(echo > /dev/tcp/localhost/{T.INTERNAL_HTTP_PORT}) 2>/dev/null'"]
interval: 2s
timeout: 2s
retries: 15
networks:
- redis_mesh""")
services.append(f""" redis:
image: redis:7-alpine
command: ["redis-server", "--save", "", "--appendonly", "no"]
ports:
- "{T.redis_port()}:6379/tcp"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 2s
timeout: 2s
retries: 10
networks:
- redis_mesh""")
services_block = "\n\n".join(services)
volumes_block = "\n".join(f" {v}:" for v in volumes)
return f"""services:
{services_block}
volumes:
{volumes_block}
networks:
redis_mesh:
driver: bridge
"""
def main():
script_dir = os.path.dirname(os.path.abspath(__file__))
configs_dir = os.path.join(script_dir, "configs-redis")
os.makedirs(configs_dir, exist_ok=True)
for name in sorted(T.REFLECTORS):
path = os.path.join(configs_dir, f"{T.service_name(name)}.conf")
with open(path, "w") as f:
f.write(generate_reflector_conf(name))
print(f" wrote {os.path.relpath(path, script_dir)}")
compose_path = os.path.join(script_dir, "docker-compose.redis.yml")
with open(compose_path, "w") as f:
f.write(generate_docker_compose())
print(f" wrote docker-compose.redis.yml")
if __name__ == "__main__":
main()
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
COMPOSE="docker compose -f docker-compose.redis.yml"
cmd=${1:-all}
usage() {
cat <<'USAGE'
Usage: run_redis_tests.sh [up|test|down|all|help]
up Generate configs, build, and start the Redis test stack (leave running).
test Run python3 test_redis.py against the already-running stack.
down Tear the stack down (docker compose down -v --remove-orphans).
all Full cycle: up -> test -> down. This is the default and CI-friendly.
help This message.
Typical dev loop:
bash run_redis_tests.sh up # once
bash run_redis_tests.sh test # many times as you edit test_redis.py
bash run_redis_tests.sh down # when finished
USAGE
}
is_stack_up() {
$COMPOSE ps --status=running --services 2>/dev/null | grep -q '^reflector-r1$'
}
cmd_up() {
echo "=== Generating Redis-test configs from topology_redis.py ==="
python3 generate_redis_configs.py
echo "=== Building and starting Redis test stack ==="
$COMPOSE up -d --build --wait
echo "=== Stack is up. Run 'bash run_redis_tests.sh test' to run tests."
}
cmd_test() {
if ! is_stack_up; then
echo "Stack is not running. Run 'bash run_redis_tests.sh up' first." >&2
exit 1
fi
echo "=== Running Redis integration tests ==="
python3 test_redis.py
}
cmd_down() {
echo "=== Tearing down Redis test environment ==="
$COMPOSE down -v --remove-orphans
}
case "$cmd" in
up) cmd_up ;;
test) cmd_test ;;
down) cmd_down ;;
all) cmd_up; cmd_test; cmd_down ;;
help|-h|--help) usage ;;
*) echo "Unknown command: $cmd" >&2; usage >&2; exit 1 ;;
esac
+533
View File
@@ -0,0 +1,533 @@
#!/usr/bin/env python3
"""Integration tests for Redis-backed config store.
Uses the separate Redis test harness (topology_redis.py +
docker-compose.redis.yml). Reuses ClientPeer from test_trunk.py for V2
client authentication.
"""
import os
import subprocess
import sys
import time
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import topology_redis as T
from test_trunk import ClientPeer
HOST = "127.0.0.1"
R1 = "r1"
R1_SVC = T.service_name(R1)
R1_CLIENT_PORT = T.mapped_client_port(R1)
R1_DB = T.redis_db_index(R1)
R1_KEY_PREFIX = T.service_name(R1)
def redis_cli(*args) -> str:
"""Run a redis-cli command against the harness's Redis container
(against the reflector's DB index). Returns stdout (stripped)."""
cmd = [
"docker", "compose", "-f", "docker-compose.redis.yml",
"exec", "-T", "redis",
"redis-cli", "-n", str(R1_DB),
] + list(args)
res = subprocess.run(cmd, capture_output=True, text=True, check=True,
cwd=os.path.dirname(os.path.abspath(__file__)))
return res.stdout.strip()
def publish(scope: str):
redis_cli("PUBLISH", f"{R1_KEY_PREFIX}:config.changed", scope)
def k(suffix: str) -> str:
"""Prepend the reflector's key prefix."""
return f"{R1_KEY_PREFIX}:{suffix}"
def flushdb():
redis_cli("FLUSHDB")
def try_authenticate(callsign: str, password: str,
port: int = R1_CLIENT_PORT,
timeout: float = 3.0) -> bool:
"""Attempt V2 client auth against a reflector. Returns True on success,
False on rejection/timeout."""
peer = ClientPeer()
try:
peer.connect(HOST, port, timeout=timeout)
peer.authenticate(callsign=callsign, password=password)
return True
except Exception:
return False
finally:
if peer.tcp is not None:
try:
peer.tcp.close()
except Exception:
pass
def docker_logs_since(service: str, since: float) -> str:
"""Return stdout/stderr from the given compose service since `since`
(Unix timestamp). Used to assert on reflector log lines produced
after a specific test action."""
from datetime import datetime, timezone
since_iso = datetime.fromtimestamp(since, tz=timezone.utc).isoformat()
cmd = [
"docker", "compose", "-f", "docker-compose.redis.yml",
"logs", "--since", since_iso, service,
]
res = subprocess.run(cmd, capture_output=True, text=True, check=True,
cwd=os.path.dirname(os.path.abspath(__file__)))
return res.stdout + res.stderr
class RedisUsersTest(unittest.TestCase):
def setUp(self):
flushdb()
def test_user_add_then_authenticate(self):
"""HSET a user + group, publish, and verify the reflector accepts
authentication within 1 s."""
redis_cli("HSET", k("user:N0TEST"), "group", "TestGroup", "enabled", "1")
redis_cli("HSET", k("group:TestGroup"), "password", "testpass")
publish("users")
# No wait needed in theory — new connections re-query Redis every
# login — but allow a small settle to account for container clock
# skew and broker latency.
time.sleep(0.3)
self.assertTrue(try_authenticate("N0TEST", "testpass"),
"expected N0TEST to authenticate after Redis write")
def test_user_disable_rejects_auth(self):
"""Disabling a user via enabled=0 must cause auth to fail."""
redis_cli("HSET", k("user:N0TEST"), "group", "TestGroup", "enabled", "1")
redis_cli("HSET", k("group:TestGroup"), "password", "testpass")
publish("users")
time.sleep(0.3)
self.assertTrue(try_authenticate("N0TEST", "testpass"))
redis_cli("HSET", k("user:N0TEST"), "enabled", "0")
publish("users")
time.sleep(0.3)
self.assertFalse(try_authenticate("N0TEST", "testpass"),
"expected N0TEST to be rejected after enabled=0")
class RedisTrunkFilterTest(unittest.TestCase):
SECTION = "TRUNK_TEST"
def setUp(self):
flushdb()
def _wait_for_reload_log(self, since: float, expected_fragment: str,
timeout: float = 3.0) -> str:
"""Poll container logs until a 'Reloaded filters' line appears
that contains `expected_fragment`. Returns the matching line."""
deadline = time.time() + timeout
last_logs = ""
while time.time() < deadline:
last_logs = docker_logs_since(R1_SVC, since)
for line in last_logs.splitlines():
if "Reloaded filters" in line and expected_fragment in line:
return line
time.sleep(0.1)
self.fail(
f"Timed out waiting for 'Reloaded filters' with "
f"'{expected_fragment}'. Last logs:\n{last_logs}")
def test_blacklist_change_triggers_reload(self):
# Baseline: no blacklist key → nothing in Redis for this section.
# Add one and verify the reload log shows it.
t0 = time.time()
redis_cli("SADD", k(f"trunk:{self.SECTION}:blacklist"), "666")
publish(f"trunk:{self.SECTION}")
line = self._wait_for_reload_log(t0, "blacklist=666")
self.assertIn("TRUNK_TEST", line)
# Remove it, verify blacklist goes away.
t1 = time.time()
redis_cli("SREM", k(f"trunk:{self.SECTION}:blacklist"), "666")
publish(f"trunk:{self.SECTION}")
# After SREM the set is empty — the reload log will lack
# "blacklist=" entirely. Poll for a reload line that mentions
# the section but has no blacklist tag.
deadline = time.time() + 3.0
while time.time() < deadline:
logs = docker_logs_since(R1_SVC, t1)
for ln in logs.splitlines():
if ("TRUNK_TEST" in ln and "Reloaded filters" in ln
and "blacklist=" not in ln):
return
time.sleep(0.1)
self.fail(f"Timed out waiting for reload without blacklist. Logs:\n{logs}")
def test_allow_change_triggers_reload(self):
t0 = time.time()
redis_cli("SADD", k(f"trunk:{self.SECTION}:allow"), "24*")
publish(f"trunk:{self.SECTION}")
line = self._wait_for_reload_log(t0, "allow=24*")
self.assertIn("TRUNK_TEST", line)
class RedisLiveStateTest(unittest.TestCase):
"""Verify live:client:<callsign> hashes appear/disappear as V2 clients
connect and disconnect. Talker and trunk live-state are not covered here
(require UDP/trunk-peer scaffolding; deferred)."""
def setUp(self):
flushdb()
# Populate the user so authentication succeeds.
redis_cli("HSET", k("user:N0TEST"), "group", "TestGroup", "enabled", "1")
redis_cli("HSET", k("group:TestGroup"), "password", "testpass")
publish("users")
time.sleep(0.3)
def _wait_for_hash(self, key: str, present: bool,
timeout: float = 3.0):
"""Poll HGETALL until the key has/lacks fields. Redis TYPE is
checked via EXISTS — empty hashes don't exist."""
deadline = time.time() + timeout
last = ""
while time.time() < deadline:
exists = redis_cli("EXISTS", key).strip() == "1"
if present and exists:
last = redis_cli("HGETALL", key)
return last
if (not present) and (not exists):
return ""
time.sleep(0.1)
self.fail(
f"Timed out waiting for {key} "
f"{'to exist' if present else 'to be absent'}. Last: {last!r}")
def test_live_client_hash_appears_on_auth(self):
peer = ClientPeer()
peer.connect(HOST, R1_CLIENT_PORT)
try:
peer.authenticate(callsign="N0TEST", password="testpass")
raw = self._wait_for_hash(k("live:client:N0TEST"), present=True)
# HGETALL returns alternating field\nvalue\nfield\nvalue\n
fields = raw.splitlines()
mapping = dict(zip(fields[0::2], fields[1::2]))
self.assertIn("connected_at", mapping)
self.assertIn("ip", mapping)
self.assertIn("tg", mapping)
# codecs may be "" — just verify the field exists
self.assertIn("codecs", mapping)
# connected_at is a unix timestamp; sanity-check it's a
# reasonable value (positive, within last minute).
ts = int(mapping["connected_at"])
self.assertGreater(ts, 0)
self.assertLess(abs(ts - time.time()), 60)
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)
peer.authenticate(callsign="N0TEST", password="testpass")
self._wait_for_hash(k("live:client:N0TEST"), present=True)
# Forceful close — reflector should see disconnect quickly.
peer.tcp.close()
# Drain queue + Redis publish should take <100ms. Give more for slack.
self._wait_for_hash(k("live:client:N0TEST"), present=False, timeout=5.0)
class RedisOutageTest(unittest.TestCase):
"""Verify reflector tolerates Redis going down and resyncs on resume."""
def setUp(self):
flushdb()
# Populate a baseline user.
redis_cli("HSET", k("user:N0TEST"), "group", "TestGroup", "enabled", "1")
redis_cli("HSET", k("group:TestGroup"), "password", "testpass")
publish("users")
time.sleep(0.3)
def _compose(self, *args, check=True):
cmd = ["docker", "compose", "-f", "docker-compose.redis.yml"] + list(args)
return subprocess.run(cmd, capture_output=True, text=True, check=check,
cwd=os.path.dirname(os.path.abspath(__file__)))
def test_reflector_survives_outage_and_resyncs(self):
# Step 1: V2 client connected and authenticated.
peer = ClientPeer()
peer.connect(HOST, R1_CLIENT_PORT)
peer.authenticate(callsign="N0TEST", password="testpass")
try:
# Step 2: stop redis container, wait a couple seconds.
self._compose("stop", "redis")
time.sleep(2.0)
# Reflector must still be up (healthcheck is HTTP on port 8080).
# Connection to existing TCP client should NOT be dropped by the
# reflector just because Redis went away.
peer.tcp.settimeout(1.0)
# Send nothing — just verify the socket isn't RST'd.
try:
peer.tcp.send(b"")
except Exception as e:
self.fail(f"existing client connection dropped during outage: {e}")
# Step 3: start redis back up.
self._compose("start", "redis")
# Wait for Redis container to become healthy, then for the
# reflector's exponential backoff to reconnect. Worst case the
# reflector's backoff was at the 30s cap; typical is 1-4s. Give
# 60s to accommodate both the container start and a few backoff
# cycles.
t_restart = time.time()
# Wait for redis-cli to succeed first.
deadline = time.time() + 30.0
while time.time() < deadline:
res = self._compose("exec", "-T", "redis",
"redis-cli", "ping", check=False)
if res.returncode == 0 and "PONG" in res.stdout:
break
time.sleep(0.5)
else:
self.fail("redis container did not come back up in 30s")
# Wait for the reflector to log the full-reload that signals
# reconnect.
deadline = time.time() + 60.0
found = False
last_logs = ""
while time.time() < deadline:
last_logs = docker_logs_since(R1_SVC, t_restart)
if "config.changed: all" in last_logs:
found = True
break
time.sleep(1.0)
if not found:
self.fail(
"Reflector did not log 'config.changed: all' after "
f"Redis resumed. Logs since restart:\n{last_logs[-4000:]}")
# Step 4: verify post-recovery writes still take effect.
# N0OTHR is a valid ham-callsign-format string that satisfies the
# reflector's default ACCEPT_CALLSIGN regex (N + 0 + OTH + R).
redis_cli("HSET", k("user:N0OTHR"), "group", "OtherGroup",
"enabled", "1")
redis_cli("HSET", k("group:OtherGroup"), "password", "otherpw")
publish("users")
time.sleep(0.5)
self.assertTrue(try_authenticate("N0OTHR", "otherpw"),
"post-outage auth for a new user should succeed")
finally:
try:
peer.tcp.close()
except Exception:
pass
class RedisImportIdempotenceTest(unittest.TestCase):
"""Verify --import-conf-to-redis is idempotent: running twice against
an unchanged .conf produces identical Redis state."""
TEST_DB = 5 # isolated from reflector's DB=0 and other tests
TEST_PREFIX = "import-test"
def _redis_cli_db(self, *args) -> str:
cmd = [
"docker", "compose", "-f", "docker-compose.redis.yml",
"exec", "-T", "redis",
"redis-cli", "-n", str(self.TEST_DB),
] + list(args)
res = subprocess.run(cmd, capture_output=True, text=True, check=True,
cwd=os.path.dirname(os.path.abspath(__file__)))
return res.stdout.strip()
def _dump_keyspace(self) -> dict:
"""Dump every key's type + content into a dict for comparison."""
keys = self._redis_cli_db("KEYS", "*").splitlines()
keys = sorted(k for k in keys if k)
dump = {}
for key in keys:
t = self._redis_cli_db("TYPE", key)
if t == "hash":
raw = self._redis_cli_db("HGETALL", key).splitlines()
dump[key] = ("hash", dict(zip(raw[0::2], raw[1::2])))
elif t == "set":
members = sorted(self._redis_cli_db("SMEMBERS", key).splitlines())
dump[key] = ("set", members)
elif t == "string":
dump[key] = ("string", self._redis_cli_db("GET", key))
else:
dump[key] = (t, None)
return dump
def setUp(self):
self._redis_cli_db("FLUSHDB")
# Write the test .conf inside the reflector container using a
# bash heredoc via docker compose exec.
conf = f"""[GLOBAL]
LISTEN_PORT=5300
CLUSTER_TGS=222,91,2221
[REDIS]
HOST=redis
PORT=6379
DB={self.TEST_DB}
KEY_PREFIX={self.TEST_PREFIX}
[USERS]
SM0ABC=MyNodes
SM0ABC-1=MyNodes
SM3XYZ=SM3XYZ
[PASSWORDS]
MyNodes=change_me
SM3XYZ=strong_password
[TRUNK_AB]
HOST=peer.example.com
PORT=5302
SECRET=shared_secret
REMOTE_PREFIX=2
BLACKLIST_TGS=666,777*
ALLOW_TGS=24*,2624123
TG_MAP=1:2624123,2:2624124
"""
# Write via a heredoc in the container.
subprocess.run([
"docker", "compose", "-f", "docker-compose.redis.yml",
"exec", "-T", R1_SVC,
"bash", "-c",
"cat > /tmp/import-test.conf"
], input=conf, text=True, check=True,
cwd=os.path.dirname(os.path.abspath(__file__)))
def _run_importer(self):
"""Invoke --import-conf-to-redis against the test conf."""
# Path to the binary — discover it dynamically in case the base
# image places it elsewhere.
res = subprocess.run([
"docker", "compose", "-f", "docker-compose.redis.yml",
"exec", "-T", R1_SVC,
"bash", "-c",
"command -v svxreflector"
], capture_output=True, text=True, check=True,
cwd=os.path.dirname(os.path.abspath(__file__)))
binary = res.stdout.strip()
self.assertTrue(binary, "svxreflector binary not found in container")
subprocess.run([
"docker", "compose", "-f", "docker-compose.redis.yml",
"exec", "-T", R1_SVC,
binary, "--config", "/tmp/import-test.conf", "--import-conf-to-redis",
], capture_output=True, text=True, check=True,
cwd=os.path.dirname(os.path.abspath(__file__)))
def test_import_is_idempotent(self):
self._run_importer()
snapshot1 = self._dump_keyspace()
# Expected key shape — sanity check.
expected_keys_subset = {
f"{self.TEST_PREFIX}:user:SM0ABC",
f"{self.TEST_PREFIX}:user:SM0ABC-1",
f"{self.TEST_PREFIX}:user:SM3XYZ",
f"{self.TEST_PREFIX}:group:MyNodes",
f"{self.TEST_PREFIX}:group:SM3XYZ",
f"{self.TEST_PREFIX}:cluster:tgs",
f"{self.TEST_PREFIX}:trunk:AB:blacklist",
f"{self.TEST_PREFIX}:trunk:AB:allow",
f"{self.TEST_PREFIX}:trunk:AB:tgmap",
}
missing = expected_keys_subset - set(snapshot1.keys())
self.assertFalse(missing, f"first import missing keys: {missing}")
self._run_importer()
snapshot2 = self._dump_keyspace()
self.assertEqual(snapshot1, snapshot2,
"second import produced different Redis state")
class RedisTrunkAddRemoveTest(unittest.TestCase):
"""Verify dashboard-style add/remove of trunk peers at runtime via
pub/sub. Uses a dedicated section name so we don't collide with the
static TRUNK_TEST section from the generated .conf."""
SECTION = "TRUNK_DYNAMIC_ADD"
PEER_KEY_SUFFIX = f"trunk:{SECTION}:peer"
def setUp(self):
# Redis may still have the key from a previous run — be tidy.
redis_cli("DEL", k(self.PEER_KEY_SUFFIX))
# Also publish so any prior dynamic link gets torn down if still
# around from a previous test run that crashed mid-test.
publish(f"trunk:{self.SECTION}")
time.sleep(0.5)
def _wait_for_log(self, since: float, expected_fragment: str,
timeout: float = 3.0) -> str:
deadline = time.time() + timeout
last_logs = ""
while time.time() < deadline:
last_logs = docker_logs_since(R1_SVC, since)
for line in last_logs.splitlines():
if expected_fragment in line:
return line
time.sleep(0.1)
self.fail(
f"Timed out waiting for log containing '{expected_fragment}'. "
f"Last logs:\n{last_logs[-3000:]}")
def test_add_then_remove_via_pubsub(self):
# --- add ---
t0 = time.time()
redis_cli("HSET", k(self.PEER_KEY_SUFFIX),
"host", "192.0.2.77",
"port", "5302",
"secret", "dyn_secret",
"remote_prefix", "8")
publish(f"trunk:{self.SECTION}")
line = self._wait_for_log(t0, f"Added trunk link: {self.SECTION}")
self.assertIn("192.0.2.77", line)
# --- remove ---
t1 = time.time()
redis_cli("DEL", k(self.PEER_KEY_SUFFIX))
publish(f"trunk:{self.SECTION}")
self._wait_for_log(t1, f"Removed trunk link: {self.SECTION}")
def test_add_missing_fields_skipped(self):
"""Peer hash with missing required fields is skipped (no link
created, no crash)."""
t0 = time.time()
# Missing secret and remote_prefix.
redis_cli("HSET", k(self.PEER_KEY_SUFFIX),
"host", "192.0.2.88",
"port", "5302")
publish(f"trunk:{self.SECTION}")
# Give the reflector time to react.
time.sleep(1.0)
logs = docker_logs_since(R1_SVC, t0)
self.assertNotIn(f"Added trunk link: {self.SECTION}", logs,
"Incomplete peer should NOT have been added")
# And the reflector should not have crashed — check compose ps
res = subprocess.run([
"docker", "compose", "-f", "docker-compose.redis.yml",
"ps", "--status=running", "--services"
], capture_output=True, text=True, check=True,
cwd=os.path.dirname(os.path.abspath(__file__)))
self.assertIn("reflector-r1", res.stdout)
if __name__ == "__main__":
unittest.main(verbosity=2)
+5 -3
View File
@@ -205,8 +205,10 @@ def parse_msg(data: bytes):
elif msg_type == MSG_TRUNK_NODE_LIST: elif msg_type == MSG_TRUNK_NODE_LIST:
# vec<string> callsigns, vec<u32> tgs, vec<float> lat, vec<float> lon, # vec<string> callsigns, vec<u32> tgs, vec<float> lat, vec<float> lon,
# vec<string> qth_names. Each vector is u32-prefixed length. # vec<string> qth_names. Each vector is u32-prefixed length.
# Vector length prefixes are u16 (MsgPacker<std::vector> in
# AsyncMsg.h uses uint16_t for element counts).
def read_vec_str(off): def read_vec_str(off):
n = struct.unpack_from("!I", data, off)[0]; off += 4 n = struct.unpack_from("!H", data, off)[0]; off += 2
out = [] out = []
for _ in range(n): for _ in range(n):
s, off = unpack_string(data, off) s, off = unpack_string(data, off)
@@ -214,13 +216,13 @@ def parse_msg(data: bytes):
return out, off return out, off
def read_vec_u32(off): def read_vec_u32(off):
n = struct.unpack_from("!I", data, off)[0]; off += 4 n = struct.unpack_from("!H", data, off)[0]; off += 2
out = list(struct.unpack_from(f"!{n}I", data, off)) out = list(struct.unpack_from(f"!{n}I", data, off))
off += 4 * n off += 4 * n
return out, off return out, off
def read_vec_f32(off): def read_vec_f32(off):
n = struct.unpack_from("!I", data, off)[0]; off += 4 n = struct.unpack_from("!H", data, off)[0]; off += 2
out = list(struct.unpack_from(f"!{n}f", data, off)) out = list(struct.unpack_from(f"!{n}f", data, off))
off += 4 * n off += 4 * n
return out, off return out, off
+12 -1
View File
@@ -10,7 +10,7 @@ to regenerate configs/ and docker-compose.test.yml. The test harness
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
REFLECTORS = { REFLECTORS = {
# name prefixes (list) host-port-base # name prefixes (list) host-port-base redis
"a": {"prefix": ["122"], "trunk_port_base": 15000}, "a": {"prefix": ["122"], "trunk_port_base": 15000},
"b": {"prefix": ["121"], "trunk_port_base": 25000}, "b": {"prefix": ["121"], "trunk_port_base": 25000},
"c": {"prefix": ["1"], "trunk_port_base": 35000}, "c": {"prefix": ["1"], "trunk_port_base": 35000},
@@ -61,6 +61,17 @@ SATELLITE = {
"listen_port": 5303, "listen_port": 5303,
} }
# Redis broker — used by reflectors flagged `redis: True`.
# Each reflector uses its own DB index to avoid pollution between tests.
REDIS = {
"host": "redis",
"port": 6379,
}
def redis_db_index(name: str) -> int:
"""Stable per-reflector Redis DB index derived from name order."""
return sorted(REFLECTORS).index(name)
# MQTT test config — broker runs as a Docker service in test compose # MQTT test config — broker runs as a Docker service in test compose
MQTT = { MQTT = {
"host": "mosquitto", "host": "mosquitto",
+53
View File
@@ -0,0 +1,53 @@
"""Minimal topology for Redis-backed test harness.
Edit here, then run `python3 generate_redis_configs.py` to regenerate
configs-redis/ and docker-compose.redis.yml.
"""
# Single Redis-enabled reflector for the Redis test suite.
REFLECTORS = {
"r1": {"prefix": ["1"], "trunk_port_base": 45000, "redis": True},
}
REDIS = {
"host": "redis",
"port": 6379,
}
# V2 test client credentials (populated into Redis by tests themselves).
TEST_CLIENTS = [
{"callsign": "N0TEST", "group": "TestGroup", "password": "testpass"},
{"callsign": "N0OTHER", "group": "OtherGroup", "password": "otherpass"},
]
# Placeholder trunk peer — no real peer is running, but its [TRUNK_TEST]
# section makes the reflector instantiate a TrunkLink whose reloadConfig()
# we can trigger via pub/sub and verify via container logs.
TRUNK_TEST = {
"section": "TRUNK_TEST",
"host": "192.0.2.1", # TEST-NET-1 — guaranteed unroutable
"port": 59302,
"secret": "test_secret",
"remote_prefix": "9",
}
# Internal container ports (same as legacy harness so the reflector
# binary's defaults don't change).
INTERNAL_CLIENT_PORT = 5300
INTERNAL_TRUNK_PORT = 5302
INTERNAL_HTTP_PORT = 8080
def service_name(name: str) -> str:
return f"reflector-{name}"
def mapped_client_port(name: str) -> int:
return REFLECTORS[name]["trunk_port_base"] + 300
def mapped_http_port(name: str) -> int:
return REFLECTORS[name]["trunk_port_base"] + 3080
def redis_port() -> int:
return 46379
def redis_db_index(name: str) -> int:
return sorted(REFLECTORS).index(name)