From 2877d6be79a49c7c774c173636298b8bae2b6121 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 02:38:27 +0200 Subject: [PATCH 01/32] Add hiredis build/runtime dependency for upcoming Redis backend --- Dockerfile | 2 ++ src/svxlink/reflector/CMakeLists.txt | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/Dockerfile b/Dockerfile index 68d4ad5..6598e2a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,6 +11,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ libopus-dev \ libgsm1-dev \ libmosquitto-dev \ + libhiredis-dev \ && rm -rf /var/lib/apt/lists/* WORKDIR /src @@ -30,6 +31,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ libopus0 \ libgsm1 \ libmosquitto1 \ + libhiredis-dev \ && rm -rf /var/lib/apt/lists/* COPY --from=builder /src/build/bin/svxreflector /usr/bin/svxreflector diff --git a/src/svxlink/reflector/CMakeLists.txt b/src/svxlink/reflector/CMakeLists.txt index 700c9ef..4313fdd 100644 --- a/src/svxlink/reflector/CMakeLists.txt +++ b/src/svxlink/reflector/CMakeLists.txt @@ -24,6 +24,11 @@ pkg_check_modules(MOSQUITTO REQUIRED libmosquitto) include_directories(${MOSQUITTO_INCLUDE_DIRS}) 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 set(LIBS asynccpp asyncaudio asynccore svxmisc ${LIBS}) From b64b79f2a71043c4966614e1003d2bfaea21f03b Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 02:41:23 +0200 Subject: [PATCH 02/32] Add RedisStore skeleton (no functionality yet) --- src/svxlink/reflector/CMakeLists.txt | 2 +- src/svxlink/reflector/RedisStore.cpp | 53 +++++++++++++ src/svxlink/reflector/RedisStore.h | 109 +++++++++++++++++++++++++++ 3 files changed, 163 insertions(+), 1 deletion(-) create mode 100644 src/svxlink/reflector/RedisStore.cpp create mode 100644 src/svxlink/reflector/RedisStore.h diff --git a/src/svxlink/reflector/CMakeLists.txt b/src/svxlink/reflector/CMakeLists.txt index 4313fdd..07c5ce4 100644 --- a/src/svxlink/reflector/CMakeLists.txt +++ b/src/svxlink/reflector/CMakeLists.txt @@ -35,7 +35,7 @@ set(LIBS asynccpp asyncaudio asynccore svxmisc ${LIBS}) # Build the executable add_executable(svxreflector svxreflector.cpp Reflector.cpp ReflectorClient.cpp TGHandler.cpp TrunkLink.cpp - SatelliteLink.cpp SatelliteClient.cpp MqttPublisher.cpp + SatelliteLink.cpp SatelliteClient.cpp MqttPublisher.cpp RedisStore.cpp ) target_link_libraries(svxreflector ${LIBS}) set_target_properties(svxreflector PROPERTIES diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp new file mode 100644 index 0000000..2983cbf --- /dev/null +++ b/src/svxlink/reflector/RedisStore.cpp @@ -0,0 +1,53 @@ +#include "RedisStore.h" +#include +#include + +RedisStore::RedisStore(const Config& cfg) : m_cfg(cfg) {} +RedisStore::~RedisStore() { + if (m_sync) { redisFree(m_sync); m_sync = nullptr; } +} + +bool RedisStore::connect(void) { + std::cerr << "RedisStore::connect not implemented yet" << std::endl; + return false; +} + +bool RedisStore::isReady(void) const { return m_sync != nullptr; } + +std::string RedisStore::lookupUserKey(const std::string&) { return ""; } +std::map RedisStore::loadAllUsers(void) { return {}; } +bool RedisStore::isUserEnabled(const std::string&) { return true; } +std::set RedisStore::loadClusterTgs(void) { return {}; } +std::string RedisStore::loadTrunkFilter(const std::string&, const std::string&) { return ""; } +std::map RedisStore::loadTrunkTgMap(const std::string&) { return {}; } +std::set RedisStore::loadTrunkMutes(const std::string&) { return {}; } +void RedisStore::addTrunkMute(const std::string&, const std::string&) {} +void RedisStore::removeTrunkMute(const std::string&, const std::string&) {} +void RedisStore::publishConfigChanged(const std::string&) {} +void RedisStore::pushLiveTalker(uint32_t, const std::string&, const std::string&) {} +void RedisStore::clearLiveTalker(uint32_t) {} +void RedisStore::pushLiveClient(const std::string&, const std::string&, + const std::string&, uint32_t) {} +void RedisStore::clearLiveClient(const std::string&) {} +void RedisStore::pushLiveTrunk(const std::string&, const std::string&, + const std::string&) {} + +size_t RedisStore::liveQueueSize(void) const { return 0; } + +bool RedisStore::connectSync(void) { return false; } +bool RedisStore::connectAsync(void) { return false; } +void RedisStore::subscribe(void) {} +void RedisStore::scheduleReconnect(void) {} +void RedisStore::onAsyncDisconnect(int) {} +void RedisStore::onPubSubMessage(const std::string&, const std::string&) {} +void RedisStore::drainLiveQueue(Async::Timer*) {} +void RedisStore::refreshLiveExpire(Async::Timer*) {} + +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"); +} diff --git a/src/svxlink/reflector/RedisStore.h b/src/svxlink/reflector/RedisStore.h new file mode 100644 index 0000000..108f919 --- /dev/null +++ b/src/svxlink/reflector/RedisStore.h @@ -0,0 +1,109 @@ +#ifndef REDIS_STORE_INCLUDED +#define REDIS_STORE_INCLUDED + +#include +#include +#include +#include +#include +#include + +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; + }; + + 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:
", or "all". + sigc::signal 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 loadAllUsers(void); + bool isUserEnabled(const std::string& callsign); + + std::set loadClusterTgs(void); + + std::string loadTrunkFilter(const std::string& section, + const std::string& field); // "blacklist"|"allow" + std::map loadTrunkTgMap(const std::string& section); + std::set loadTrunkMutes(const std::string& section); + + // Mute set ops (sync, used by PTY persistence). + void addTrunkMute(const std::string& section, const std::string& callsign); + void removeTrunkMute(const std::string& section, const std::string& callsign); + + // 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; + + private: + Config m_cfg; + redisContext* m_sync = nullptr; + redisAsyncContext* m_async = nullptr; + 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; + uint64_t m_dropped_live_writes = 0; + + bool connectSync(void); + bool connectAsync(void); + void subscribe(void); + void scheduleReconnect(void); + void onAsyncDisconnect(int status); + 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 */ From 6ecbf69bc0f3bad2a841806121a2dcaf0c47efe4 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 02:44:01 +0200 Subject: [PATCH 03/32] Implement RedisStore sync connect and schema reads/writes --- src/svxlink/reflector/RedisStore.cpp | 184 +++++++++++++++++++++++++-- 1 file changed, 173 insertions(+), 11 deletions(-) diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp index 2983cbf..0e42e13 100644 --- a/src/svxlink/reflector/RedisStore.cpp +++ b/src/svxlink/reflector/RedisStore.cpp @@ -7,23 +7,186 @@ RedisStore::~RedisStore() { 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) { - std::cerr << "RedisStore::connect not implemented yet" << std::endl; - return false; + if (!connectSync()) return false; + std::cout << "RedisStore: connected (sync) to " + << (m_cfg.unix_socket.empty() + ? (m_cfg.host + ":" + std::to_string(m_cfg.port)) + : m_cfg.unix_socket) + << std::endl; + return true; } bool RedisStore::isReady(void) const { return m_sync != nullptr; } -std::string RedisStore::lookupUserKey(const std::string&) { return ""; } +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 RedisStore::loadAllUsers(void) { return {}; } bool RedisStore::isUserEnabled(const std::string&) { return true; } -std::set RedisStore::loadClusterTgs(void) { return {}; } -std::string RedisStore::loadTrunkFilter(const std::string&, const std::string&) { return ""; } -std::map RedisStore::loadTrunkTgMap(const std::string&) { return {}; } -std::set RedisStore::loadTrunkMutes(const std::string&) { return {}; } -void RedisStore::addTrunkMute(const std::string&, const std::string&) {} -void RedisStore::removeTrunkMute(const std::string&, const std::string&) {} -void RedisStore::publishConfigChanged(const std::string&) {} + +std::set RedisStore::loadClusterTgs(void) { + std::set 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 RedisStore::loadTrunkTgMap(const std::string& section) { + std::map 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::set RedisStore::loadTrunkMutes(const std::string& section) { + std::set out; + if (!m_sync) return out; + std::string k = keyFor("trunk:" + section + ":mutes"); + 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) { + out.emplace(r->element[i]->str, r->element[i]->len); + } + } + } + if (r) freeReplyObject(r); + return out; +} + +void RedisStore::addTrunkMute(const std::string& section, const std::string& callsign) { + if (!m_sync) return; + std::string k = keyFor("trunk:" + section + ":mutes"); + redisReply* r = (redisReply*)redisCommand(m_sync, "SADD %s %s", + k.c_str(), callsign.c_str()); + if (r) freeReplyObject(r); +} + +void RedisStore::removeTrunkMute(const std::string& section, const std::string& callsign) { + if (!m_sync) return; + std::string k = keyFor("trunk:" + section + ":mutes"); + redisReply* r = (redisReply*)redisCommand(m_sync, "SREM %s %s", + k.c_str(), callsign.c_str()); + if (r) freeReplyObject(r); +} + +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, const std::string&, const std::string&) {} void RedisStore::clearLiveTalker(uint32_t) {} void RedisStore::pushLiveClient(const std::string&, const std::string&, @@ -34,7 +197,6 @@ void RedisStore::pushLiveTrunk(const std::string&, const std::string&, size_t RedisStore::liveQueueSize(void) const { return 0; } -bool RedisStore::connectSync(void) { return false; } bool RedisStore::connectAsync(void) { return false; } void RedisStore::subscribe(void) {} void RedisStore::scheduleReconnect(void) {} From 98b7d0a89eb8834f31c8d14049af2adfdabb99c3 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 02:47:23 +0200 Subject: [PATCH 04/32] Parse [REDIS] section and connect at startup (sync only) --- src/svxlink/reflector/Reflector.cpp | 36 +++++++++++++++++++++++++++++ src/svxlink/reflector/Reflector.h | 4 ++++ 2 files changed, 40 insertions(+) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 4c47d5d..4f62537 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -69,6 +69,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "ReflectorClient.h" #include "TGHandler.h" #include "TrunkLink.h" +#include "RedisStore.h" #include @@ -298,6 +299,8 @@ Reflector::~Reflector(void) m_srv = 0; delete m_cmd_pty; m_cmd_pty = 0; + delete m_redis; + m_redis = nullptr; for (auto* link : m_trunk_links) { delete link; @@ -417,6 +420,39 @@ bool Reflector::initialize(Async::Config &cfg) 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(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; + } + } + } + m_cfg->getValue("GLOBAL", "ACCEPT_CERT_EMAIL", m_accept_cert_email); m_cfg->valueUpdated.connect(sigc::mem_fun(*this, &Reflector::cfgUpdated)); diff --git a/src/svxlink/reflector/Reflector.h b/src/svxlink/reflector/Reflector.h index 9bbea97..6e5481b 100644 --- a/src/svxlink/reflector/Reflector.h +++ b/src/svxlink/reflector/Reflector.h @@ -86,6 +86,7 @@ namespace Async class ReflectorMsg; 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 isSatelliteMode(void) const { return m_is_satellite; } + RedisStore* redisStore(void) const { return m_redis; } + // Callbacks for SatelliteLink to forward satellite events to trunk peers void forwardSatelliteAudioToTrunks(uint32_t tg, const std::string& callsign); @@ -338,6 +341,7 @@ class Reflector : public sigc::trackable // MQTT publishing MqttPublisher* m_mqtt = nullptr; + RedisStore* m_redis = nullptr; Async::Timer m_mqtt_status_timer; Reflector(const Reflector&); From 0de78c459b5b305e997cb042afcf90e131719d68 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 02:52:03 +0200 Subject: [PATCH 05/32] Add hiredis async adapter and pub/sub subscription --- src/svxlink/reflector/CMakeLists.txt | 1 + src/svxlink/reflector/RedisAsyncAdapter.cpp | 60 ++++++++++++++++++ src/svxlink/reflector/RedisAsyncAdapter.h | 16 +++++ src/svxlink/reflector/RedisStore.cpp | 67 ++++++++++++++++++--- src/svxlink/reflector/RedisStore.h | 3 +- 5 files changed, 139 insertions(+), 8 deletions(-) create mode 100644 src/svxlink/reflector/RedisAsyncAdapter.cpp create mode 100644 src/svxlink/reflector/RedisAsyncAdapter.h diff --git a/src/svxlink/reflector/CMakeLists.txt b/src/svxlink/reflector/CMakeLists.txt index 07c5ce4..775ed0f 100644 --- a/src/svxlink/reflector/CMakeLists.txt +++ b/src/svxlink/reflector/CMakeLists.txt @@ -36,6 +36,7 @@ set(LIBS asynccpp asyncaudio asynccore svxmisc ${LIBS}) add_executable(svxreflector svxreflector.cpp Reflector.cpp ReflectorClient.cpp TGHandler.cpp TrunkLink.cpp SatelliteLink.cpp SatelliteClient.cpp MqttPublisher.cpp RedisStore.cpp + RedisAsyncAdapter.cpp ) target_link_libraries(svxreflector ${LIBS}) set_target_properties(svxreflector PROPERTIES diff --git a/src/svxlink/reflector/RedisAsyncAdapter.cpp b/src/svxlink/reflector/RedisAsyncAdapter.cpp new file mode 100644 index 0000000..8d72544 --- /dev/null +++ b/src/svxlink/reflector/RedisAsyncAdapter.cpp @@ -0,0 +1,60 @@ +#include "RedisAsyncAdapter.h" +#include +#include +#include + +namespace { + +struct AdapterData +{ + redisAsyncContext* ac; + Async::FdWatch* rd = nullptr; + Async::FdWatch* wr = nullptr; +}; + +void adapterAddRead(void* priv) { + auto* d = static_cast(priv); + if (d->rd) d->rd->setEnabled(true); +} +void adapterDelRead(void* priv) { + auto* d = static_cast(priv); + if (d->rd) d->rd->setEnabled(false); +} +void adapterAddWrite(void* priv) { + auto* d = static_cast(priv); + if (d->wr) d->wr->setEnabled(true); +} +void adapterDelWrite(void* priv) { + auto* d = static_cast(priv); + if (d->wr) d->wr->setEnabled(false); +} +void adapterCleanup(void* priv) { + auto* d = static_cast(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; +} diff --git a/src/svxlink/reflector/RedisAsyncAdapter.h b/src/svxlink/reflector/RedisAsyncAdapter.h new file mode 100644 index 0000000..11361e3 --- /dev/null +++ b/src/svxlink/reflector/RedisAsyncAdapter.h @@ -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 */ diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp index 0e42e13..546a0fb 100644 --- a/src/svxlink/reflector/RedisStore.cpp +++ b/src/svxlink/reflector/RedisStore.cpp @@ -1,7 +1,29 @@ #include "RedisStore.h" #include +#include +#include "RedisAsyncAdapter.h" #include +namespace { + +void onPubSubMessageThunk(redisAsyncContext* /*ac*/, void* reply, void* priv) { + auto* self = static_cast(priv); + auto* r = static_cast(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(ac->data); + if (self) self->onAsyncDisconnect(status); +} + +} // namespace + RedisStore::RedisStore(const Config& cfg) : m_cfg(cfg) {} RedisStore::~RedisStore() { if (m_sync) { redisFree(m_sync); m_sync = nullptr; } @@ -45,11 +67,10 @@ bool RedisStore::connectSync(void) { bool RedisStore::connect(void) { if (!connectSync()) return false; - std::cout << "RedisStore: connected (sync) to " - << (m_cfg.unix_socket.empty() - ? (m_cfg.host + ":" + std::to_string(m_cfg.port)) - : m_cfg.unix_socket) - << std::endl; + if (!connectAsync()) return false; + subscribe(); + std::cout << "RedisStore: connected sync+async, subscribed to " + << channelName() << std::endl; return true; } @@ -197,8 +218,40 @@ void RedisStore::pushLiveTrunk(const std::string&, const std::string&, size_t RedisStore::liveQueueSize(void) const { return 0; } -bool RedisStore::connectAsync(void) { return false; } -void RedisStore::subscribe(void) {} +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; +} + +void RedisStore::subscribe(void) { + if (!m_async) return; + std::string ch = channelName(); + redisAsyncCommand(m_async, onPubSubMessageThunk, this, + "SUBSCRIBE %s", ch.c_str()); +} void RedisStore::scheduleReconnect(void) {} void RedisStore::onAsyncDisconnect(int) {} void RedisStore::onPubSubMessage(const std::string&, const std::string&) {} diff --git a/src/svxlink/reflector/RedisStore.h b/src/svxlink/reflector/RedisStore.h index 108f919..50d0c50 100644 --- a/src/svxlink/reflector/RedisStore.h +++ b/src/svxlink/reflector/RedisStore.h @@ -81,6 +81,8 @@ class RedisStore : public sigc::trackable uint64_t droppedLiveWrites(void) const { return m_dropped_live_writes; } size_t liveQueueSize(void) const; + void onAsyncDisconnect(int status); + private: Config m_cfg; redisContext* m_sync = nullptr; @@ -97,7 +99,6 @@ class RedisStore : public sigc::trackable bool connectAsync(void); void subscribe(void); void scheduleReconnect(void); - void onAsyncDisconnect(int status); void onPubSubMessage(const std::string& channel, const std::string& payload); void drainLiveQueue(Async::Timer*); void refreshLiveExpire(Async::Timer*); From 2a3515247cc0fc082a7b05d34a5641e5f9ad2fd4 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 08:46:39 +0200 Subject: [PATCH 06/32] Route auth lookup through RedisStore when [REDIS] is configured --- src/svxlink/reflector/Reflector.cpp | 11 +++++++++++ src/svxlink/reflector/ReflectorClient.cpp | 9 +++++++++ 2 files changed, 20 insertions(+) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 4f62537..467a842 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -31,6 +31,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ****************************************************************************/ #include +#include #include #include #include @@ -450,6 +451,16 @@ bool Reflector::initialize(Async::Config &cfg) << "Aborting startup." << std::endl; return false; } + auto warn_if_nonempty = [this](const char* section) { + std::list 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"); } } diff --git a/src/svxlink/reflector/ReflectorClient.cpp b/src/svxlink/reflector/ReflectorClient.cpp index e73631b..067a8d8 100644 --- a/src/svxlink/reflector/ReflectorClient.cpp +++ b/src/svxlink/reflector/ReflectorClient.cpp @@ -63,6 +63,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "ReflectorClient.h" #include "Reflector.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) { + 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; if (!m_cfg->getValue("USERS", callsign, auth_group) || auth_group.empty()) { From 977624febfee449da596f47c038d99a23408c2b4 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 08:57:08 +0200 Subject: [PATCH 07/32] Dispatch Redis config.changed events to per-scope reload paths --- src/svxlink/reflector/Reflector.cpp | 28 ++++++++++++++++++++++++++++ src/svxlink/reflector/Reflector.h | 2 ++ 2 files changed, 30 insertions(+) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 467a842..2fbd97a 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -461,6 +461,8 @@ bool Reflector::initialize(Async::Config &cfg) }; warn_if_nonempty("USERS"); warn_if_nonempty("PASSWORDS"); + m_redis->configChanged.connect( + sigc::mem_fun(*this, &Reflector::onRedisConfigChanged)); } } @@ -2728,6 +2730,32 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, } /* Reflector::onTrunkTalkerUpdated */ +void Reflector::reloadClusterTgs(void) +{ + // Stub — populated by Task C2 (Cluster TGs from Redis). +} + + +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); + for (auto* link : m_trunk_links) { + if (section.empty() || link->section() == section) link->reloadConfig(); + } + } +} + + void Reflector::publishRxUpdate(ReflectorClient* client) { if (m_mqtt != nullptr && !client->callsign().empty()) diff --git a/src/svxlink/reflector/Reflector.h b/src/svxlink/reflector/Reflector.h index 6e5481b..2a67ab0 100644 --- a/src/svxlink/reflector/Reflector.h +++ b/src/svxlink/reflector/Reflector.h @@ -366,6 +366,8 @@ class Reflector : public sigc::trackable void cfgUpdated(const std::string& section, const std::string& tag); void onTrunkTalkerUpdated(uint32_t tg, std::string old_cs, std::string new_cs); + void onRedisConfigChanged(std::string scope); + void reloadClusterTgs(void); void refreshStatus(void); void initTrunkLinks(void); void initTrunkServer(void); From 2826376070fe6817421ff28b19b1e908d9581b0a Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 09:02:25 +0200 Subject: [PATCH 08/32] Add --import-conf-to-redis migration tool (USERS+PASSWORDS) --- src/svxlink/reflector/svxreflector.cpp | 102 +++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/src/svxlink/reflector/svxreflector.cpp b/src/svxlink/reflector/svxreflector.cpp index 1239248..c47ad0e 100644 --- a/src/svxlink/reflector/svxreflector.cpp +++ b/src/svxlink/reflector/svxreflector.cpp @@ -77,6 +77,8 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "version/SVXREFLECTOR.h" #include "Reflector.h" +#include +#include "RedisStore.h" /**************************************************************************** @@ -144,6 +146,98 @@ namespace { 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(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 " + << std::endl; + } else { + redisReply* r = (redisReply*)redisCommand(ctx, + "HSET %s password %s", gkey.c_str(), pw.c_str()); + if (r) freeReplyObject(r); + } + ++groups; + } + + std::cout << "Imported " << users << " users, " << groups << " groups." + << std::endl; + + if (ctx) redisFree(ctx); + return true; +} + /**************************************************************************** * @@ -388,6 +482,10 @@ int main(int argc, const char *argv[]) stdin_watch->activity.connect(sigc::ptr_fun(&stdinHandler)); } + if (import_to_redis) { + return runImportConfToRedis(cfg, dry_run != 0) ? 0 : 1; + } + Reflector ref; if (ref.initialize(cfg)) { @@ -453,6 +551,10 @@ static void parse_arguments(int argc, const char **argv) "Start " PROGRAM_NAME " as a daemon", NULL}, {"version", 0, POPT_ARG_NONE, &print_version, 0, "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} }; int err; From 11751a08ed845bbdc4aade9733f4aa48d0220c0a Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 09:04:49 +0200 Subject: [PATCH 09/32] TrunkLink reads filters/mutes from Redis when [REDIS] is configured --- src/svxlink/reflector/TrunkLink.cpp | 64 ++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 2ab712d..206ca6f 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -60,6 +60,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "Reflector.h" #include "TGHandler.h" #include "ReflectorClient.h" +#include "RedisStore.h" #include @@ -1098,35 +1099,58 @@ void TrunkLink::reloadConfig(void) m_tg_map_in.clear(); m_tg_map_out.clear(); + RedisStore* rs = m_reflector->redisStore(); + std::string blacklist_str; - if (m_cfg.getValue(m_section, "BLACKLIST_TGS", blacklist_str) - && !blacklist_str.empty()) + if (rs) { + 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); } 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); } - std::string tgmap_str; - if (m_cfg.getValue(m_section, "TG_MAP", tgmap_str) && !tgmap_str.empty()) - { - std::istringstream ms(tgmap_str); - std::string pair; - while (std::getline(ms, pair, ',')) - { - auto colon = pair.find(':'); - if (colon == std::string::npos) continue; - try { - 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 */ } + if (rs) { + auto tgmap = rs->loadTrunkTgMap(m_section); + for (auto& kv : tgmap) { + m_tg_map_in[kv.first] = kv.second; + m_tg_map_out[kv.second] = kv.first; } + } else { + std::string tgmap_str; + if (m_cfg.getValue(m_section, "TG_MAP", tgmap_str) && !tgmap_str.empty()) + { + std::istringstream ms(tgmap_str); + std::string pair; + while (std::getline(ms, pair, ',')) + { + auto colon = pair.find(':'); + if (colon == std::string::npos) continue; + try { + 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 */ } + } + } + } + + if (rs) { + m_muted_callsigns = rs->loadTrunkMutes(m_section); } cout << m_section << ": Reloaded filters" @@ -1134,7 +1158,9 @@ void TrunkLink::reloadConfig(void) " blacklist=" + m_blacklist_filter.toString()) << (m_allow_filter.empty() ? "" : " allow=" + m_allow_filter.toString()) - << " tg_map_entries=" << m_tg_map_in.size() << endl; + << " tg_map_entries=" << m_tg_map_in.size(); + if (rs) cout << " mutes=" << m_muted_callsigns.size(); + cout << endl; } /* TrunkLink::reloadConfig */ From 97ebdeb172f23f7a2aa4830605a1e86af64bdff7 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 09:06:35 +0200 Subject: [PATCH 10/32] Cluster TGs sourced from Redis when enabled; reload on pub/sub --- src/svxlink/reflector/Reflector.cpp | 58 ++++++++++++++++------------- 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 2fbd97a..f0ae336 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -471,31 +471,7 @@ bool Reflector::initialize(Async::Config &cfg) m_cfg->valueUpdated.connect(sigc::mem_fun(*this, &Reflector::cfgUpdated)); // Parse CLUSTER_TGS — comma-separated list of TG numbers broadcast to all peers - std::string cluster_tgs_str; - 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(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; - } - } + reloadClusterTgs(); // Satellite mode: connect to parent instead of joining the trunk mesh std::string satellite_of; @@ -2732,7 +2708,37 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, void Reflector::reloadClusterTgs(void) { - // Stub — populated by Task C2 (Cluster TGs from Redis). + 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(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; + } } From 2fc63fc6f3dda59dcc98a7edfd7d60a283d5a880 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 09:09:15 +0200 Subject: [PATCH 11/32] Extend --import-conf-to-redis to cluster TGs and trunk filters Imports CLUSTER_TGS from [GLOBAL] into Redis set cluster:tgs, and per-[TRUNK_*] BLACKLIST_TGS/ALLOW_TGS into sets and TG_MAP into a hash. Summary line updated with cluster_n and trunks_n counters. --- src/svxlink/reflector/svxreflector.cpp | 86 +++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/src/svxlink/reflector/svxreflector.cpp b/src/svxlink/reflector/svxreflector.cpp index c47ad0e..395d8c2 100644 --- a/src/svxlink/reflector/svxreflector.cpp +++ b/src/svxlink/reflector/svxreflector.cpp @@ -231,7 +231,91 @@ static bool runImportConfToRedis(Async::Config& cfg, bool dry_run) ++groups; } - std::cout << "Imported " << users << " users, " << groups << " 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 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" + + 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); From 92c2a949402d4335fa6e28263491fdcfbafc3bc8 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 09:10:40 +0200 Subject: [PATCH 12/32] Persist PTY MUTE/UNMUTE to Redis when [REDIS] is configured --- src/svxlink/reflector/Reflector.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index f0ae336..c82f6d5 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -2014,6 +2014,13 @@ void Reflector::ctrlPtyDataReceived(const void *buf, size_t count) } if (subcmd == "MUTE") link->muteCallsign(callsign); else link->unmuteCallsign(callsign); + + if (m_redis) { + if (subcmd == "MUTE") m_redis->addTrunkMute(section, callsign); + else m_redis->removeTrunkMute(section, callsign); + m_redis->publishConfigChanged("trunk:" + section); + } + m_cmd_pty->write(section + ": " + subcmd + " " + callsign + "\n"); } else if (subcmd == "RELOAD") From 8363e36f6ab807dea717bee6c6cf7f150b5f089e Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 09:21:01 +0200 Subject: [PATCH 13/32] Add bounded in-memory queue for live-state Redis writes --- src/svxlink/reflector/CMakeLists.txt | 2 +- src/svxlink/reflector/RedisLiveQueue.cpp | 22 +++++++++++++ src/svxlink/reflector/RedisLiveQueue.h | 40 ++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 src/svxlink/reflector/RedisLiveQueue.cpp create mode 100644 src/svxlink/reflector/RedisLiveQueue.h diff --git a/src/svxlink/reflector/CMakeLists.txt b/src/svxlink/reflector/CMakeLists.txt index 775ed0f..fb6df21 100644 --- a/src/svxlink/reflector/CMakeLists.txt +++ b/src/svxlink/reflector/CMakeLists.txt @@ -36,7 +36,7 @@ set(LIBS asynccpp asyncaudio asynccore svxmisc ${LIBS}) add_executable(svxreflector svxreflector.cpp Reflector.cpp ReflectorClient.cpp TGHandler.cpp TrunkLink.cpp SatelliteLink.cpp SatelliteClient.cpp MqttPublisher.cpp RedisStore.cpp - RedisAsyncAdapter.cpp + RedisAsyncAdapter.cpp RedisLiveQueue.cpp ) target_link_libraries(svxreflector ${LIBS}) set_target_properties(svxreflector PROPERTIES diff --git a/src/svxlink/reflector/RedisLiveQueue.cpp b/src/svxlink/reflector/RedisLiveQueue.cpp new file mode 100644 index 0000000..1354623 --- /dev/null +++ b/src/svxlink/reflector/RedisLiveQueue.cpp @@ -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& 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; +} diff --git a/src/svxlink/reflector/RedisLiveQueue.h b/src/svxlink/reflector/RedisLiveQueue.h new file mode 100644 index 0000000..aeb082a --- /dev/null +++ b/src/svxlink/reflector/RedisLiveQueue.h @@ -0,0 +1,40 @@ +#ifndef REDIS_LIVE_QUEUE_INCLUDED +#define REDIS_LIVE_QUEUE_INCLUDED + +#include +#include +#include +#include +#include + +class RedisLiveQueue +{ + public: + enum class OpType { HSET, DEL, EXPIRE }; + + struct Op { + OpType op; + std::string key; + std::vector> 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& out); + + uint64_t droppedCount(void) const { return m_dropped; } + size_t size(void) const { return m_q.size(); } + + private: + std::deque m_q; + size_t m_max; + uint64_t m_dropped = 0; +}; + +#endif /* REDIS_LIVE_QUEUE_INCLUDED */ From 97467a4f7082543c325f16aff256a64749956cb5 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 09:25:07 +0200 Subject: [PATCH 14/32] Push live-state events through queued drain to Redis --- src/svxlink/reflector/RedisStore.cpp | 132 +++++++++++++++++++++++++-- src/svxlink/reflector/Reflector.cpp | 28 ++++++ 2 files changed, 150 insertions(+), 10 deletions(-) diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp index 546a0fb..09786d2 100644 --- a/src/svxlink/reflector/RedisStore.cpp +++ b/src/svxlink/reflector/RedisStore.cpp @@ -2,7 +2,10 @@ #include #include #include "RedisAsyncAdapter.h" +#include +#include "RedisLiveQueue.h" #include +#include namespace { @@ -26,7 +29,10 @@ void onAsyncDisconnectThunk(const redisAsyncContext* ac, int status) { RedisStore::RedisStore(const Config& cfg) : m_cfg(cfg) {} RedisStore::~RedisStore() { - if (m_sync) { redisFree(m_sync); m_sync = nullptr; } + delete m_drain_timer; m_drain_timer = nullptr; + delete m_live_queue; m_live_queue = nullptr; + if (m_async) { redisAsyncFree(m_async); m_async = nullptr; } + if (m_sync) { redisFree(m_sync); m_sync = nullptr; } } bool RedisStore::connectSync(void) { @@ -69,6 +75,12 @@ bool RedisStore::connect(void) { if (!connectSync()) return false; if (!connectAsync()) return false; subscribe(); + + 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)); + std::cout << "RedisStore: connected sync+async, subscribed to " << channelName() << std::endl; return true; @@ -208,15 +220,74 @@ void RedisStore::publishConfigChanged(const std::string& scope) { if (r) freeReplyObject(r); } -void RedisStore::pushLiveTalker(uint32_t, const std::string&, const std::string&) {} -void RedisStore::clearLiveTalker(uint32_t) {} -void RedisStore::pushLiveClient(const std::string&, const std::string&, - const std::string&, uint32_t) {} -void RedisStore::clearLiveClient(const std::string&) {} -void RedisStore::pushLiveTrunk(const std::string&, const std::string&, - const std::string&) {} +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)); + 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)); +} -size_t RedisStore::liveQueueSize(void) const { return 0; } +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_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); + 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_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); + 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()) { @@ -255,7 +326,48 @@ void RedisStore::subscribe(void) { void RedisStore::scheduleReconnect(void) {} void RedisStore::onAsyncDisconnect(int) {} void RedisStore::onPubSubMessage(const std::string&, const std::string&) {} -void RedisStore::drainLiveQueue(Async::Timer*) {} +void RedisStore::drainLiveQueue(Async::Timer*) { + if (!m_async || !m_live_queue) return; + std::vector ops; + m_live_queue->drain(ops); + if (ops.empty()) return; + + for (auto& op : ops) { + switch (op.op) { + case RedisLiveQueue::OpType::HSET: { + std::vector argv; + std::vector 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, nullptr, nullptr, + static_cast(argv.size()), + argv.data(), argl.data()); + if (op.ttl_s > 0) { + redisAsyncCommand(m_async, nullptr, nullptr, + "EXPIRE %s %d", op.key.c_str(), op.ttl_s); + } + break; + } + case RedisLiveQueue::OpType::DEL: + redisAsyncCommand(m_async, nullptr, nullptr, + "DEL %s", op.key.c_str()); + break; + case RedisLiveQueue::OpType::EXPIRE: + redisAsyncCommand(m_async, 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, nullptr, nullptr, + "PUBLISH %s tick", ch.c_str()); +} void RedisStore::refreshLiveExpire(Async::Timer*) {} std::string RedisStore::keyFor(const std::string& suffix) const { diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index c82f6d5..1613b79 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -1081,6 +1081,10 @@ void Reflector::clientDisconnected(Async::FramedTcpConnection *con, { m_mqtt->onClientDisconnected(client->callsign()); } + if (m_redis != nullptr) + { + m_redis->clearLiveClient(client->callsign()); + } scheduleNodeListUpdate(); } //Application::app().runTask([=]{ delete client; }); @@ -1546,6 +1550,10 @@ void Reflector::onTalkerUpdated(uint32_t tg, ReflectorClient* old_talker, { m_mqtt->onTalkerStop(tg, old_talker->callsign(), false); } + if (m_redis != nullptr) + { + m_redis->clearLiveTalker(tg); + } } if (new_talker != 0) { @@ -1565,6 +1573,10 @@ void Reflector::onTalkerUpdated(uint32_t tg, ReflectorClient* old_talker, { 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 @@ -2682,6 +2694,10 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, { m_mqtt->onTalkerStop(tg, old_cs, true); } + if (m_redis != nullptr) + { + m_redis->clearLiveTalker(tg); + } } if (!new_cs.empty()) { @@ -2696,6 +2712,10 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, { 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 @@ -2785,6 +2805,10 @@ void Reflector::onClientAuthenticated(const std::string& callsign, { m_mqtt->onClientConnected(callsign, tg, ip); } + if (m_redis != nullptr) + { + m_redis->pushLiveClient(callsign, ip, "", tg); + } scheduleNodeListUpdate(); } /* Reflector::onClientAuthenticated */ @@ -2851,6 +2875,10 @@ void Reflector::onTrunkStateChanged(const std::string& section, m_mqtt->onTrunkDown(topic_id, direction); } } + if (m_redis != nullptr) + { + m_redis->pushLiveTrunk(section, up ? "up" : "down", peer_id); + } } /* Reflector::onTrunkStateChanged */ From d0b8a44dc706cde6ec57fd48894b8531b8c4ab59 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 09:34:42 +0200 Subject: [PATCH 15/32] Refresh live-state TTLs every 30s; expose Redis metrics in /status --- src/svxlink/reflector/RedisStore.cpp | 21 ++++++++++++++++++++- src/svxlink/reflector/RedisStore.h | 1 + src/svxlink/reflector/Reflector.cpp | 9 +++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp index 09786d2..c7b103f 100644 --- a/src/svxlink/reflector/RedisStore.cpp +++ b/src/svxlink/reflector/RedisStore.cpp @@ -29,6 +29,7 @@ void onAsyncDisconnectThunk(const redisAsyncContext* ac, int status) { RedisStore::RedisStore(const Config& cfg) : m_cfg(cfg) {} RedisStore::~RedisStore() { + 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) { redisAsyncFree(m_async); m_async = nullptr; } @@ -81,6 +82,10 @@ bool RedisStore::connect(void) { 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; @@ -226,6 +231,7 @@ void RedisStore::pushLiveTalker(uint32_t tg, const std::string& callsign, 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))}, @@ -240,6 +246,7 @@ void RedisStore::clearLiveTalker(uint32_t tg) { 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)); } @@ -251,6 +258,7 @@ void RedisStore::pushLiveClient(const std::string& callsign, 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}, @@ -266,6 +274,7 @@ void RedisStore::clearLiveClient(const std::string& callsign) { 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)); } @@ -276,6 +285,7 @@ void RedisStore::pushLiveTrunk(const std::string& section, 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}, @@ -368,7 +378,16 @@ void RedisStore::drainLiveQueue(Async::Timer*) { redisAsyncCommand(m_async, nullptr, nullptr, "PUBLISH %s tick", ch.c_str()); } -void RedisStore::refreshLiveExpire(Async::Timer*) {} +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; diff --git a/src/svxlink/reflector/RedisStore.h b/src/svxlink/reflector/RedisStore.h index 50d0c50..c3f3517 100644 --- a/src/svxlink/reflector/RedisStore.h +++ b/src/svxlink/reflector/RedisStore.h @@ -94,6 +94,7 @@ class RedisStore : public sigc::trackable Async::Timer* m_heartbeat_timer = nullptr; int m_reconnect_backoff_s = 1; uint64_t m_dropped_live_writes = 0; + std::set m_live_keys; bool connectSync(void); bool connectAsync(void); diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 1613b79..28ef084 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -1763,6 +1763,15 @@ void Reflector::refreshStatus(void) m_status["satellite_server"] = sat_srv; } } + if (m_redis != nullptr) + { + Json::Value redis_status(Json::objectValue); + redis_status["live_queue_size"] = + static_cast(m_redis->liveQueueSize()); + redis_status["dropped_live_writes"] = + static_cast(m_redis->droppedLiveWrites()); + m_status["redis"] = redis_status; + } } /* Reflector::refreshStatus */ From 2981361c6d922c487c8fe9d48fe4944abde326da Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 09:47:04 +0200 Subject: [PATCH 16/32] Redis: reconnect with exponential backoff and full reload on resume --- src/svxlink/reflector/RedisStore.cpp | 40 ++++++++++++++++++++++++++-- src/svxlink/reflector/RedisStore.h | 1 + 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp index c7b103f..5fe483d 100644 --- a/src/svxlink/reflector/RedisStore.cpp +++ b/src/svxlink/reflector/RedisStore.cpp @@ -29,6 +29,8 @@ void onAsyncDisconnectThunk(const redisAsyncContext* ac, int status) { 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; @@ -333,8 +335,42 @@ void RedisStore::subscribe(void) { redisAsyncCommand(m_async, onPubSubMessageThunk, this, "SUBSCRIBE %s", ch.c_str()); } -void RedisStore::scheduleReconnect(void) {} -void RedisStore::onAsyncDisconnect(int) {} +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::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; + if (connectAsync()) { + 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"); + } else { + m_reconnect_backoff_s = std::min(m_reconnect_backoff_s * 2, 30); + scheduleReconnect(); + } + }); +} void RedisStore::onPubSubMessage(const std::string&, const std::string&) {} void RedisStore::drainLiveQueue(Async::Timer*) { if (!m_async || !m_live_queue) return; diff --git a/src/svxlink/reflector/RedisStore.h b/src/svxlink/reflector/RedisStore.h index c3f3517..1f8d8b7 100644 --- a/src/svxlink/reflector/RedisStore.h +++ b/src/svxlink/reflector/RedisStore.h @@ -93,6 +93,7 @@ class RedisStore : public sigc::trackable 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 m_live_keys; From b16653e4df4c6eaf02ac1ae0d131c67d8124629f Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 10:54:02 +0200 Subject: [PATCH 17/32] Test harness: add redis service + per-reflector redis flag (infra only) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - topology.py: add REDIS constants and redis_db_index() helper; support a 'redis' key in REFLECTORS entries (default off — not flipped for any reflector here). - generate_configs.py: emit [REDIS] section per reflector when flagged, add redis:7-alpine service to docker-compose when any reflector is flagged, add depends_on for redis-enabled reflectors. No reflector has 'redis: True' set; regenerated configs match master byte-for-byte. Later tests (F2+) will flip the flag selectively and handle Redis population via --import-conf-to-redis. --- tests/generate_configs.py | 35 ++++++++++++++++++++++++++++++++++- tests/topology.py | 13 ++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/tests/generate_configs.py b/tests/generate_configs.py index b4d20da..bffbf7f 100644 --- a/tests/generate_configs.py +++ b/tests/generate_configs.py @@ -109,6 +109,16 @@ def generate_reflector_conf(name: str) -> str: lines.append(f"MQTT_NAME={T.MQTT_NAMES[name]}") 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) @@ -133,6 +143,13 @@ def generate_docker_compose() -> str: sat_port = T.mapped_satellite_port(name) 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}: build: context: .. @@ -151,7 +168,7 @@ def generate_docker_compose() -> str: timeout: 2s retries: 15 networks: - - trunk_mesh""") + - trunk_mesh{depends_on_line}""") # Mosquitto broker for MQTT testing services.append(""" mosquitto: @@ -167,6 +184,22 @@ def generate_docker_compose() -> str: networks: - 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) volumes_block = "\n".join(f" {v}:" for v in volumes) diff --git a/tests/topology.py b/tests/topology.py index e1da69b..38aaea4 100644 --- a/tests/topology.py +++ b/tests/topology.py @@ -10,7 +10,7 @@ to regenerate configs/ and docker-compose.test.yml. The test harness # --------------------------------------------------------------------------- REFLECTORS = { - # name prefixes (list) host-port-base + # name prefixes (list) host-port-base redis "a": {"prefix": ["122"], "trunk_port_base": 15000}, "b": {"prefix": ["121"], "trunk_port_base": 25000}, "c": {"prefix": ["1"], "trunk_port_base": 35000}, @@ -61,6 +61,17 @@ SATELLITE = { "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 = { "host": "mosquitto", From 363648ae43347ec20b4e5c22c259c234dcf3fe31 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 11:03:09 +0200 Subject: [PATCH 18/32] Add Redis test harness and user add/disable integration tests Parallel harness (topology_redis.py, generate_redis_configs.py, docker-compose.redis.yml, run_redis_tests.sh) runs on port range 45xxx without conflicting with the legacy test stack. test_redis.py adds two integration tests: user add+auth and user disable rejection, both using the existing ClientPeer V2 auth from test_trunk.py. --- .gitignore | 4 ++ tests/generate_redis_configs.py | 116 ++++++++++++++++++++++++++++++++ tests/run_redis_tests.sh | 18 +++++ tests/test_redis.py | 107 +++++++++++++++++++++++++++++ tests/topology_redis.py | 42 ++++++++++++ 5 files changed, 287 insertions(+) create mode 100755 tests/generate_redis_configs.py create mode 100755 tests/run_redis_tests.sh create mode 100755 tests/test_redis.py create mode 100644 tests/topology_redis.py diff --git a/.gitignore b/.gitignore index ab5ab4a..5689a01 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,10 @@ tests/configs/ tests/docker-compose.test.yml tests/__pycache__/ +# Redis test generated files (regenerated by tests/generate_redis_configs.py) +tests/configs-redis/ +tests/docker-compose.redis.yml + # Editor and IDE .vscode/ .idea/ diff --git a/tests/generate_redis_configs.py b/tests/generate_redis_configs.py new file mode 100755 index 0000000..0e4f361 --- /dev/null +++ b/tests/generate_redis_configs.py @@ -0,0 +1,116 @@ +#!/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}", + "", + "[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)}", + "", + ] + 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() diff --git a/tests/run_redis_tests.sh b/tests/run_redis_tests.sh new file mode 100755 index 0000000..d9e1d8f --- /dev/null +++ b/tests/run_redis_tests.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" + +cleanup() { + echo "=== Tearing down Redis test environment ===" + docker compose -f docker-compose.redis.yml down -v --remove-orphans 2>/dev/null +} +trap cleanup EXIT + +echo "=== Generating Redis-test configs from topology_redis.py ===" +python3 generate_redis_configs.py + +echo "=== Building and starting Redis test stack ===" +docker compose -f docker-compose.redis.yml up -d --build --wait + +echo "=== Running Redis integration tests ===" +python3 test_redis.py diff --git a/tests/test_redis.py b/tests/test_redis.py new file mode 100755 index 0000000..56354ed --- /dev/null +++ b/tests/test_redis.py @@ -0,0 +1,107 @@ +#!/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 + + +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") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/topology_redis.py b/tests/topology_redis.py new file mode 100644 index 0000000..a39e2db --- /dev/null +++ b/tests/topology_redis.py @@ -0,0 +1,42 @@ +"""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"}, +] + +# 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) From ce305e957e6812934b193933afa8c7a5431311c1 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 11:06:51 +0200 Subject: [PATCH 19/32] Test: verify trunk filter reload via Redis pub/sub Add [TRUNK_TEST] placeholder trunk section to the Redis test topology so TrunkLink::reloadConfig() is instantiated. Add RedisTrunkFilterTest with two tests that SADD/SREM blacklist and allow entries, publish config.changed, and assert the expected 'Reloaded filters' log line appears in container stdout within 3 s. --- tests/generate_redis_configs.py | 6 +++ tests/test_redis.py | 71 +++++++++++++++++++++++++++++++++ tests/topology_redis.py | 11 +++++ 3 files changed, 88 insertions(+) diff --git a/tests/generate_redis_configs.py b/tests/generate_redis_configs.py index 0e4f361..29a2395 100755 --- a/tests/generate_redis_configs.py +++ b/tests/generate_redis_configs.py @@ -31,6 +31,12 @@ def generate_reflector_conf(name: str) -> str: 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) diff --git a/tests/test_redis.py b/tests/test_redis.py index 56354ed..d0b787e 100755 --- a/tests/test_redis.py +++ b/tests/test_redis.py @@ -71,6 +71,21 @@ def try_authenticate(callsign: str, password: str, 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() @@ -103,5 +118,61 @@ class RedisUsersTest(unittest.TestCase): "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) + + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/topology_redis.py b/tests/topology_redis.py index a39e2db..c321b51 100644 --- a/tests/topology_redis.py +++ b/tests/topology_redis.py @@ -20,6 +20,17 @@ TEST_CLIENTS = [ {"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 From 685696b6b25f08c35da15d878f55949d29daf52a Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 11:09:47 +0200 Subject: [PATCH 20/32] Test: PTY MUTE/UNMUTE persists to Redis --- tests/generate_redis_configs.py | 1 + tests/test_redis.py | 47 +++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/tests/generate_redis_configs.py b/tests/generate_redis_configs.py index 29a2395..2f1bda9 100755 --- a/tests/generate_redis_configs.py +++ b/tests/generate_redis_configs.py @@ -18,6 +18,7 @@ def generate_reflector_conf(name: str) -> str: "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)}", diff --git a/tests/test_redis.py b/tests/test_redis.py index d0b787e..69a2f2c 100755 --- a/tests/test_redis.py +++ b/tests/test_redis.py @@ -174,5 +174,52 @@ class RedisTrunkFilterTest(unittest.TestCase): self.assertIn("TRUNK_TEST", line) +class RedisPtyMuteTest(unittest.TestCase): + SECTION = "TRUNK_TEST" + + def setUp(self): + flushdb() + + def _pty_send(self, command: str) -> None: + """Write a command line to the reflector's PTY inside the + container. The existing COMMAND_PTY config lives at + /dev/shm/reflector_ctrl.""" + subprocess.run([ + "docker", "compose", "-f", "docker-compose.redis.yml", + "exec", "-T", R1_SVC, + "bash", "-c", + f"printf '{command}\\n' > /dev/shm/reflector_ctrl" + ], check=True, + cwd=os.path.dirname(os.path.abspath(__file__))) + + def _wait_for_members(self, key: str, expected_cs: str, present: bool, + timeout: float = 3.0) -> None: + deadline = time.time() + timeout + last = "" + while time.time() < deadline: + last = redis_cli("SMEMBERS", key) + members = set(filter(None, last.splitlines())) + if present and expected_cs in members: + return + if (not present) and expected_cs not in members: + return + time.sleep(0.1) + self.fail( + f"Timed out waiting for {expected_cs} " + f"{'in' if present else 'absent from'} {key}. " + f"Last SMEMBERS: {last!r}") + + def test_pty_mute_then_unmute_persists_to_redis(self): + key = k(f"trunk:{self.SECTION}:mutes") + # Baseline: empty + self.assertEqual(redis_cli("SMEMBERS", key), "") + + self._pty_send(f"TRUNK MUTE {self.SECTION} SM0XYZ") + self._wait_for_members(key, "SM0XYZ", present=True) + + self._pty_send(f"TRUNK UNMUTE {self.SECTION} SM0XYZ") + self._wait_for_members(key, "SM0XYZ", present=False) + + if __name__ == "__main__": unittest.main(verbosity=2) From 9ce6211b03c3441c17624e1620eafdd3f81177e4 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 11:54:48 +0200 Subject: [PATCH 21/32] Test: live:client hash appears/disappears on V2 auth/disconnect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add RedisLiveStateTest (2 tests) to test_redis.py verifying that live:client: hashes appear in Redis on V2 client auth and are deleted on disconnect. Fix a pre-existing bug in RedisStore where drainLiveQueue() sent HSET/ DEL/EXPIRE commands on m_async — the same hiredis context used for SUBSCRIBE. Redis rejects non-pub/sub commands on a subscribed connection, causing the repeated "async disconnect" loop seen in logs. Add a second async context m_async_write exclusively for live-state writes; the sub context m_async is now used only for SUBSCRIBE/config.changed delivery. All 7 Redis integration tests pass. --- src/svxlink/reflector/RedisStore.cpp | 94 +++++++++++++++++++++------- src/svxlink/reflector/RedisStore.h | 5 +- tests/test_redis.py | 69 ++++++++++++++++++++ 3 files changed, 145 insertions(+), 23 deletions(-) diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp index 5fe483d..3c854cb 100644 --- a/src/svxlink/reflector/RedisStore.cpp +++ b/src/svxlink/reflector/RedisStore.cpp @@ -25,6 +25,11 @@ void onAsyncDisconnectThunk(const redisAsyncContext* ac, int status) { if (self) self->onAsyncDisconnect(status); } +void onAsyncWriteDisconnectThunk(const redisAsyncContext* ac, int status) { + auto* self = static_cast(ac->data); + if (self) self->onAsyncWriteDisconnect(status); +} + } // namespace RedisStore::RedisStore(const Config& cfg) : m_cfg(cfg) {} @@ -34,6 +39,7 @@ RedisStore::~RedisStore() { 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; } } @@ -78,6 +84,7 @@ 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); @@ -329,6 +336,35 @@ bool RedisStore::connectAsync(void) { 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(); @@ -343,6 +379,13 @@ void RedisStore::onAsyncDisconnect(int /*status*/) { 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; @@ -350,30 +393,37 @@ void RedisStore::scheduleReconnect(void) { Async::Timer::TYPE_ONESHOT); m_reconnect_timer->expired.connect([this](Async::Timer*) { if (m_shutting_down) return; - if (connectAsync()) { - 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"); - } else { + // 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 || !m_live_queue) return; + if (!m_async_write || !m_live_queue) return; std::vector ops; m_live_queue->drain(ops); if (ops.empty()) return; @@ -389,21 +439,21 @@ void RedisStore::drainLiveQueue(Async::Timer*) { 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, nullptr, nullptr, + redisAsyncCommandArgv(m_async_write, nullptr, nullptr, static_cast(argv.size()), argv.data(), argl.data()); if (op.ttl_s > 0) { - redisAsyncCommand(m_async, nullptr, nullptr, + redisAsyncCommand(m_async_write, nullptr, nullptr, "EXPIRE %s %d", op.key.c_str(), op.ttl_s); } break; } case RedisLiveQueue::OpType::DEL: - redisAsyncCommand(m_async, nullptr, nullptr, + redisAsyncCommand(m_async_write, nullptr, nullptr, "DEL %s", op.key.c_str()); break; case RedisLiveQueue::OpType::EXPIRE: - redisAsyncCommand(m_async, nullptr, nullptr, + redisAsyncCommand(m_async_write, nullptr, nullptr, "EXPIRE %s %d", op.key.c_str(), op.ttl_s); break; } @@ -411,7 +461,7 @@ void RedisStore::drainLiveQueue(Async::Timer*) { // Notify dashboards once per drain cycle. std::string ch = keyFor("live.changed"); - redisAsyncCommand(m_async, nullptr, nullptr, + redisAsyncCommand(m_async_write, nullptr, nullptr, "PUBLISH %s tick", ch.c_str()); } void RedisStore::refreshLiveExpire(Async::Timer*) { diff --git a/src/svxlink/reflector/RedisStore.h b/src/svxlink/reflector/RedisStore.h index 1f8d8b7..655668a 100644 --- a/src/svxlink/reflector/RedisStore.h +++ b/src/svxlink/reflector/RedisStore.h @@ -82,11 +82,13 @@ class RedisStore : public sigc::trackable 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; + 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; @@ -99,6 +101,7 @@ class RedisStore : public sigc::trackable 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); diff --git a/tests/test_redis.py b/tests/test_redis.py index 69a2f2c..83bd40b 100755 --- a/tests/test_redis.py +++ b/tests/test_redis.py @@ -221,5 +221,74 @@ class RedisPtyMuteTest(unittest.TestCase): self._wait_for_members(key, "SM0XYZ", present=False) +class RedisLiveStateTest(unittest.TestCase): + """Verify live:client: 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) + + if __name__ == "__main__": unittest.main(verbosity=2) From 6036f4903a4f34ce5d683fc784b8076180f8109e Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 13:04:01 +0200 Subject: [PATCH 22/32] Test: reflector survives Redis outage and resyncs on restore Adds RedisOutageTest: stops Redis mid-session, verifies the existing V2 client connection stays alive, then confirms the reflector logs config.changed: all after reconnect and that post-recovery user writes take effect. Fixed callsign N0OTHR to satisfy the reflector's default ACCEPT_CALLSIGN regex (N0OTHER is 7 chars and fails the pattern). --- tests/test_redis.py | 91 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/tests/test_redis.py b/tests/test_redis.py index 83bd40b..aa3347f 100755 --- a/tests/test_redis.py +++ b/tests/test_redis.py @@ -290,5 +290,96 @@ class RedisLiveStateTest(unittest.TestCase): 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 + + if __name__ == "__main__": unittest.main(verbosity=2) From a7cd1909f9e62e858b48b84488445121edbb9845 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 13:06:30 +0200 Subject: [PATCH 23/32] Test: --import-conf-to-redis is idempotent --- tests/test_redis.py | 124 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) diff --git a/tests/test_redis.py b/tests/test_redis.py index aa3347f..c68cf6f 100755 --- a/tests/test_redis.py +++ b/tests/test_redis.py @@ -381,5 +381,129 @@ class RedisOutageTest(unittest.TestCase): 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") + + if __name__ == "__main__": unittest.main(verbosity=2) From 276aedc3e1414e52f4c234ceddfbe776a5d8905a Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 13:14:50 +0200 Subject: [PATCH 24/32] Document Redis-backed config store --- README.md | 2 + docs/REDIS.md | 467 +++++++++++++++++++++ src/svxlink/reflector/svxreflector.conf.in | 19 + 3 files changed, 488 insertions(+) create mode 100644 docs/REDIS.md diff --git a/README.md b/README.md index 3e8b153..726b26a 100644 --- a/README.md +++ b/README.md @@ -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) - [`docs/MQTT.md`](docs/MQTT.md) — MQTT publishing: topic structure, payload 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 MQTT events via Telegram, SMS, Discord, webhooks, dashboards, and more - [`docs/DESIGN_SATELLITE_AND_CLUSTER.md`](docs/DESIGN_SATELLITE_AND_CLUSTER.md) — design diff --git a/docs/REDIS.md b/docs/REDIS.md new file mode 100644 index 0000000..28cabdc --- /dev/null +++ b/docs/REDIS.md @@ -0,0 +1,467 @@ +# 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, mute lists). 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 `:` | +| `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` +- Per-trunk mute lists + +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 `:` when `KEY_PREFIX` is +set. + +### Configuration keys (dashboard writes, reflector reads) + +| Key | Redis type | Contents | +|-----|-----------|----------| +| `user:` | HASH | `{ group, enabled }` | +| `group:` | HASH | `{ password }` | +| `cluster:tgs` | SET | TG numbers as decimal strings | +| `trunk:
:blacklist` | SET | TG patterns: exact (`666`), prefix (`24*`), range (`100-199`) | +| `trunk:
:allow` | SET | Same syntax as blacklist | +| `trunk:
:tgmap` | HASH | `{ peer_tg: local_tg }` decimal string pairs | +| `trunk:
:mutes` | SET | Callsigns currently muted on this trunk | + +`
` 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:` | HASH | `{ callsign, started_at, source }` | +| `live:client:` | HASH | `{ connected_at, ip, codecs, tg }` | +| `live:trunk:
` | 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:
` | 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 -a ` +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 +redis-cli SMEMBERS trunk:TRUNK_1_2:mutes +``` + +### Per-trunk mute lists + +**Mute a callsign on a trunk:** +```bash +redis-cli SADD trunk:TRUNK_1_2:mutes ON4ABC +redis-cli PUBLISH config.changed trunk:TRUNK_1_2 +``` + +**Unmute:** +```bash +redis-cli SREM trunk:TRUNK_1_2:mutes ON4ABC +redis-cli PUBLISH config.changed trunk:TRUNK_1_2 +``` + +Note: the PTY command `TRUNK MUTE TRUNK_1_2 ON4ABC` also persists to +`trunk:TRUNK_1_2:mutes` and publishes `config.changed trunk:TRUNK_1_2` +automatically. Either channel (dashboard or PTY) keeps the other in sync. + +--- + +## 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 ` 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:` hashes | +| `[PASSWORDS]` entries | `group:` hashes | +| `CLUSTER_TGS` | `cluster:tgs` set | +| `BLACKLIST_TGS` per `[TRUNK_x]` | `trunk:
:blacklist` sets | +| `ALLOW_TGS` per `[TRUNK_x]` | `trunk:
:allow` sets | +| `TG_MAP` per `[TRUNK_x]` | `trunk:
: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`. + +--- + +## 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. | +| Sync PTY write fails (e.g. mute persistence) | Report error to the operator via PTY. In-memory state is not changed; the PTY command is rejected. | +| 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, mutes them on a trunk, 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. Mute ON4ABC on the trunk link +redis-cli SADD trunk:TRUNK_1_2:mutes ON4ABC +redis-cli PUBLISH config.changed trunk:TRUNK_1_2 +# → (integer) 1 + +# 4. Confirm the mute is stored +redis-cli SMEMBERS trunk:TRUNK_1_2:mutes +# 1) "ON4ABC" + +# 5. Add a cluster TG +redis-cli SADD cluster:tgs 9990 +redis-cli PUBLISH config.changed cluster +# → (integer) 1 + +# 6. 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" + +# 7. 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 +# } + +# 8. Unmute and clean up (optional) +redis-cli SREM trunk:TRUNK_1_2:mutes ON4ABC +redis-cli PUBLISH config.changed trunk:TRUNK_1_2 +``` diff --git a/src/svxlink/reflector/svxreflector.conf.in b/src/svxlink/reflector/svxreflector.conf.in index cefa9ee..a587992 100644 --- a/src/svxlink/reflector/svxreflector.conf.in +++ b/src/svxlink/reflector/svxreflector.conf.in @@ -157,3 +157,22 @@ CERT_CA_HOOK=@SVX_SHARE_INSTALL_DIR@/ca-hook.py #TLS_CLIENT_CERT=/path/to/client.crt #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= + From 525bebdd5af2e1539c6d8ab6bc8dd30c35e9cff0 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 13:32:45 +0200 Subject: [PATCH 25/32] Gitignore an internal workflow docs subdirectory --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 5689a01..32a50c6 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,9 @@ tests/__pycache__/ tests/configs-redis/ tests/docker-compose.redis.yml +# Superpowers workflow artifacts (local only — not for publication) +docs/superpowers/ + # Editor and IDE .vscode/ .idea/ From aed5566956c082c839a1aadbac531995aa15cfd0 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 13:40:44 +0200 Subject: [PATCH 26/32] Split run_redis_tests.sh into up/test/down subcommands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Default 'all' runs the full cycle (CI-friendly). Developers can use 'up' once, 'test' repeatedly as they iterate, 'down' when finished. Dramatically cuts per-iteration overhead — no rebuild or healthcheck wait between test runs. --- tests/run_redis_tests.sh | 61 +++++++++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 10 deletions(-) diff --git a/tests/run_redis_tests.sh b/tests/run_redis_tests.sh index d9e1d8f..6dcdadb 100755 --- a/tests/run_redis_tests.sh +++ b/tests/run_redis_tests.sh @@ -2,17 +2,58 @@ set -euo pipefail cd "$(dirname "$0")" -cleanup() { - echo "=== Tearing down Redis test environment ===" - docker compose -f docker-compose.redis.yml down -v --remove-orphans 2>/dev/null +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 } -trap cleanup EXIT -echo "=== Generating Redis-test configs from topology_redis.py ===" -python3 generate_redis_configs.py +is_stack_up() { + $COMPOSE ps --status=running --services 2>/dev/null | grep -q '^reflector-r1$' +} -echo "=== Building and starting Redis test stack ===" -docker compose -f docker-compose.redis.yml up -d --build --wait +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." +} -echo "=== Running Redis integration tests ===" -python3 test_redis.py +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 From bc412e1847af8c5aa8cd8a0465128e176df6d7c1 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 13:45:00 +0200 Subject: [PATCH 27/32] Remove Redis mute plumbing; expose mute list in /status JSON Dashboard will write mutes directly to the PTY rather than Redis; the Redis addTrunkMute/removeTrunkMute/loadTrunkMutes methods and the PTY write-through were unused. Mute state is now reflected in the /status JSON as a per-trunk 'muted' array so operators and dashboards can see current state without polling Redis. --- src/svxlink/reflector/RedisStore.cpp | 32 ------------------- src/svxlink/reflector/RedisStore.h | 6 ---- src/svxlink/reflector/Reflector.cpp | 6 ---- src/svxlink/reflector/TrunkLink.cpp | 13 ++++---- src/svxlink/reflector/TrunkLink.h | 4 +++ tests/test_redis.py | 47 ---------------------------- 6 files changed, 10 insertions(+), 98 deletions(-) diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp index 3c854cb..eed8d23 100644 --- a/src/svxlink/reflector/RedisStore.cpp +++ b/src/svxlink/reflector/RedisStore.cpp @@ -194,38 +194,6 @@ std::map RedisStore::loadTrunkTgMap(const std::string& secti return out; } -std::set RedisStore::loadTrunkMutes(const std::string& section) { - std::set out; - if (!m_sync) return out; - std::string k = keyFor("trunk:" + section + ":mutes"); - 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) { - out.emplace(r->element[i]->str, r->element[i]->len); - } - } - } - if (r) freeReplyObject(r); - return out; -} - -void RedisStore::addTrunkMute(const std::string& section, const std::string& callsign) { - if (!m_sync) return; - std::string k = keyFor("trunk:" + section + ":mutes"); - redisReply* r = (redisReply*)redisCommand(m_sync, "SADD %s %s", - k.c_str(), callsign.c_str()); - if (r) freeReplyObject(r); -} - -void RedisStore::removeTrunkMute(const std::string& section, const std::string& callsign) { - if (!m_sync) return; - std::string k = keyFor("trunk:" + section + ":mutes"); - redisReply* r = (redisReply*)redisCommand(m_sync, "SREM %s %s", - k.c_str(), callsign.c_str()); - if (r) freeReplyObject(r); -} - void RedisStore::publishConfigChanged(const std::string& scope) { if (!m_sync) return; std::string ch = channelName(); diff --git a/src/svxlink/reflector/RedisStore.h b/src/svxlink/reflector/RedisStore.h index 655668a..67067ae 100644 --- a/src/svxlink/reflector/RedisStore.h +++ b/src/svxlink/reflector/RedisStore.h @@ -56,12 +56,6 @@ class RedisStore : public sigc::trackable std::string loadTrunkFilter(const std::string& section, const std::string& field); // "blacklist"|"allow" std::map loadTrunkTgMap(const std::string& section); - std::set loadTrunkMutes(const std::string& section); - - // Mute set ops (sync, used by PTY persistence). - void addTrunkMute(const std::string& section, const std::string& callsign); - void removeTrunkMute(const std::string& section, const std::string& callsign); - // Publish a config.changed scope token (sync). void publishConfigChanged(const std::string& scope); diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 28ef084..3643c5b 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -2036,12 +2036,6 @@ void Reflector::ctrlPtyDataReceived(const void *buf, size_t count) if (subcmd == "MUTE") link->muteCallsign(callsign); else link->unmuteCallsign(callsign); - if (m_redis) { - if (subcmd == "MUTE") m_redis->addTrunkMute(section, callsign); - else m_redis->removeTrunkMute(section, callsign); - m_redis->publishConfigChanged("trunk:" + section); - } - m_cmd_pty->write(section + ": " + subcmd + " " + callsign + "\n"); } else if (subcmd == "RELOAD") diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 206ca6f..402d50f 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -384,6 +384,10 @@ Json::Value TrunkLink::statusJson(void) const } 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; } /* TrunkLink::statusJson */ @@ -1149,18 +1153,13 @@ void TrunkLink::reloadConfig(void) } } - if (rs) { - m_muted_callsigns = rs->loadTrunkMutes(m_section); - } - cout << m_section << ": Reloaded filters" << (m_blacklist_filter.empty() ? "" : " blacklist=" + m_blacklist_filter.toString()) << (m_allow_filter.empty() ? "" : " allow=" + m_allow_filter.toString()) - << " tg_map_entries=" << m_tg_map_in.size(); - if (rs) cout << " mutes=" << m_muted_callsigns.size(); - cout << endl; + << " tg_map_entries=" << m_tg_map_in.size() + << endl; } /* TrunkLink::reloadConfig */ diff --git a/src/svxlink/reflector/TrunkLink.h b/src/svxlink/reflector/TrunkLink.h index 876639f..87f7bb3 100644 --- a/src/svxlink/reflector/TrunkLink.h +++ b/src/svxlink/reflector/TrunkLink.h @@ -154,6 +154,10 @@ class TrunkLink : public sigc::trackable { return m_muted_callsigns.count(callsign) > 0; } + const std::set& mutedCallsigns(void) const + { + return m_muted_callsigns; + } // Re-parse BLACKLIST_TGS, ALLOW_TGS and TG_MAP from current config void reloadConfig(void); // One-line summary for TRUNK STATUS diff --git a/tests/test_redis.py b/tests/test_redis.py index c68cf6f..1ba0fdc 100755 --- a/tests/test_redis.py +++ b/tests/test_redis.py @@ -174,53 +174,6 @@ class RedisTrunkFilterTest(unittest.TestCase): self.assertIn("TRUNK_TEST", line) -class RedisPtyMuteTest(unittest.TestCase): - SECTION = "TRUNK_TEST" - - def setUp(self): - flushdb() - - def _pty_send(self, command: str) -> None: - """Write a command line to the reflector's PTY inside the - container. The existing COMMAND_PTY config lives at - /dev/shm/reflector_ctrl.""" - subprocess.run([ - "docker", "compose", "-f", "docker-compose.redis.yml", - "exec", "-T", R1_SVC, - "bash", "-c", - f"printf '{command}\\n' > /dev/shm/reflector_ctrl" - ], check=True, - cwd=os.path.dirname(os.path.abspath(__file__))) - - def _wait_for_members(self, key: str, expected_cs: str, present: bool, - timeout: float = 3.0) -> None: - deadline = time.time() + timeout - last = "" - while time.time() < deadline: - last = redis_cli("SMEMBERS", key) - members = set(filter(None, last.splitlines())) - if present and expected_cs in members: - return - if (not present) and expected_cs not in members: - return - time.sleep(0.1) - self.fail( - f"Timed out waiting for {expected_cs} " - f"{'in' if present else 'absent from'} {key}. " - f"Last SMEMBERS: {last!r}") - - def test_pty_mute_then_unmute_persists_to_redis(self): - key = k(f"trunk:{self.SECTION}:mutes") - # Baseline: empty - self.assertEqual(redis_cli("SMEMBERS", key), "") - - self._pty_send(f"TRUNK MUTE {self.SECTION} SM0XYZ") - self._wait_for_members(key, "SM0XYZ", present=True) - - self._pty_send(f"TRUNK UNMUTE {self.SECTION} SM0XYZ") - self._wait_for_members(key, "SM0XYZ", present=False) - - class RedisLiveStateTest(unittest.TestCase): """Verify live:client: hashes appear/disappear as V2 clients connect and disconnect. Talker and trunk live-state are not covered here From 5cab611ccda4b36c4ac98c590de391f2c2186bd9 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 13:48:28 +0200 Subject: [PATCH 28/32] docs: remove Redis mute plumbing references; direct to PTY + /status --- docs/REDIS.md | 55 +++++++++++++-------------------------------------- 1 file changed, 14 insertions(+), 41 deletions(-) diff --git a/docs/REDIS.md b/docs/REDIS.md index 28cabdc..2ab897e 100644 --- a/docs/REDIS.md +++ b/docs/REDIS.md @@ -2,7 +2,7 @@ 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, mute lists). This lets a web dashboard push +(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 @@ -74,7 +74,6 @@ When `[REDIS]` is present, Redis **fully overrides** the following: - `[PASSWORDS]` — password-group → plaintext password - `CLUSTER_TGS` in `[GLOBAL]` - Per-trunk `BLACKLIST_TGS`, `ALLOW_TGS`, `TG_MAP` -- Per-trunk mute lists There is no merging. Entries in `.conf` for these sections are silently ignored. The reflector logs a warning for each overridden section at startup: @@ -104,7 +103,6 @@ set. | `trunk:
:blacklist` | SET | TG patterns: exact (`666`), prefix (`24*`), range (`100-199`) | | `trunk:
:allow` | SET | Same syntax as blacklist | | `trunk:
:tgmap` | HASH | `{ peer_tg: local_tg }` decimal string pairs | -| `trunk:
:mutes` | SET | Callsigns currently muted on this trunk | `
` is the `[TRUNK_x]` section name from `svxreflector.conf` (e.g. `TRUNK_1_2`). @@ -278,26 +276,15 @@ redis-cli PUBLISH config.changed trunk:TRUNK_1_2 redis-cli SMEMBERS trunk:TRUNK_1_2:blacklist redis-cli SMEMBERS trunk:TRUNK_1_2:allow redis-cli HGETALL trunk:TRUNK_1_2:tgmap -redis-cli SMEMBERS trunk:TRUNK_1_2:mutes ``` -### Per-trunk mute lists +### Mute management (not in Redis) -**Mute a callsign on a trunk:** -```bash -redis-cli SADD trunk:TRUNK_1_2:mutes ON4ABC -redis-cli PUBLISH config.changed trunk:TRUNK_1_2 -``` - -**Unmute:** -```bash -redis-cli SREM trunk:TRUNK_1_2:mutes ON4ABC -redis-cli PUBLISH config.changed trunk:TRUNK_1_2 -``` - -Note: the PTY command `TRUNK MUTE TRUNK_1_2 ON4ABC` also persists to -`trunk:TRUNK_1_2:mutes` and publishes `config.changed trunk:TRUNK_1_2` -automatically. Either channel (dashboard or PTY) keeps the other in sync. +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. --- @@ -375,7 +362,6 @@ the `[USERS]`, `[PASSWORDS]`, and `CLUSTER_TGS` entries from `.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. | -| Sync PTY write fails (e.g. mute persistence) | Report error to the operator via PTY. In-memory state is not changed; the PTY command is rejected. | | 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 @@ -415,10 +401,10 @@ capacity that is too small for the load. The audio path is never affected. ## Minimal working example -The following transcript sets up one user, mutes them on a trunk, 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`. +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 @@ -430,21 +416,12 @@ redis-cli PUBLISH config.changed users # 2. Verify the user can now authenticate # (connect a SvxLink node as ON4ABC with password "s3cur3p@ss" — it should succeed) -# 3. Mute ON4ABC on the trunk link -redis-cli SADD trunk:TRUNK_1_2:mutes ON4ABC -redis-cli PUBLISH config.changed trunk:TRUNK_1_2 -# → (integer) 1 - -# 4. Confirm the mute is stored -redis-cli SMEMBERS trunk:TRUNK_1_2:mutes -# 1) "ON4ABC" - -# 5. Add a cluster TG +# 3. Add a cluster TG redis-cli SADD cluster:tgs 9990 redis-cli PUBLISH config.changed cluster # → (integer) 1 -# 6. Start a transmission on TG 9990 from any connected node, then check +# 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" @@ -454,14 +431,10 @@ redis-cli HGETALL live:talker:9990 # 5) "source" # 6) "local" -# 7. Check /status for Redis metrics +# 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 # } - -# 8. Unmute and clean up (optional) -redis-cli SREM trunk:TRUNK_1_2:mutes ON4ABC -redis-cli PUBLISH config.changed trunk:TRUNK_1_2 ``` From 9c6f27e12bd10ed5817e9f4b37679d8be735e11f Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 14:41:18 +0200 Subject: [PATCH 29/32] Load trunk peer definitions from Redis at startup When [REDIS] is configured, Reflector::initialize synthesizes [TRUNK_*] sections from 'trunk:
:peer' hashes before the trunk discovery loop. .conf [TRUNK_*] sections are ignored (with a warning) when Redis is configured. The importer --import-conf-to-redis now also writes peer definitions into 'trunk:
:peer' so existing configs can migrate. --- src/svxlink/reflector/RedisStore.cpp | 59 ++++++++++++++++++++++++++ src/svxlink/reflector/RedisStore.h | 10 +++++ src/svxlink/reflector/Reflector.cpp | 31 ++++++++++++++ src/svxlink/reflector/svxreflector.cpp | 29 +++++++++++++ 4 files changed, 129 insertions(+) diff --git a/src/svxlink/reflector/RedisStore.cpp b/src/svxlink/reflector/RedisStore.cpp index eed8d23..c98da85 100644 --- a/src/svxlink/reflector/RedisStore.cpp +++ b/src/svxlink/reflector/RedisStore.cpp @@ -194,6 +194,65 @@ std::map RedisStore::loadTrunkTgMap(const std::string& secti return out; } +std::map +RedisStore::loadTrunkPeers(void) +{ + std::map 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 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 ":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(); diff --git a/src/svxlink/reflector/RedisStore.h b/src/svxlink/reflector/RedisStore.h index 67067ae..5ac50d6 100644 --- a/src/svxlink/reflector/RedisStore.h +++ b/src/svxlink/reflector/RedisStore.h @@ -32,6 +32,15 @@ class RedisStore : public sigc::trackable 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(); @@ -56,6 +65,7 @@ class RedisStore : public sigc::trackable std::string loadTrunkFilter(const std::string& section, const std::string& field); // "blacklist"|"allow" std::map loadTrunkTgMap(const std::string& section); + std::map loadTrunkPeers(void); // Publish a config.changed scope token (sync). void publishConfigChanged(const std::string& scope); diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 3643c5b..e6c6271 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -2168,6 +2168,37 @@ 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 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); + } + std::cout << "Redis: loaded " << peers.size() << " trunk peer(s)" + << std::endl; + } + // First pass: collect all remote prefixes so we can do longest-prefix-match std::vector trunk_sections; for (const auto& section : m_cfg->listSections()) diff --git a/src/svxlink/reflector/svxreflector.cpp b/src/svxlink/reflector/svxreflector.cpp index 395d8c2..ba09695 100644 --- a/src/svxlink/reflector/svxreflector.cpp +++ b/src/svxlink/reflector/svxreflector.cpp @@ -262,6 +262,35 @@ static bool runImportConfToRedis(Async::Config& cfg, bool dry_run) ++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" ? "" : 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; From 1d639dd0b056d8bb5ae3425bfd8dcd8014e43928 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 15:09:17 +0200 Subject: [PATCH 30/32] Dynamic trunk add/remove via Redis pub/sub Reflector::onRedisConfigChanged now handles 'trunk:
' events by reading the trunk:
:peer hash from Redis: - peer present + no local link -> create new TrunkLink - peer absent + local link -> destroy local TrunkLink (Redis-managed only) - both present -> reload filters (existing behavior) - neither -> log and ignore Tracks which sections were loaded from Redis (m_redis_trunk_sections) so conf-based test trunks (e.g. TRUNK_TEST) correctly fall back to reloadConfig() rather than being destroyed on a filter-change event. Dashboards can now add/remove trunk peers without restarting the reflector. --- src/svxlink/reflector/Reflector.cpp | 109 +++++++++++++++++++++++++++- src/svxlink/reflector/Reflector.h | 4 + 2 files changed, 111 insertions(+), 2 deletions(-) diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index e6c6271..3d0ccf5 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -2194,6 +2194,7 @@ void Reflector::initTrunkLinks(void) 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; @@ -2803,6 +2804,84 @@ void Reflector::reloadClusterTgs(void) } +std::vector Reflector::collectAllTrunkPrefixes(void) const +{ + std::vector 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; @@ -2816,8 +2895,34 @@ void Reflector::onRedisConfigChanged(std::string scope) } if (scope.rfind("trunk:", 0) == 0 || scope == "all") { std::string section = (scope == "all") ? "" : scope.substr(6); - for (auto* link : m_trunk_links) { - if (section.empty() || link->section() == section) link->reloadConfig(); + 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{}; + 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; + } } } } diff --git a/src/svxlink/reflector/Reflector.h b/src/svxlink/reflector/Reflector.h index 2a67ab0..9d40ea2 100644 --- a/src/svxlink/reflector/Reflector.h +++ b/src/svxlink/reflector/Reflector.h @@ -319,6 +319,7 @@ class Reflector : public sigc::trackable Json::Value m_status; std::vector m_trunk_links; + std::set m_redis_trunk_sections; // sections loaded from Redis std::set m_cluster_tgs; bool m_trunk_debug = false; Async::Timer m_nodelist_timer; @@ -368,6 +369,9 @@ class Reflector : public sigc::trackable 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 collectAllTrunkPrefixes(void) const; void refreshStatus(void); void initTrunkLinks(void); void initTrunkServer(void); From 16a98f3562ceb11e8cee0a03d9af08f4da74bf27 Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 15:16:54 +0200 Subject: [PATCH 31/32] Test + document dynamic trunk add/remove via Redis pub/sub Add RedisTrunkAddRemoveTest (2 cases: happy-path add/remove and missing-fields guard) to the Redis integration suite (10 tests total). Update docs/REDIS.md with trunk:peer key schema, override-semantics bullet, cookbook add/remove subsections, and static-vs-Redis note. --- docs/REDIS.md | 44 ++++++++++++++++++++++++++++ tests/test_redis.py | 71 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) diff --git a/docs/REDIS.md b/docs/REDIS.md index 2ab897e..5ee267d 100644 --- a/docs/REDIS.md +++ b/docs/REDIS.md @@ -74,6 +74,7 @@ When `[REDIS]` is present, Redis **fully overrides** the following: - `[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: @@ -100,6 +101,7 @@ set. | `user:` | HASH | `{ group, enabled }` | | `group:` | HASH | `{ password }` | | `cluster:tgs` | SET | TG numbers as decimal strings | +| `trunk:
:peer` | HASH | `{ host, port, secret, remote_prefix, peer_id }` — runtime-addable trunk peer definition | | `trunk:
:blacklist` | SET | TG patterns: exact (`666`), prefix (`24*`), range (`100-199`) | | `trunk:
:allow` | SET | Same syntax as blacklist | | `trunk:
:tgmap` | HASH | `{ peer_tg: local_tg }` decimal string pairs | @@ -278,6 +280,38 @@ 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`), @@ -354,6 +388,16 @@ 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:
` +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 | diff --git a/tests/test_redis.py b/tests/test_redis.py index 1ba0fdc..940fa5f 100755 --- a/tests/test_redis.py +++ b/tests/test_redis.py @@ -458,5 +458,76 @@ TG_MAP=1:2624123,2:2624124 "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) From ba3b1003615dfe7eef29d52b82307c562f5ddceb Mon Sep 17 00:00:00 2001 From: Audric Date: Wed, 15 Apr 2026 15:59:36 +0200 Subject: [PATCH 32/32] Fix 4 pre-existing legacy-test failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three distinct root causes, all pre-existing on master and confirmed there with the same symptoms: 1. tests/generate_configs.py was missing COMMAND_PTY=, so the reflector never opened its admin PTY. Every PTY-driven test (MUTE, UNMUTE, CFG, TRUNK RELOAD) wrote to a regular file that nobody read. Adding the config entry makes those commands actually reach the reflector, fixing test_24_pty_trunk_mute and test_25_pty_trunk_reload. 2. TrunkLink::statusJson built active_talkers by iterating the global trunk-talker map and filtering by isSharedTG(tg), which checks the peer's remote_prefix. When TG_MAP remaps a peer-owned wire TG to a local-owned TG, the local TG no longer matches the peer's prefix, so the view silently dropped it. Iterate m_peer_active_tgs directly instead — that set already contains post-remap local TGs for this specific peer. Fixes test_22_tg_map_remap_in. 3. Python test harness parsed MsgTrunkNodeList vector-length prefixes as u32 ('!I'), but AsyncMsg.h MsgPacker emits u16 lengths. The parser mis-read into garbage at huge offsets and crashed with a struct.error. Switch read_vec_str/u32/f32 to u16 ('!H') to match the wire format. Fixes test_27_node_list_emitted. Legacy suite: 27/27 passing (was 23/27). Redis suite: 10/10 still passing. --- src/svxlink/reflector/TrunkLink.cpp | 14 +++++++++----- tests/generate_configs.py | 1 + tests/test_trunk.py | 8 +++++--- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 402d50f..c874c26 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -372,14 +372,18 @@ Json::Value TrunkLink::statusJson(void) const for (const auto& p : m_remote_prefix) remote_arr.append(p); 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); - const auto& trunk_map = TGHandler::instance()->trunkTalkersSnapshot(); - for (auto& kv : trunk_map) + for (uint32_t tg : m_peer_active_tgs) { - 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; diff --git a/tests/generate_configs.py b/tests/generate_configs.py index bffbf7f..16ffcb4 100644 --- a/tests/generate_configs.py +++ b/tests/generate_configs.py @@ -24,6 +24,7 @@ def generate_reflector_conf(name: str) -> str: f"CLUSTER_TGS={cluster_str}", f"TRUNK_LISTEN_PORT={T.INTERNAL_TRUNK_PORT}", f"HTTP_SRV_PORT={T.INTERNAL_HTTP_PORT}", + "COMMAND_PTY=/dev/shm/reflector_ctrl", "TRUNK_DEBUG=1", "", "[SERVER_CERT]", diff --git a/tests/test_trunk.py b/tests/test_trunk.py index 5dc91e6..a8171d2 100644 --- a/tests/test_trunk.py +++ b/tests/test_trunk.py @@ -205,8 +205,10 @@ def parse_msg(data: bytes): elif msg_type == MSG_TRUNK_NODE_LIST: # vec callsigns, vec tgs, vec lat, vec lon, # vec qth_names. Each vector is u32-prefixed length. + # Vector length prefixes are u16 (MsgPacker in + # AsyncMsg.h uses uint16_t for element counts). 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 = [] for _ in range(n): s, off = unpack_string(data, off) @@ -214,13 +216,13 @@ def parse_msg(data: bytes): return out, 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)) off += 4 * n return out, 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)) off += 4 * n return out, off