diff --git a/src/misc/CMakeLists.txt b/src/misc/CMakeLists.txt index aec5140..46d3493 100644 --- a/src/misc/CMakeLists.txt +++ b/src/misc/CMakeLists.txt @@ -1,6 +1,6 @@ set(LIBNAME svxmisc) -set(EXPINC common.h CppStdCompat.h LogWriter.h) -set(LIBSRC common.cpp LogWriter.cpp) +set(EXPINC common.h CppStdCompat.h LogWriter.h Log.h) +set(LIBSRC common.cpp LogWriter.cpp Log.cpp) # Copy exported include files to the global include directory foreach(incfile ${EXPINC}) diff --git a/src/misc/Log.cpp b/src/misc/Log.cpp new file mode 100644 index 0000000..611a039 --- /dev/null +++ b/src/misc/Log.cpp @@ -0,0 +1,233 @@ +#include "Log.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using geulog::Level; +using geulog::SUBSYSTEMS; +using geulog::NUM_SUBSYSTEMS; + +// Per-subsystem level, indexed by SUBSYSTEMS[] position. Stored as int +// because std::atomic is unconditionally lock-free and portable. +std::array, NUM_SUBSYSTEMS> g_levels; +// Startup snapshot used by reset(). +std::array g_snapshot; + +// Async queue + worker. +std::mutex g_queue_mu; +std::condition_variable g_queue_cv; +std::deque g_queue; +bool g_stop = false; // guarded by g_queue_mu +std::thread g_worker; + +int subIndex(const char* sub) { + for (std::size_t i = 0; i < NUM_SUBSYSTEMS; ++i) { + if (std::strcmp(SUBSYSTEMS[i], sub) == 0) return static_cast(i); + } + return -1; +} + +const char* levelName(Level l) { + switch (l) { + case Level::Trace: return "trace"; + case Level::Debug: return "debug"; + case Level::Info: return "info"; + case Level::Warn: return "warn"; + case Level::Error: return "error"; + case Level::Off: return "off"; + } + return "?"; +} + +bool parseLevel(const std::string& s, Level& out) { + if (s == "trace") { out = Level::Trace; return true; } + if (s == "debug") { out = Level::Debug; return true; } + if (s == "info") { out = Level::Info; return true; } + if (s == "warn") { out = Level::Warn; return true; } + if (s == "error") { out = Level::Error; return true; } + if (s == "off") { out = Level::Off; return true; } + return false; +} + +void trim(std::string& s) { + s.erase(0, s.find_first_not_of(" \t")); + std::size_t e = s.find_last_not_of(" \t\r\n"); + if (e != std::string::npos) s.erase(e + 1); +} + +void workerLoop() { + std::deque local; + for (;;) { + { + std::unique_lock lock(g_queue_mu); + g_queue_cv.wait(lock, []{ return !g_queue.empty() || g_stop; }); + local.swap(g_queue); + if (g_stop && local.empty()) return; + } + for (auto& line : local) { + // Short writes are possible on a pipe; we tolerate the rare + // truncated line rather than introduce a retry loop that could + // block the worker on a stuck consumer. + ::write(STDOUT_FILENO, line.data(), line.size()); + } + local.clear(); + } +} + +void startWorker() { + if (g_worker.joinable()) return; + { + std::lock_guard lock(g_queue_mu); + g_stop = false; + } + g_worker = std::thread(workerLoop); +} + +} // anonymous namespace + +namespace geulog { + +bool shouldLog(const char* sub, Level lvl) { + int idx = subIndex(sub); + if (idx < 0) return false; + return static_cast(lvl) >= + g_levels[idx].load(std::memory_order_relaxed); +} + +namespace detail { + +void enqueue(Level lvl, const char* sub, std::string&& msg) { + std::string line = "["; + line += levelName(lvl); + line += "] ["; + line += sub; + line += "] "; + line += msg; + line += "\n"; + { + std::lock_guard lock(g_queue_mu); + g_queue.push_back(std::move(line)); + } + g_queue_cv.notify_one(); +} + +} // namespace detail + +bool configure(Async::Config& cfg) { + Level default_level = Level::Info; + std::map per_sub; + + std::string spec; + cfg.getValue("GLOBAL", "LOG", spec); + if (!spec.empty()) { + std::stringstream ss(spec); + std::string token; + while (std::getline(ss, token, ',')) { + auto eq = token.find('='); + if (eq == std::string::npos) { + std::cerr << "*** ERROR: LOG config: missing '=' in '" + << token << "'" << std::endl; + return false; + } + std::string key = token.substr(0, eq); + std::string val = token.substr(eq + 1); + trim(key); + trim(val); + Level lvl; + if (!parseLevel(val, lvl)) { + std::cerr << "*** ERROR: LOG config: unknown level '" + << val << "'" << std::endl; + return false; + } + if (key == "*") { + default_level = lvl; + } else if (subIndex(key.c_str()) < 0) { + std::cerr << "*** WARNING: LOG config: unknown subsystem '" + << key << "' ignored" << std::endl; + } else { + per_sub[key] = lvl; + } + } + } + + for (std::size_t i = 0; i < NUM_SUBSYSTEMS; ++i) { + Level lvl = default_level; + auto it = per_sub.find(SUBSYSTEMS[i]); + if (it != per_sub.end()) lvl = it->second; + g_levels[i].store(static_cast(lvl), std::memory_order_relaxed); + g_snapshot[i] = static_cast(lvl); + } + + // TRUNK_DEBUG deprecation warning. + std::string td; + if (cfg.getValue("GLOBAL", "TRUNK_DEBUG", td) && + !td.empty() && td != "0") { + std::cerr << "*** WARNING: TRUNK_DEBUG is obsolete; use " + "LOG=trunk=debug in [GLOBAL] instead" << std::endl; + } + + startWorker(); + return true; +} + +void shutdown() { + { + std::lock_guard lock(g_queue_mu); + g_stop = true; + } + g_queue_cv.notify_all(); + if (g_worker.joinable()) g_worker.join(); +} + +bool setLevel(const std::string& sub, const std::string& lvl_s) { + Level lvl; + if (!parseLevel(lvl_s, lvl)) return false; + if (sub == "*") { setDefaultLevel(lvl_s); return true; } + int idx = subIndex(sub.c_str()); + if (idx < 0) return false; + g_levels[idx].store(static_cast(lvl), std::memory_order_relaxed); + return true; +} + +void setDefaultLevel(const std::string& lvl_s) { + Level lvl; + if (!parseLevel(lvl_s, lvl)) return; + for (auto& a : g_levels) { + a.store(static_cast(lvl), std::memory_order_relaxed); + } +} + +std::string snapshot() { + std::string out; + for (std::size_t i = 0; i < NUM_SUBSYSTEMS; ++i) { + Level lvl = static_cast( + g_levels[i].load(std::memory_order_relaxed)); + out += SUBSYSTEMS[i]; + out += "="; + out += levelName(lvl); + out += "\n"; + } + return out; +} + +void reset() { + for (std::size_t i = 0; i < NUM_SUBSYSTEMS; ++i) { + g_levels[i].store(g_snapshot[i], std::memory_order_relaxed); + } +} + +} // namespace geulog diff --git a/src/misc/Log.h b/src/misc/Log.h new file mode 100644 index 0000000..151fff9 --- /dev/null +++ b/src/misc/Log.h @@ -0,0 +1,92 @@ +#ifndef LOG_INCLUDED +#define LOG_INCLUDED + +#include +#include +#include +#include + +namespace Async { class Config; } + +namespace geulog { + +enum class Level : int { + Trace = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Off = 5 +}; + +// Seven subsystems, matching the design spec. Strings are what sysops +// type in config and PTY commands; the index is how levels are looked +// up on the hot path. +constexpr const char* SUBSYSTEMS[] = { + "trunk", "satellite", "twin", "client", "mqtt", "redis", "core" +}; +constexpr std::size_t NUM_SUBSYSTEMS = + sizeof(SUBSYSTEMS) / sizeof(SUBSYSTEMS[0]); + +// Init: parse [GLOBAL] LOG=, set per-subsystem levels, spawn the worker +// thread. Call once, before LogWriter::start(). Returns false on config +// parse error (error already written to stderr). +bool configure(Async::Config& cfg); + +// Stop the worker thread, drain the queue, join. Call on normal exit +// before LogWriter::stop(). Safe to call multiple times. +void shutdown(); + +// Set one subsystem's level at runtime. Unknown subsystem or level +// string => false. Passing "*" as the subsystem applies setDefaultLevel. +bool setLevel(const std::string& subsystem, const std::string& level); + +// Apply `level` to every subsystem. +void setDefaultLevel(const std::string& level); + +// Return "=\n..." for each subsystem. +std::string snapshot(); + +// Restore the per-subsystem levels that configure() set from .conf. +// Does NOT reread .conf from disk. +void reset(); + +// Hot-path gate — one atomic load and one integer compare. +bool shouldLog(const char* subsystem, Level level); + +namespace detail { + // Async enqueue. Called only after shouldLog() passed. + void enqueue(Level level, const char* subsystem, std::string&& message); + + // Recursive stream append — C++11-compatible (avoids fold expressions so + // Log.h can be #included from call sites built at --std=c++11). + inline void append_all(std::ostringstream&) {} + + template + inline void append_all(std::ostringstream& os, T&& first, Rest&&... rest) { + os << std::forward(first); + append_all(os, std::forward(rest)...); + } + + template + inline std::string concat(Args&&... args) { + std::ostringstream os; + append_all(os, std::forward(args)...); + return os.str(); + } +} + +#define _LOG_DEFINE(fnname, lvlenum) \ + template \ + inline void fnname(const char* sub, Args&&... args) { \ + if (!shouldLog(sub, Level::lvlenum)) return; \ + detail::enqueue(Level::lvlenum, sub, \ + detail::concat(std::forward(args)...)); \ + } + +_LOG_DEFINE(trace, Trace) +_LOG_DEFINE(debug, Debug) +_LOG_DEFINE(info, Info) +_LOG_DEFINE(warn, Warn) +_LOG_DEFINE(error, Error) + +#undef _LOG_DEFINE + +} // namespace geulog + +#endif diff --git a/src/svxlink/reflector/Reflector.cpp b/src/svxlink/reflector/Reflector.cpp index 8d416ab..c6b59a3 100644 --- a/src/svxlink/reflector/Reflector.cpp +++ b/src/svxlink/reflector/Reflector.cpp @@ -70,6 +70,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "ReflectorClient.h" #include "TGHandler.h" #include "TrunkLink.h" +#include #include "TwinLink.h" #include "RedisStore.h" #include @@ -601,8 +602,8 @@ bool Reflector::sendUdpDatagram(ReflectorClient *client, std::stringstream aadss; if (!aad.pack(aadss)) { - std::cout << "*** WARNING: Packing associated data failed for UDP " - "datagram to " << udp_addr << ":" << udp_port << std::endl; + geulog::warn("client", "Packing associated data failed for UDP " + "datagram to ", udp_addr, ":", udp_port); return false; } return m_udp_sock->write(udp_addr, udp_port, @@ -642,8 +643,8 @@ void Reflector::requestQsy(ReflectorClient *client, uint32_t tg) uint32_t current_tg = TGHandler::instance()->TGForClient(client); if (current_tg == 0) { - std::cout << client->callsign() - << ": Cannot request QSY from TG #0" << std::endl; + geulog::info("client", client->callsign(), + ": Cannot request QSY from TG #0"); return; } @@ -653,8 +654,8 @@ void Reflector::requestQsy(ReflectorClient *client, uint32_t tg) if (tg == 0) { return; } } - cout << client->callsign() << ": Requesting QSY from TG #" - << current_tg << " to TG #" << tg << endl; + geulog::info("client", client->callsign(), ": Requesting QSY from TG #", + current_tg, " to TG #", tg); broadcastMsg(MsgRequestQsy(tg), ReflectorClient::mkAndFilter( @@ -839,7 +840,7 @@ bool Reflector::callsignOk(const std::string& callsign, bool verbose) const { if (verbose) { - std::cout << "*** WARNING: The callsign is empty" << std::endl; + geulog::warn("client", "The callsign is empty"); } return false; } @@ -859,9 +860,8 @@ bool Reflector::callsignOk(const std::string& callsign, bool verbose) const { if (verbose) { - std::cerr << "*** WARNING: The callsign '" << callsign - << "' is not accepted by configuration (ACCEPT_CALLSIGN)" - << std::endl; + geulog::warn("client", "The callsign '", callsign, + "' is not accepted by configuration (ACCEPT_CALLSIGN)"); } return false; } @@ -876,9 +876,8 @@ bool Reflector::callsignOk(const std::string& callsign, bool verbose) const { if (verbose) { - std::cerr << "*** WARNING: The callsign '" << callsign - << "' has been rejected by configuration (REJECT_CALLSIGN)." - << std::endl; + geulog::warn("client", "The callsign '", callsign, + "' has been rejected by configuration (REJECT_CALLSIGN)."); } return false; } @@ -886,8 +885,8 @@ bool Reflector::callsignOk(const std::string& callsign, bool verbose) const } catch (std::regex_error& e) { - std::cerr << "*** WARNING: Regular expression parsing error in " - << "ACCEPT_CALLSIGN/REJECT_CALLSIGN: " << e.what() << std::endl; + geulog::warn("client", "Regular expression parsing error in " + "ACCEPT_CALLSIGN/REJECT_CALLSIGN: ", e.what()); return false; } @@ -907,8 +906,8 @@ bool Reflector::emailOk(const std::string& email) const } catch (std::regex_error& e) { - std::cerr << "*** WARNING: Regular expression parsing error in " - << "ACCEPT_CERT_EMAIL: " << e.what() << std::endl; + geulog::warn("client", "Regular expression parsing error in " + "ACCEPT_CERT_EMAIL: ", e.what()); return false; } } /* Reflector::emailOk */ @@ -968,8 +967,7 @@ Async::SslX509 Reflector::csrReceived(Async::SslCertSigningReq& req) std::string callsign(req.commonName()); if (!callsignOk(callsign)) { - std::cerr << "*** WARNING: The CSR CN (callsign) check failed" - << std::endl; + geulog::warn("client", "The CSR CN (callsign) check failed"); return nullptr; } @@ -982,12 +980,11 @@ Async::SslX509 Reflector::csrReceived(Async::SslCertSigningReq& req) if (!csr.isNull() && (req.publicKey() != csr.publicKey())) { - std::cerr << "*** WARNING: The received CSR with callsign '" - << callsign << "' has a different public key " + geulog::warn("client", "The received CSR with callsign '", + callsign, "' has a different public key " "than the current CSR. That may be a sign of someone " "trying to hijack a callsign or the owner of the " - "callsign has generated a new private/public key pair." - << std::endl; + "callsign has generated a new private/public key pair."); return nullptr; } @@ -1011,8 +1008,8 @@ Async::SslX509 Reflector::csrReceived(Async::SslCertSigningReq& req) (req.digest() != pending_csr.digest()) )) { - std::cout << callsign << ": Add pending CSR '" << pending_csr_path - << "' to CA" << std::endl; + geulog::info("client", callsign, ": Add pending CSR '", pending_csr_path, + "' to CA"); if (req.writePemFile(pending_csr_path)) { const auto ca_op = @@ -1024,8 +1021,8 @@ Async::SslX509 Reflector::csrReceived(Async::SslCertSigningReq& req) } else { - std::cerr << "*** WARNING: Could not write CSR file '" - << pending_csr_path << "'" << std::endl; + geulog::warn("client", "Could not write CSR file '", + pending_csr_path, "'"); } } @@ -1059,8 +1056,8 @@ Json::Value& Reflector::clientStatus(const std::string& callsign) void Reflector::clientConnected(Async::FramedTcpConnection *con) { - std::cout << con->remoteHost() << ":" << con->remotePort() - << ": Client connected" << endl; + geulog::info("client", con->remoteHost(), ":", con->remotePort(), + ": Client connected"); ReflectorClient *client = new ReflectorClient(this, con, m_cfg); con->verifyPeer.connect(sigc::mem_fun(*this, &Reflector::onVerifyPeer)); m_client_con_map[con] = client; @@ -1078,14 +1075,15 @@ void Reflector::clientDisconnected(Async::FramedTcpConnection *con, if (!client->callsign().empty()) { - cout << client->callsign() << ": "; + geulog::info("client", client->callsign(), ": Client disconnected: ", + TcpConnection::disconnectReasonStr(reason)); } else { - std::cout << con->remoteHost() << ":" << con->remotePort() << ": "; + geulog::info("client", con->remoteHost(), ":", con->remotePort(), + ": Client disconnected: ", + TcpConnection::disconnectReasonStr(reason)); } - std::cout << "Client disconnected: " - << TcpConnection::disconnectReasonStr(reason) << std::endl; m_client_con_map.erase(it); @@ -1114,8 +1112,8 @@ bool Reflector::udpCipherDataReceived(const IpAddress& addr, uint16_t port, { if ((count <= 0) || (static_cast(count) < UdpCipher::AADLEN)) { - std::cout << "### : Ignoring too short UDP datagram (" << count - << " bytes)" << std::endl; + geulog::debug("client", "Ignoring too short UDP datagram (", count, + " bytes)"); return true; } @@ -1123,7 +1121,7 @@ bool Reflector::udpCipherDataReceived(const IpAddress& addr, uint16_t port, ss.write(reinterpret_cast(buf), UdpCipher::AADLEN); if (!m_aad.unpack(ss)) { - std::cout << "### Ignoring UDP datagram with unparseable AAD" << std::endl; + geulog::debug("client", "Ignoring UDP datagram with unparseable AAD"); return true; } @@ -1135,8 +1133,7 @@ bool Reflector::udpCipherDataReceived(const IpAddress& addr, uint16_t port, // << m_aad.iv_cntr << std::endl; if (static_cast(count) < iaad.packedSize()) { - std::cout << "### Reflector::udpCipherDataReceived: " - "Ignoring malformed UDP registration datagram" << std::endl; + geulog::debug("client", "Ignoring malformed UDP registration datagram"); return true; } ss.clear(); @@ -1149,8 +1146,8 @@ bool Reflector::udpCipherDataReceived(const IpAddress& addr, uint16_t port, auto client = ReflectorClient::lookup(iaad.client_id); if (client == nullptr) { - std::cout << "### Could not find client id (" << iaad.client_id - << ") specified in initial AAD datagram" << std::endl; + geulog::debug("client", "Could not find client id (", iaad.client_id, + ") specified in initial AAD datagram"); return true; } m_udp_sock->setCipherIV(UdpCipher::IV{client->udpCipherIVRand(), @@ -1201,7 +1198,7 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, if (m_udp_sock->cipherAADLength() < UdpCipher::AADLEN) { - std::cerr << "*** ERROR: Cipher AAD length too short" << std::endl; + geulog::error("client", "Cipher AAD length too short"); return; } @@ -1211,8 +1208,8 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, ReflectorUdpMsg header; if (!header.unpack(ss)) { - cout << "*** WARNING: Unpacking message header failed for UDP datagram " - "from " << addr << ":" << port << endl; + geulog::warn("client", "Unpacking message header failed for UDP datagram " + "from ", addr, ":", port); return; } ReflectorUdpMsgV2 header_v2; @@ -1239,8 +1236,7 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, if (!aadss.good()) return; if (!iaad.unpack(aadss)) { - std::cout << "### Reflector::udpDatagramReceived: " - "Could not unpack iaad" << std::endl; + geulog::debug("client", "Could not unpack iaad"); return; } if (iaad.iv_cntr != 0) return; @@ -1249,8 +1245,7 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, client = ReflectorClient::lookup(iaad.client_id); if (client == nullptr) { - std::cout << "### Reflector::udpDatagramReceived: Could not find " - "client id " << iaad.client_id << std::endl; + geulog::debug("client", "Could not find client id ", iaad.client_id); return; } else if (client->remoteUdpPort() == 0) @@ -1259,8 +1254,7 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, } else { - std::cout << "### Reflector::udpDatagramReceived: Client " - << iaad.client_id << " already registered." << std::endl; + geulog::debug("client", "Client ", iaad.client_id, " already registered."); } client->setUdpRxSeq(0); //client->sendUdpMsg(MsgUdpHeartbeat()); @@ -1270,7 +1264,7 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, client = ReflectorClient::lookup(std::make_pair(addr, port)); if (client == nullptr) { - std::cout << "### Unknown client " << addr << ":" << port << std::endl; + geulog::debug("client", "Unknown client ", addr, ":", port); return; } } @@ -1280,24 +1274,23 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, ss.seekg(0); if (!header_v2.unpack(ss)) { - std::cout << "*** WARNING: Unpacking V2 message header failed for UDP " - "datagram from " << addr << ":" << port << std::endl; + geulog::warn("client", "Unpacking V2 message header failed for UDP " + "datagram from ", addr, ":", port); return; } client = ReflectorClient::lookup(header_v2.clientId()); if (client == nullptr) { - std::cerr << "*** WARNING: Incoming V2 UDP datagram from " << addr << ":" - << port << " has invalid client id " << header_v2.clientId() - << std::endl; + geulog::warn("client", "Incoming V2 UDP datagram from ", addr, ":", + port, " has invalid client id ", header_v2.clientId()); return; } if (addr != client->remoteHost()) { - cerr << "*** WARNING[" << client->callsign() - << "]: Incoming UDP packet has the wrong source ip, " - << addr << " instead of " << client->remoteHost() << endl; + geulog::warn("client", client->callsign(), + ": Incoming UDP packet has the wrong source ip, ", + addr, " instead of ", client->remoteHost()); return; } } @@ -1321,10 +1314,10 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, } if (port != client->remoteUdpPort()) { - cerr << "*** WARNING[" << client->callsign() - << "]: Incoming UDP packet has the wrong source UDP " - "port number, " << port << " instead of " - << client->remoteUdpPort() << endl; + geulog::warn("client", client->callsign(), + ": Incoming UDP packet has the wrong source UDP " + "port number, ", port, " instead of ", + client->remoteUdpPort()); return; } @@ -1333,18 +1326,18 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, { if (aad.iv_cntr < client->nextUdpRxSeq()) // Frame out of sequence (ignore) { - std::cout << client->callsign() - << ": Dropping out of sequence UDP frame with seq=" - << aad.iv_cntr << std::endl; + geulog::debug("client", client->callsign(), + ": Dropping out of sequence UDP frame with seq=", + aad.iv_cntr); return; } else if (aad.iv_cntr > client->nextUdpRxSeq()) // Frame lost { - std::cout << client->callsign() << ": UDP frame(s) lost. Expected seq=" - << client->nextUdpRxSeq() - << " but received " << aad.iv_cntr - << ". Resetting next expected sequence number to " - << (aad.iv_cntr + 1) << std::endl; + geulog::info("client", client->callsign(), ": UDP frame(s) lost. Expected seq=", + client->nextUdpRxSeq(), + " but received ", aad.iv_cntr, + ". Resetting next expected sequence number to ", + (aad.iv_cntr + 1)); } client->setUdpRxSeq(aad.iv_cntr + 1); } @@ -1354,17 +1347,17 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, uint16_t udp_rx_seq_diff = header_v2.sequenceNum() - next_udp_rx_seq; if (udp_rx_seq_diff > 0x7fff) // Frame out of sequence (ignore) { - std::cout << client->callsign() - << ": Dropping out of sequence frame with seq=" - << header_v2.sequenceNum() << ". Expected seq=" - << next_udp_rx_seq << std::endl; + geulog::debug("client", client->callsign(), + ": Dropping out of sequence frame with seq=", + header_v2.sequenceNum(), ". Expected seq=", + next_udp_rx_seq); return; } else if (udp_rx_seq_diff > 0) // Frame(s) lost { - cout << client->callsign() - << ": UDP frame(s) lost. Expected seq=" << next_udp_rx_seq - << ". Received seq=" << header_v2.sequenceNum() << endl; + geulog::info("client", client->callsign(), + ": UDP frame(s) lost. Expected seq=", next_udp_rx_seq, + ". Received seq=", header_v2.sequenceNum()); } client->setUdpRxSeq(header_v2.sequenceNum() + 1); } @@ -1385,8 +1378,8 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, MsgUdpAudio msg; if (!msg.unpack(ss)) { - cerr << "*** WARNING[" << client->callsign() - << "]: Could not unpack incoming MsgUdpAudioV1 message" << endl; + geulog::warn("client", client->callsign(), + ": Could not unpack incoming MsgUdpAudioV1 message"); return; } uint32_t tg = TGHandler::instance()->TGForClient(client); @@ -1512,9 +1505,9 @@ void Reflector::udpDatagramReceived(const IpAddress& addr, uint16_t port, MsgUdpSignalStrengthValues msg; if (!msg.unpack(ss)) { - cerr << "*** WARNING[" << client->callsign() - << "]: Could not unpack incoming " - "MsgUdpSignalStrengthValues message" << endl; + geulog::warn("client", client->callsign(), + ": Could not unpack incoming " + "MsgUdpSignalStrengthValues message"); return; } typedef MsgUdpSignalStrengthValues::Rxs::const_iterator RxsIter; @@ -1555,7 +1548,7 @@ void Reflector::onTalkerUpdated(uint32_t tg, ReflectorClient* old_talker, { if (old_talker != 0) { - cout << old_talker->callsign() << ": Talker stop on TG #" << tg << endl; + geulog::info("client", old_talker->callsign(), ": Talker stop on TG #", tg); old_talker->updateIsTalker(); broadcastMsg(MsgTalkerStop(tg, old_talker->callsign()), ReflectorClient::mkAndFilter( @@ -1582,7 +1575,7 @@ void Reflector::onTalkerUpdated(uint32_t tg, ReflectorClient* old_talker, } if (new_talker != 0) { - cout << new_talker->callsign() << ": Talker start on TG #" << tg << endl; + geulog::info("client", new_talker->callsign(), ": Talker start on TG #", tg); new_talker->updateIsTalker(); broadcastMsg(MsgTalkerStart(tg, new_talker->callsign()), ReflectorClient::mkAndFilter( @@ -1830,8 +1823,8 @@ void Reflector::onRequestAutoQsy(uint32_t from_tg) uint32_t tg = nextRandomQsyTg(); if (tg == 0) { return; } - std::cout << "Requesting auto-QSY from TG #" << from_tg - << " to TG #" << tg << std::endl; + geulog::info("core", "Requesting auto-QSY from TG #", from_tg, + " to TG #", tg); broadcastMsg(MsgRequestQsy(tg), ReflectorClient::mkAndFilter( @@ -1844,8 +1837,8 @@ uint32_t Reflector::nextRandomQsyTg(void) { if (m_random_qsy_tg == 0) { - std::cout << "*** WARNING: QSY request for random TG " - << "requested but RANDOM_QSY_RANGE is empty" << std::endl; + geulog::warn("core", "QSY request for random TG " + "requested but RANDOM_QSY_RANGE is empty"); return 0; } @@ -1862,7 +1855,7 @@ uint32_t Reflector::nextRandomQsyTg(void) } } - std::cout << "*** WARNING: No random TG available for QSY" << std::endl; + geulog::warn("core", "No random TG available for QSY"); return 0; } /* Reflector::nextRandomQsyTg */ @@ -2119,9 +2112,65 @@ void Reflector::ctrlPtyDataReceived(const void *buf, size_t count) goto write_status; } } + else if (cmd == "LOG") + { + std::string rest; + std::getline(ss, rest); + // trim leading whitespace + size_t first = rest.find_first_not_of(" \t"); + if (first == std::string::npos) rest.clear(); + else rest = rest.substr(first); + // trim trailing whitespace / cr / lf + size_t last = rest.find_last_not_of(" \t\r\n"); + if (last != std::string::npos) rest.erase(last + 1); + else rest.clear(); + + if (rest.empty() || rest == "SHOW" || rest == "show") + { + m_cmd_pty->write(geulog::snapshot()); + goto write_status; + } + if (rest == "RESET" || rest == "reset") + { + geulog::reset(); + m_cmd_pty->write("LOG: restored from startup snapshot\n"); + goto write_status; + } + + // "=[,=...]" + { + std::stringstream pairs(rest); + std::string pair; + while (std::getline(pairs, pair, ',')) + { + auto eq = pair.find('='); + if (eq == std::string::npos) + { + errss << "LOG: missing '=' in '" << pair << "'"; + goto write_status; + } + std::string sub = pair.substr(0, eq); + std::string lvl = pair.substr(eq + 1); + auto trim = [](std::string& s) { + s.erase(0, s.find_first_not_of(" \t")); + size_t e = s.find_last_not_of(" \t\r\n"); + if (e != std::string::npos) s.erase(e + 1); + else s.clear(); + }; + trim(sub); trim(lvl); + if (!geulog::setLevel(sub, lvl)) + { + errss << "LOG: unknown subsystem or level in '" + << sub << "=" << lvl << "'"; + goto write_status; + } + m_cmd_pty->write("LOG: " + sub + "=" + lvl + "\n"); + } + } + } else { - errss << "Valid commands are: CFG, NODE, CA, TRUNK\n" + errss << "Valid commands are: CFG, NODE, CA, TRUNK, LOG\n" << "Usage:\n" << "CFG
\n" << "NODE BLOCK \n" @@ -2129,13 +2178,14 @@ void Reflector::ctrlPtyDataReceived(const void *buf, size_t count) << "TRUNK MUTE|UNMUTE
\n" << "TRUNK RELOAD [
]\n" << "TRUNK STATUS [
]\n" + << "LOG [SHOW|RESET|=[,...]]\n" << "\nEmpty CFG lists all configuration"; } write_status: if (!errss.str().empty()) { - std::cerr << "*** ERROR: " << errss.str() << std::endl; + geulog::error("core", errss.str()); m_cmd_pty->write(std::string("ERR:") + errss.str() + "\n"); return; } @@ -2148,8 +2198,8 @@ void Reflector::cfgUpdated(const std::string& section, const std::string& tag) std::string value; if (!m_cfg->getValue(section, tag, value)) { - std::cout << "*** ERROR: Failed to read updated configuration variable '" - << section << "/" << tag << "'" << std::endl; + geulog::error("core", "Failed to read updated configuration variable '", + section, "/", tag, "'"); return; } @@ -2160,8 +2210,8 @@ void Reflector::cfgUpdated(const std::string& section, const std::string& tag) unsigned t = TGHandler::instance()->sqlTimeoutBlocktime(); if (!SvxLink::setValueFromString(t, value)) { - std::cout << "*** ERROR: Failed to set updated configuration " - "variable '" << section << "/" << tag << "'" << std::endl; + geulog::error("core", "Failed to set updated configuration " + "variable '", section, "/", tag, "'"); return; } TGHandler::instance()->setSqlTimeoutBlocktime(t); @@ -2172,8 +2222,8 @@ void Reflector::cfgUpdated(const std::string& section, const std::string& tag) unsigned t = TGHandler::instance()->sqlTimeout(); if (!SvxLink::setValueFromString(t, value)) { - std::cout << "*** ERROR: Failed to set updated configuration " - "variable '" << section << "/" << tag << "'" << std::endl; + geulog::error("core", "Failed to set updated configuration " + "variable '", section, "/", tag, "'"); return; } TGHandler::instance()->setSqlTimeout(t); @@ -2228,8 +2278,7 @@ void Reflector::initTrunkLinks(void) 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; + geulog::info("core", "Redis: loaded ", peers.size(), " trunk peer(s)"); } // First pass: collect all remote prefixes so we can do longest-prefix-match @@ -2329,9 +2378,8 @@ void Reflector::trunkClientConnected(Async::FramedTcpConnection* con) } if (ip_pending >= 2) { - std::cerr << "*** WARNING: TRUNK inbound from " << remote_ip - << ": too many pending connections from this IP — rejecting" - << std::endl; + geulog::warn("trunk", "TRUNK inbound from ", remote_ip, + ": too many pending connections from this IP — rejecting"); con->disconnect(); return; } @@ -2339,21 +2387,18 @@ void Reflector::trunkClientConnected(Async::FramedTcpConnection* con) // Reject connections beyond the global pending limit to prevent fd exhaustion if (m_trunk_pending_cons.size() >= TRUNK_MAX_PENDING_CONS) { - std::cerr << "*** WARNING: TRUNK inbound from " << remote_ip - << ": too many pending connections — rejecting" << std::endl; + geulog::warn("trunk", "TRUNK inbound from ", remote_ip, + ": too many pending connections — rejecting"); con->disconnect(); return; } - std::cout << "TRUNK: Inbound connection from " - << con->remoteHost() << ":" << con->remotePort() << std::endl; + geulog::info("trunk", "TRUNK: Inbound connection from ", + con->remoteHost(), ":", con->remotePort()); - if (m_trunk_debug) - { - std::cout << "TRUNK [DEBUG]: pending_count=" << m_trunk_pending_cons.size() - << " ip_pending=" << ip_pending - << " from " << remote_ip << std::endl; - } + geulog::debug("trunk", "TRUNK: pending_count=", m_trunk_pending_cons.size(), + " ip_pending=", ip_pending, + " from ", remote_ip); // Set up a timeout for receiving the hello message auto* timer = new Async::Timer(10000, Async::Timer::TYPE_ONESHOT); @@ -2379,8 +2424,8 @@ void Reflector::trunkClientDisconnected(Async::FramedTcpConnection* con, { delete pit->second; // timer m_trunk_pending_cons.erase(pit); - std::cout << "TRUNK: Pending inbound from " - << con->remoteHost() << " disconnected" << std::endl; + geulog::info("trunk", "TRUNK: Pending inbound from ", + con->remoteHost(), " disconnected"); return; } @@ -2421,16 +2466,15 @@ void Reflector::trunkPendingFrameReceived(Async::FramedTcpConnection* con, ReflectorMsg header; if (!header.unpack(ss)) { - std::cerr << "*** ERROR: TRUNK inbound: failed to unpack message header" - << std::endl; + geulog::error("trunk", "TRUNK inbound: failed to unpack message header"); rejectPending(); return; } if (header.type() != MsgTrunkHello::TYPE) { - std::cerr << "*** WARNING: TRUNK inbound: expected MsgTrunkHello, got type=" - << header.type() << std::endl; + geulog::warn("trunk", "TRUNK inbound: expected MsgTrunkHello, got type=", + header.type()); rejectPending(); return; } @@ -2438,16 +2482,14 @@ void Reflector::trunkPendingFrameReceived(Async::FramedTcpConnection* con, MsgTrunkHello msg; if (!msg.unpack(ss)) { - std::cerr << "*** ERROR: TRUNK inbound: failed to unpack MsgTrunkHello" - << std::endl; + geulog::error("trunk", "TRUNK inbound: failed to unpack MsgTrunkHello"); rejectPending(); return; } if (msg.id().empty()) { - std::cerr << "*** ERROR: TRUNK inbound: peer sent empty trunk ID" - << std::endl; + geulog::error("trunk", "TRUNK inbound: peer sent empty trunk ID"); rejectPending(); return; } @@ -2480,16 +2522,12 @@ void Reflector::trunkPendingFrameReceived(Async::FramedTcpConnection* con, if (!msg.verify(link->secret())) { - if (m_trunk_debug) - { - std::cout << "TRUNK [DEBUG]: peer '" << safe_id - << "' section matches " << link->section() - << " but HMAC mismatch" << std::endl; - } - std::cerr << "*** ERROR: TRUNK inbound: peer '" << safe_id - << "' section matches " << link->section() - << " but authentication failed (wrong secret)" - << std::endl; + geulog::debug("trunk", "TRUNK: peer '", safe_id, + "' section matches ", link->section(), + " but HMAC mismatch"); + geulog::error("trunk", "TRUNK inbound: peer '", safe_id, + "' section matches ", link->section(), + " but authentication failed (wrong secret)"); rejectPending(); return; } @@ -2531,10 +2569,10 @@ void Reflector::trunkPendingFrameReceived(Async::FramedTcpConnection* con, if (!peer_str.empty()) peer_str += ","; peer_str += p; } - std::cerr << "*** ERROR: TRUNK inbound: peer '" << safe_id - << "' section matches " << link->section() - << " but prefix mismatch: expected=[" << exp_str - << "] got=[" << peer_str << "]" << std::endl; + geulog::error("trunk", "TRUNK inbound: peer '", safe_id, + "' section matches ", link->section(), + " but prefix mismatch: expected=[", exp_str, + "] got=[", peer_str, "]"); rejectPending(); return; } @@ -2542,18 +2580,14 @@ void Reflector::trunkPendingFrameReceived(Async::FramedTcpConnection* con, if (matched_link == nullptr) { - std::cerr << "*** ERROR: TRUNK inbound: peer '" << safe_id - << "' no matching section name" - << std::endl; + geulog::error("trunk", "TRUNK inbound: peer '", safe_id, + "' no matching section name"); rejectPending(); return; } - if (m_trunk_debug) - { - std::cout << "TRUNK [DEBUG]: peer '" << safe_id - << "' matched to " << matched_link->section() << std::endl; - } + geulog::debug("trunk", "TRUNK: peer '", safe_id, + "' matched to ", matched_link->section()); // Clean up the pending entry delete pit->second; // timer @@ -2580,9 +2614,9 @@ void Reflector::trunkPendingTimeout(Async::Timer* t) { if (it->second == t) { - std::cerr << "*** WARNING: TRUNK inbound from " - << it->first->remoteHost() - << ": hello timeout — disconnecting" << std::endl; + geulog::warn("trunk", "TRUNK inbound from ", + it->first->remoteHost(), + ": hello timeout — disconnecting"); auto* con = it->first; delete it->second; // timer m_trunk_pending_cons.erase(it); @@ -2617,8 +2651,8 @@ void Reflector::initSatelliteServer(void) void Reflector::satelliteConnected(Async::FramedTcpConnection* con) { - std::cout << "SAT: Inbound connection from " - << con->remoteHost() << ":" << con->remotePort() << std::endl; + geulog::info("satellite", "SAT: Inbound connection from ", + con->remoteHost(), ":", con->remotePort()); auto* link = new SatelliteLink(this, con, m_satellite_secret); link->linkFailed.connect( sigc::mem_fun(*this, &Reflector::onSatelliteLinkFailed)); @@ -2635,8 +2669,8 @@ void Reflector::satelliteDisconnected(Async::FramedTcpConnection* con, auto it = m_satellite_con_map.find(con); if (it != m_satellite_con_map.end()) { - std::cout << "SAT: Satellite '" << it->second->satelliteId() - << "' disconnected" << std::endl; + geulog::info("satellite", "SAT: Satellite '", it->second->satelliteId(), + "' disconnected"); if (m_redis != nullptr) { m_redis->clearSatelliteStatus(it->second->satelliteId()); } @@ -2674,8 +2708,8 @@ void Reflector::processSatelliteCleanup(Async::Timer* t) } if (con == nullptr) continue; - std::cout << "SAT: Cleaning up timed-out satellite '" - << link->satelliteId() << "'" << std::endl; + geulog::info("satellite", "SAT: Cleaning up timed-out satellite '", + link->satelliteId(), "'"); if (m_redis != nullptr) { m_redis->clearSatelliteStatus(link->satelliteId()); } @@ -2759,7 +2793,7 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, if (!old_cs.empty()) { - std::cout << old_cs << ": Trunk talker stop on TG #" << tg << std::endl; + geulog::info("trunk", old_cs, ": Trunk talker stop on TG #", tg); broadcastMsg(MsgTalkerStop(tg, old_cs), ReflectorClient::mkAndFilter( ge_v2_client_filter, @@ -2779,7 +2813,7 @@ void Reflector::onTrunkTalkerUpdated(uint32_t tg, } if (!new_cs.empty()) { - std::cout << new_cs << ": Trunk talker start on TG #" << tg << std::endl; + geulog::info("trunk", new_cs, ": Trunk talker start on TG #", tg); broadcastMsg(MsgTalkerStart(tg, new_cs), ReflectorClient::mkAndFilter( ge_v2_client_filter, @@ -2837,12 +2871,13 @@ void Reflector::reloadClusterTgs(void) } if (!m_cluster_tgs.empty()) { - std::cout << "Cluster TGs:"; + std::ostringstream _clust_oss; + _clust_oss << "Cluster TGs:"; for (uint32_t tg : m_cluster_tgs) { - std::cout << " " << tg; + _clust_oss << " " << tg; } - std::cout << std::endl; + geulog::info("core", _clust_oss.str()); } publishMetaToRedis(); } @@ -2861,8 +2896,7 @@ std::vector Reflector::collectAllTrunkPrefixes(void) const bool Reflector::addTrunkLink(const std::string& section) { if (m_redis == nullptr) { - std::cerr << "*** addTrunkLink called without Redis — refusing" - << std::endl; + geulog::error("trunk", "addTrunkLink called without Redis — refusing"); return false; } // Already present? @@ -2873,8 +2907,8 @@ bool Reflector::addTrunkLink(const std::string& section) 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; + geulog::error("trunk", "addTrunkLink(", section, + "): peer hash not found in Redis"); return false; } const auto& p = it->second; @@ -2888,8 +2922,8 @@ bool Reflector::addTrunkLink(const std::string& section) auto* link = new TrunkLink(this, *m_cfg, section); if (!link->initialize()) { - std::cerr << "*** addTrunkLink(" << section - << "): TrunkLink::initialize() failed" << std::endl; + geulog::error("trunk", "addTrunkLink(", section, + "): TrunkLink::initialize() failed"); delete link; return false; } @@ -2900,8 +2934,8 @@ bool Reflector::addTrunkLink(const std::string& section) 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; + geulog::info("trunk", "Added trunk link: ", section, " (", p.host, + ":", (p.port.empty() ? "5302" : p.port), ")"); return true; } @@ -2921,14 +2955,14 @@ bool Reflector::removeTrunkLink(const std::string& section) auto all_prefixes = collectAllTrunkPrefixes(); for (auto* l : m_trunk_links) l->setAllPrefixes(all_prefixes); - std::cout << "Removed trunk link: " << section << std::endl; + geulog::info("trunk", "Removed trunk link: ", section); return true; } void Reflector::onRedisConfigChanged(std::string scope) { - std::cout << "Redis config.changed: " << scope << std::endl; + geulog::info("core", "Redis config.changed: ", scope); if (scope == "users" || scope == "all") { // Auth lookups are stateless (per-connect). Nothing to invalidate on // existing connections — they are already authenticated. New @@ -2966,9 +3000,8 @@ void Reflector::onRedisConfigChanged(std::string scope) existing->reloadConfig(); } else { // neither — log and ignore - std::cout << "Redis: trunk:" << section - << " event but peer not in Redis and no local link" - << std::endl; + geulog::info("core", "Redis: trunk:", section, + " event but peer not in Redis and no local link"); } } } @@ -4087,7 +4120,7 @@ void Reflector::initTwinLink(void) { delete m_twin_link; m_twin_link = nullptr; - cerr << "*** ERROR: TwinLink initialization failed" << endl; + geulog::error("twin", "TwinLink initialization failed"); } } /* Reflector::initTwinLink */ @@ -4117,9 +4150,9 @@ void Reflector::initTwinServer(void) void Reflector::twinClientConnected(Async::FramedTcpConnection* con) { - std::cout << "TWIN: inbound connection from " - << con->remoteHost() << ":" << con->remotePort() - << " (awaiting hello)" << std::endl; + geulog::info("twin", "TWIN: inbound connection from ", + con->remoteHost(), ":", con->remotePort(), + " (awaiting hello)"); auto* timer = new Async::Timer(10000, Async::Timer::TYPE_ONESHOT); timer->expired.connect( @@ -4140,8 +4173,8 @@ void Reflector::twinClientDisconnected(Async::FramedTcpConnection* con, { delete pit->second; // timer m_twin_pending_cons.erase(pit); - std::cout << "TWIN: pending inbound from " - << con->remoteHost() << " disconnected" << std::endl; + geulog::info("twin", "TWIN: pending inbound from ", + con->remoteHost(), " disconnected"); } // If already handed off to m_twin_link, TwinLink owns the connection. } /* Reflector::twinClientDisconnected */ @@ -4173,16 +4206,15 @@ void Reflector::twinPendingFrameReceived(Async::FramedTcpConnection* con, ReflectorMsg header; if (!header.unpack(ss)) { - std::cerr << "*** ERROR: TWIN inbound: failed to unpack message header" - << std::endl; + geulog::error("twin", "TWIN inbound: failed to unpack message header"); rejectPending(); return; } if (header.type() != MsgTrunkHello::TYPE) { - std::cerr << "*** WARNING: TWIN inbound: expected MsgTrunkHello, got type=" - << header.type() << std::endl; + geulog::warn("twin", "TWIN inbound: expected MsgTrunkHello, got type=", + header.type()); rejectPending(); return; } @@ -4190,17 +4222,16 @@ void Reflector::twinPendingFrameReceived(Async::FramedTcpConnection* con, MsgTrunkHello msg; if (!msg.unpack(ss)) { - std::cerr << "*** ERROR: TWIN inbound: failed to unpack MsgTrunkHello" - << std::endl; + geulog::error("twin", "TWIN inbound: failed to unpack MsgTrunkHello"); rejectPending(); return; } if (msg.role() != MsgTrunkHello::ROLE_TWIN) { - std::cerr << "*** ERROR: TWIN inbound: peer sent role=" << int(msg.role()) - << ", expected ROLE_TWIN (" << int(MsgTrunkHello::ROLE_TWIN) - << ")" << std::endl; + geulog::error("twin", "TWIN inbound: peer sent role=", int(msg.role()), + ", expected ROLE_TWIN (", int(MsgTrunkHello::ROLE_TWIN), + ")"); rejectPending(); return; } @@ -4208,8 +4239,8 @@ void Reflector::twinPendingFrameReceived(Async::FramedTcpConnection* con, // Verify HMAC (shared secret proof) before leaking any other info. if (!msg.verify(m_twin_link->secret())) { - std::cerr << "*** ERROR: TWIN inbound: authentication failed " - << "(wrong secret)" << std::endl; + geulog::error("twin", "TWIN inbound: authentication failed " + "(wrong secret)"); rejectPending(); return; } @@ -4217,9 +4248,9 @@ void Reflector::twinPendingFrameReceived(Async::FramedTcpConnection* con, // Twins must share the same LOCAL_PREFIX. if (msg.localPrefix() != m_twin_link->localPrefix()) { - std::cerr << "*** ERROR: TWIN inbound: local_prefix mismatch: " - << "ours='" << m_twin_link->localPrefix() - << "' theirs='" << msg.localPrefix() << "'" << std::endl; + geulog::error("twin", "TWIN inbound: local_prefix mismatch: " + "ours='", m_twin_link->localPrefix(), + "' theirs='", msg.localPrefix(), "'"); rejectPending(); return; } @@ -4242,9 +4273,9 @@ void Reflector::twinPendingTimeout(Async::Timer* t) { if (it->second == t) { - std::cerr << "*** WARNING: TWIN inbound from " - << it->first->remoteHost() - << ": hello timeout — disconnecting" << std::endl; + geulog::warn("twin", "TWIN inbound from ", + it->first->remoteHost(), + ": hello timeout — disconnecting"); auto* con = it->first; delete it->second; // timer m_twin_pending_cons.erase(it); diff --git a/src/svxlink/reflector/ReflectorClient.cpp b/src/svxlink/reflector/ReflectorClient.cpp index 66a39d8..28eb157 100644 --- a/src/svxlink/reflector/ReflectorClient.cpp +++ b/src/svxlink/reflector/ReflectorClient.cpp @@ -64,6 +64,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "Reflector.h" #include "TGHandler.h" #include "RedisStore.h" +#include /**************************************************************************** @@ -219,9 +220,9 @@ ReflectorClient::ReflectorClient(Reflector *ref, Async::FramedTcpConnection *con { m_supported_codecs.erase(m_supported_codecs.begin()+1, m_supported_codecs.end()); - cout << "*** WARNING: The GLOBAL/CODECS configuration " - "variable can only take one codec at the moment. Using the first " - "one: \"" << m_supported_codecs.front() << "\"" << endl; + geulog::warn("client", "The GLOBAL/CODECS configuration variable can only " + "take one codec at the moment. Using the first one: \"", + m_supported_codecs.front(), "\""); } else if (m_supported_codecs.empty()) { @@ -286,7 +287,7 @@ int ReflectorClient::sendMsg(const ReflectorMsg& msg) ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { - cerr << "*** ERROR: Failed to pack TCP message\n"; + geulog::error("client", "Failed to pack TCP message"); errno = EBADMSG; } } @@ -299,10 +300,8 @@ int ReflectorClient::sendMsg(const ReflectorMsg& msg) return ret; } } - std::cerr << "*** ERROR[" << m_con->remoteHost() << ":" - << m_con->remotePort() << "]: Write to client failed due to '" - << strerror(errno) << "'. Message type=" << msg.type() << "." - << std::endl; + geulog::debug("client", "sendMsg: write failed: ", strerror(errno), + " (msg type ", msg.type(), ")"); disconnect(); return -1; } /* ReflectorClient::sendMsg */ @@ -336,12 +335,12 @@ void ReflectorClient::setBlock(unsigned blocktime) { if (blocktime > 0) { - std::cout << m_callsign << ": Blocking talker for " << blocktime - << " seconds" << std::endl; + geulog::info("client", m_callsign, ": Blocking talker for ", blocktime, + " seconds"); } else if (m_blocktime > 0) { - std::cout << m_callsign << ": Unblocking talker" << std::endl; + geulog::info("client", m_callsign, ": Unblocking talker"); } m_blocktime = blocktime; m_remaining_blocktime = blocktime; @@ -505,9 +504,8 @@ void ReflectorClient::onFrameReceived(FramedTcpConnection *con, ReflectorMsg header; if (!header.unpack(ss)) { - std::cout << "*** ERROR[" << idss.str() - << "]: Unpacking failed for TCP message header" - << std::endl; + geulog::error("client", "[", idss.str(), + "]: Unpacking failed for TCP message header"); sendError("Protocol error"); return; } @@ -517,10 +515,8 @@ void ReflectorClient::onFrameReceived(FramedTcpConnection *con, // FIXME: This should really be an error and the client should be // disconnected but it will cause too much problems in existing // misbeaving clients at the moment. - std::cout << "*** WARNING[" << idss.str() - << "]: User message " << header.type() - << " received in unauthenticated state" - << std::endl; + geulog::warn("client", "[", idss.str(), "]: User message ", header.type(), + " received in unauthenticated state"); //sendError("Protocol error"); // Do not reset heartbeat — unauthenticated clients must not stay alive return; @@ -598,9 +594,8 @@ void ReflectorClient::handleMsgProtoVer(std::istream& is) MsgProtoVer msg; if (!msg.unpack(is)) { - std::cout << "*** ERROR[" << m_con->remoteHost() << ":" - << m_con->remotePort() << "]: Could not unpack MsgProtoVer" - << std::endl; + geulog::error("client", "[", m_con->remoteHost(), ":", + m_con->remotePort(), "]: Could not unpack MsgProtoVer"); sendError("Illegal MsgProtoVer protocol message received"); return; } @@ -608,36 +603,36 @@ void ReflectorClient::handleMsgProtoVer(std::istream& is) ProtoVer max_proto_ver(MsgProtoVer::MAJOR, MsgProtoVer::MINOR); if (m_client_proto_ver > max_proto_ver) { - std::cout << m_con->remoteHost() << ":" << m_con->remotePort() - << ": Using protocol version " - << msg.majorVer() << "." << msg.minorVer() - << " which is newer than we can handle."; if (m_con_state == STATE_EXPECT_PROTO_VER) { - std::cout << " Asking for downgrade to " - << MsgProtoVer::MAJOR << "." << MsgProtoVer::MINOR << "."; + geulog::warn("client", m_con->remoteHost(), ":", m_con->remotePort(), + ": Using protocol version ", msg.majorVer(), ".", + msg.minorVer(), " which is newer than we can handle." + " Asking for downgrade to ", + MsgProtoVer::MAJOR, ".", MsgProtoVer::MINOR, "."); sendMsg(MsgProtoVerDowngrade()); } else { - std::cout << " Downgrade failed."; + geulog::warn("client", m_con->remoteHost(), ":", m_con->remotePort(), + ": Using protocol version ", msg.majorVer(), ".", + msg.minorVer(), " which is newer than we can handle." + " Downgrade failed."); std::ostringstream ss; ss << "Unsupported protocol version " << msg.majorVer() << "." << msg.minorVer() << ". May be at most " << MsgProtoVer::MAJOR << "." << MsgProtoVer::MINOR << "."; sendError(ss.str()); } - std::cout << std::endl; return; } else if (m_client_proto_ver < ProtoVer(MIN_MAJOR_VER, MIN_MINOR_VER)) { - std::cout << "*** ERROR[" << m_con->remoteHost() << ":" - << m_con->remotePort() - << "]: Client is using protocol version " - << msg.majorVer() << "." << msg.minorVer() - << " which is too old. Must at least be version " - << MIN_MAJOR_VER << "." << MIN_MINOR_VER << "." << std::endl; + geulog::error("client", "[", m_con->remoteHost(), ":", m_con->remotePort(), + "]: Client is using protocol version ", + msg.majorVer(), ".", msg.minorVer(), + " which is too old. Must at least be version ", + MIN_MAJOR_VER, ".", MIN_MINOR_VER, "."); std::ostringstream ss; ss << "Unsupported protocol version " << msg.majorVer() << "." << msg.minorVer() << ". Must be at least " @@ -857,8 +852,8 @@ void ReflectorClient::handleSelectTG(std::istream& is) MsgSelectTG msg; if (!msg.unpack(is)) { - cout << "Client " << m_con->remoteHost() << ":" << m_con->remotePort() - << " ERROR: Could not unpack MsgSelectTG" << endl; + geulog::error("client", "Client ", m_con->remoteHost(), ":", + m_con->remotePort(), ": Could not unpack MsgSelectTG"); sendError("Illegal MsgSelectTG protocol message received"); return; } @@ -887,8 +882,8 @@ void ReflectorClient::handleTgMonitor(std::istream& is) MsgTgMonitor msg; if (!msg.unpack(is)) { - cout << "Client " << m_con->remoteHost() << ":" << m_con->remotePort() - << " ERROR: Could not unpack MsgTgMonitor" << endl; + geulog::error("client", "Client ", m_con->remoteHost(), ":", + m_con->remotePort(), ": Could not unpack MsgTgMonitor"); sendError("Illegal MsgTgMonitor protocol message received"); return; } @@ -899,16 +894,18 @@ void ReflectorClient::handleTgMonitor(std::istream& is) const auto& tg = *it; if (!TGHandler::instance()->allowTgMonitoring(this, tg) || (tg == 0)) { - std::cout << m_callsign << ": Not allowed to monitor TG #" - << tg << std::endl; + geulog::info("client", m_callsign, ": Not allowed to monitor TG #", tg); tgs.erase(it++); continue; } ++it; } - cout << m_callsign << ": Monitor TG#: [ "; - std::copy(tgs.begin(), tgs.end(), std::ostream_iterator(cout, " ")); - cout << "]" << endl; + { + std::ostringstream tglist; + std::copy(tgs.begin(), tgs.end(), + std::ostream_iterator(tglist, " ")); + geulog::info("client", m_callsign, ": Monitor TG#: [ ", tglist.str(), "]"); + } setMonitoredTGs(tgs); } /* ReflectorClient::handleTgMonitor */ @@ -922,8 +919,8 @@ void ReflectorClient::handleNodeInfo(std::istream& is) MsgNodeInfo msg; if (!msg.unpack(is)) { - cout << "Client " << m_con->remoteHost() << ":" << m_con->remotePort() - << " ERROR: Could not unpack MsgNodeInfo" << endl; + geulog::error("client", "Client ", m_con->remoteHost(), ":", + m_con->remotePort(), ": Could not unpack MsgNodeInfo"); sendError("Illegal MsgNodeInfo protocol message received"); return; } @@ -941,9 +938,8 @@ void ReflectorClient::handleNodeInfo(std::istream& is) MsgNodeInfoV2 msg; if (!msg.unpack(is)) { - std::cout << "Client " << m_con->remoteHost() << ":" - << m_con->remotePort() - << " ERROR: Could not unpack MsgNodeInfoV2" << std::endl; + geulog::error("client", "Client ", m_con->remoteHost(), ":", + m_con->remotePort(), ": Could not unpack MsgNodeInfoV2"); sendError("Illegal MsgNodeInfo protocol message received"); return; } @@ -1012,9 +1008,8 @@ void ReflectorClient::handleNodeInfo(std::istream& is) } catch (const Json::Exception& e) { - std::cerr << "*** WARNING[" << m_callsign - << "]: Failed to parse MsgNodeInfo JSON object: " - << e.what() << std::endl; + geulog::warn("client", "[", m_callsign, + "]: Failed to parse MsgNodeInfo JSON object: ", e.what()); } if (m_reflector != nullptr) m_reflector->publishClientStatus(this); } /* ReflectorClient::handleNodeInfo */ @@ -1025,9 +1020,8 @@ void ReflectorClient::handleMsgSignalStrengthValues(std::istream& is) MsgSignalStrengthValues msg; if (!msg.unpack(is)) { - cerr << "*** WARNING[" << callsign() - << "]: Could not unpack incoming " - "MsgSignalStrengthValues message" << endl; + geulog::warn("client", "[", callsign(), + "]: Could not unpack incoming MsgSignalStrengthValues message"); return; } typedef MsgSignalStrengthValues::Rxs::const_iterator RxsIter; @@ -1055,8 +1049,8 @@ void ReflectorClient::handleMsgTxStatus(std::istream& is) MsgTxStatus msg; if (!msg.unpack(is)) { - cerr << "*** WARNING[" << callsign() - << "]: Could not unpack incoming MsgTxStatus message" << endl; + geulog::warn("client", "[", callsign(), + "]: Could not unpack incoming MsgTxStatus message"); return; } typedef MsgTxStatus::Txs::const_iterator TxsIter; @@ -1077,8 +1071,8 @@ void ReflectorClient::handleRequestQsy(std::istream& is) MsgRequestQsy msg; if (!msg.unpack(is)) { - cout << "Client " << m_con->remoteHost() << ":" << m_con->remotePort() - << " ERROR: Could not unpack MsgRequestQsy" << endl; + geulog::error("client", "Client ", m_con->remoteHost(), ":", + m_con->remotePort(), ": Could not unpack MsgRequestQsy"); sendError("Illegal MsgRequestQsy protocol message received"); return; } @@ -1091,16 +1085,13 @@ void ReflectorClient::handleStateEvent(std::istream& is) MsgStateEvent msg; if (!msg.unpack(is)) { - cout << "Client " << m_con->remoteHost() << ":" << m_con->remotePort() - << " ERROR: Could not unpack MsgStateEvent" << endl; + geulog::error("client", "Client ", m_con->remoteHost(), ":", + m_con->remotePort(), ": Could not unpack MsgStateEvent"); sendError("Illegal MsgStateEvent protocol message received"); return; } - cout << "### ReflectorClient::handleStateEvent:" - << " src=" << msg.src() - << " name=" << msg.name() - << " msg=" << msg.msg() - << std::endl; + geulog::debug("client", "StateEvent: src=", msg.src(), + " name=", msg.name(), " msg=", msg.msg()); } /* ReflectorClient::handleStateEvent */ @@ -1194,15 +1185,14 @@ void ReflectorClient::handleMsgError(std::istream& is) { message = msg.message(); } - if (!m_callsign.empty()) { - cout << m_callsign << ": "; + const std::string id = m_callsign.empty() + ? (m_con->remoteHost().toString() + ":" + + std::to_string(m_con->remotePort())) + : m_callsign; + geulog::info("client", id, ": Error message received from client: ", + message); } - else - { - cout << m_con->remoteHost() << ":" << m_con->remotePort() << " "; - } - cout << "Error message received from client: " << message << endl; disconnect(); } /* ReflectorClient::handleMsgError */ @@ -1248,31 +1238,21 @@ void ReflectorClient::handleHeartbeat(Async::Timer *t) if (--m_heartbeat_rx_cnt == 0) { - if (!callsign().empty()) - { - cout << callsign() << ": "; - } - else - { - cout << "Client " << m_con->remoteHost() << ":" - << m_con->remotePort() << " "; - } - cout << "TCP heartbeat timeout" << endl; + const std::string id = callsign().empty() + ? ("Client " + m_con->remoteHost().toString() + ":" + + std::to_string(m_con->remotePort())) + : callsign(); + geulog::info("client", id, ": TCP heartbeat timeout"); sendError("TCP heartbeat timeout"); } if (--m_udp_heartbeat_rx_cnt == 0) { - if (!callsign().empty()) - { - cout << callsign() << ": "; - } - else - { - cout << "Client " << m_con->remoteHost() << ":" - << m_con->remotePort() << " "; - } - cout << "UDP heartbeat timeout" << endl; + const std::string id = callsign().empty() + ? ("Client " + m_con->remoteHost().toString() + ":" + + std::to_string(m_con->remotePort())) + : callsign(); + geulog::info("client", id, ": UDP heartbeat timeout"); sendError("UDP heartbeat timeout"); } @@ -1295,24 +1275,23 @@ 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; + geulog::warn("client", "Redis lookup failed for user \"", + callsign, "\""); } return key; } string auth_group; if (!m_cfg->getValue("USERS", callsign, auth_group) || auth_group.empty()) { - cout << "*** WARNING: Unknown user \"" << callsign << "\"" - << endl; + geulog::warn("client", "Unknown user \"", callsign, "\""); return ""; } string auth_key; if (!m_cfg->getValue("PASSWORDS", auth_group, auth_key) || auth_key.empty()) { - cout << "*** ERROR: User \"" << callsign << "\" found in SvxReflector " - << "configuration but password with groupname \"" << auth_group - << "\" not found." << endl; + geulog::error("client", "User \"", callsign, "\" found in SvxReflector " + "configuration but password with groupname \"", auth_group, + "\" not found."); return ""; } return auth_key; @@ -1329,11 +1308,10 @@ void ReflectorClient::connectionAuthenticated(const std::string& callsign) m_con->setMaxRxFrameSize(ReflectorMsg::MAX_POSTAUTH_FRAME_SIZE); m_callsign = callsign; sendMsg(MsgAuthOk()); - cout << m_callsign << ": Login OK from " - << m_con->remoteHost() << ":" << m_con->remotePort() - << " with protocol version " << m_client_proto_ver.majorVer() - << "." << m_client_proto_ver.minorVer() - << endl; + geulog::info("client", m_callsign, ": Login OK from ", + m_con->remoteHost(), ":", m_con->remotePort(), + " with protocol version ", m_client_proto_ver.majorVer(), + ".", m_client_proto_ver.minorVer()); m_con_state = STATE_CONNECTED; assert(client_callsign_map.find(m_callsign) == client_callsign_map.end()); @@ -1360,7 +1338,7 @@ void ReflectorClient::connectionAuthenticated(const std::string& callsign) } else { - cout << callsign << ": Already connected" << endl; + geulog::info("client", callsign, ": Already connected"); sendError("Access denied"); } } /* ReflectorClient::connectionAuthenticated */ @@ -1406,11 +1384,10 @@ void ReflectorClient::renewClientCertificate(void) auto cert = m_con->sslPeerCertificate(); if (cert.isNull() || !m_reflector->renewedClientCert(cert)) { - std::cerr << "*** WARNING: Certificate renewal for '" - << m_callsign << "' failed" << std::endl; + geulog::warn("client", "Certificate renewal for '", m_callsign, "' failed"); return; } - std::cout << m_callsign << ": Send renewed client certificate" << std::endl; + geulog::info("client", m_callsign, ": Send renewed client certificate"); sendClientCert(cert); m_con_state = STATE_EXPECT_DISCONNECT; } /* ReflectorClient::renewClientCertificate */ @@ -1444,12 +1421,12 @@ void ReflectorClient::setTg(uint32_t tg) { if (TGHandler::instance()->switchTo(this, tg)) { - std::cout << m_callsign << ": Select TG #" << tg << std::endl; + geulog::info("client", m_callsign, ": Select TG #", tg); } else { // FIXME: Notify the client that the TG selection was not allowed - std::cout << m_callsign << ": Not allowed to use TG #" << tg << std::endl; + geulog::info("client", m_callsign, ": Not allowed to use TG #", tg); TGHandler::instance()->switchTo(this, 0); tg = 0; } diff --git a/src/svxlink/reflector/SatelliteClient.cpp b/src/svxlink/reflector/SatelliteClient.cpp index e44c41f..0360b03 100644 --- a/src/svxlink/reflector/SatelliteClient.cpp +++ b/src/svxlink/reflector/SatelliteClient.cpp @@ -4,6 +4,8 @@ #include +#include + #include "SatelliteClient.h" #include "ReflectorMsg.h" #include "Reflector.h" @@ -47,7 +49,7 @@ bool SatelliteClient::initialize(void) if (!m_cfg.getValue("GLOBAL", "SATELLITE_OF", m_parent_host) || m_parent_host.empty()) { - cerr << "*** ERROR: Missing SATELLITE_OF in [GLOBAL]" << endl; + geulog::error("satellite", "Missing SATELLITE_OF in [GLOBAL]"); return false; } @@ -56,7 +58,7 @@ bool SatelliteClient::initialize(void) if (!m_cfg.getValue("GLOBAL", "SATELLITE_SECRET", m_secret) || m_secret.empty()) { - cerr << "*** ERROR: Missing SATELLITE_SECRET in [GLOBAL]" << endl; + geulog::error("satellite", "Missing SATELLITE_SECRET in [GLOBAL]"); return false; } @@ -64,8 +66,8 @@ bool SatelliteClient::initialize(void) m_satellite_id = "satellite"; m_cfg.getValue("GLOBAL", "SATELLITE_ID", m_satellite_id); - cout << "SATELLITE: Connecting to parent " << m_parent_host - << ":" << m_parent_port << " as '" << m_satellite_id << "'" << endl; + geulog::info("satellite", "Connecting to parent ", m_parent_host, + ":", m_parent_port, " as '", m_satellite_id, "'"); m_con.addStaticSRVRecord(0, 0, 0, m_parent_port, m_parent_host); m_con.connect(); @@ -106,8 +108,8 @@ void SatelliteClient::onLocalFlush(uint32_t tg) void SatelliteClient::onConnected(void) { - cout << "SATELLITE: Connected to parent " << m_con.remoteHost() - << ":" << m_con.remotePort() << endl; + geulog::info("satellite", "Connected to parent ", m_con.remoteHost(), + ":", m_con.remotePort()); m_hello_received = false; m_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; @@ -123,8 +125,8 @@ void SatelliteClient::onConnected(void) void SatelliteClient::onDisconnected(TcpConnection* con, TcpConnection::DisconnectReason reason) { - cout << "SATELLITE: Disconnected from parent: " - << TcpConnection::disconnectReasonStr(reason) << endl; + geulog::info("satellite", "Disconnected from parent: ", + TcpConnection::disconnectReasonStr(reason)); m_heartbeat_timer.setEnable(false); m_hello_received = false; @@ -142,7 +144,7 @@ void SatelliteClient::onFrameReceived(FramedTcpConnection* con, ReflectorMsg header; if (!header.unpack(ss)) { - cerr << "*** ERROR[SATELLITE]: Failed to unpack message header" << endl; + geulog::error("satellite", "Failed to unpack message header"); return; } @@ -191,19 +193,19 @@ void SatelliteClient::handleMsgTrunkHello(std::istream& is) MsgTrunkHello msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[SATELLITE]: Failed to unpack MsgTrunkHello" << endl; + geulog::error("satellite", "Failed to unpack MsgTrunkHello"); return; } if (!msg.verify(m_secret)) { - cerr << "*** ERROR[SATELLITE]: Parent authentication failed" << endl; + geulog::error("satellite", "Parent authentication failed"); m_con.disconnect(); return; } m_hello_received = true; - cout << "SATELLITE: Parent authenticated (id='" << msg.id() << "')" << endl; + geulog::info("satellite", "Parent authenticated (id='", msg.id(), "')"); } /* SatelliteClient::handleMsgTrunkHello */ @@ -256,8 +258,7 @@ void SatelliteClient::sendMsg(const ReflectorMsg& msg) ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { - cerr << "*** ERROR[SATELLITE]: Failed to pack message type=" - << msg.type() << endl; + geulog::error("satellite", "Failed to pack message type=", msg.type()); return; } m_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; @@ -275,7 +276,7 @@ void SatelliteClient::heartbeatTick(Async::Timer* t) if (--m_hb_rx_cnt == 0) { - cerr << "*** ERROR[SATELLITE]: Heartbeat timeout — disconnecting" << endl; + geulog::error("satellite", "Heartbeat timeout — disconnecting"); m_con.disconnect(); } } /* SatelliteClient::heartbeatTick */ diff --git a/src/svxlink/reflector/SatelliteLink.cpp b/src/svxlink/reflector/SatelliteLink.cpp index b6325ed..bd76f02 100644 --- a/src/svxlink/reflector/SatelliteLink.cpp +++ b/src/svxlink/reflector/SatelliteLink.cpp @@ -1,6 +1,8 @@ #include #include +#include + #include "SatelliteLink.h" #include "ReflectorMsg.h" #include "Reflector.h" @@ -96,8 +98,7 @@ void SatelliteLink::onFrameReceived(FramedTcpConnection* con, ReflectorMsg header; if (!header.unpack(ss)) { - cerr << "*** ERROR[SAT]: Failed to unpack satellite message header" - << endl; + geulog::error("satellite", "Failed to unpack satellite message header"); return; } @@ -105,8 +106,8 @@ void SatelliteLink::onFrameReceived(FramedTcpConnection* con, header.type() != MsgTrunkHello::TYPE && header.type() != MsgTrunkHeartbeat::TYPE) { - cerr << "*** WARNING[SAT]: Ignoring message type=" << header.type() - << " before hello" << endl; + geulog::warn("satellite", "Ignoring message type=", header.type(), + " before hello"); return; } @@ -133,8 +134,7 @@ void SatelliteLink::onFrameReceived(FramedTcpConnection* con, handleMsgTrunkFlush(ss); break; default: - cerr << "*** WARNING[SAT]: Unknown message type=" << header.type() - << endl; + geulog::warn("satellite", "Unknown message type=", header.type()); break; } } /* SatelliteLink::onFrameReceived */ @@ -150,29 +150,29 @@ void SatelliteLink::handleMsgTrunkHello(std::istream& is) MsgTrunkHello msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[SAT]: Failed to unpack MsgTrunkHello" << endl; + geulog::error("satellite", "Failed to unpack MsgTrunkHello"); return; } if (msg.id().empty()) { - cerr << "*** ERROR[SAT]: Satellite sent empty ID" << endl; + geulog::error("satellite", "Satellite sent empty ID"); m_con->disconnect(); return; } if (msg.role() != MsgTrunkHello::ROLE_SATELLITE) { - cerr << "*** ERROR[SAT]: Expected ROLE_SATELLITE from '" << msg.id() - << "' but got role=" << (int)msg.role() << endl; + geulog::error("satellite", "Expected ROLE_SATELLITE from '", msg.id(), + "' but got role=", (int)msg.role()); m_con->disconnect(); return; } if (!msg.verify(m_secret)) { - cerr << "*** ERROR[SAT]: Authentication failed for satellite '" - << msg.id() << "'" << endl; + geulog::error("satellite", "Authentication failed for satellite '", + msg.id(), "'"); m_con->disconnect(); return; } @@ -180,8 +180,7 @@ void SatelliteLink::handleMsgTrunkHello(std::istream& is) m_satellite_id = msg.id(); m_hello_received = true; - cout << "SAT: Satellite '" << m_satellite_id - << "' authenticated" << endl; + geulog::info("satellite", "Satellite '", m_satellite_id, "' authenticated"); // Send hello reply so the satellite client can set m_hello_received // and start forwarding local events. This also generates early @@ -272,8 +271,7 @@ void SatelliteLink::sendMsg(const ReflectorMsg& msg) ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { - cerr << "*** ERROR[SAT]: Failed to pack message type=" << msg.type() - << endl; + geulog::error("satellite", "Failed to pack message type=", msg.type()); return; } m_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; @@ -291,8 +289,8 @@ void SatelliteLink::heartbeatTick(Async::Timer* t) if (--m_hb_rx_cnt == 0) { - cerr << "*** ERROR[SAT '" << m_satellite_id - << "']: Heartbeat timeout — disconnecting" << endl; + geulog::error("satellite", "Satellite '", m_satellite_id, + "': Heartbeat timeout — disconnecting"); m_heartbeat_timer.setEnable(false); linkFailed(this); } diff --git a/src/svxlink/reflector/TGHandler.cpp b/src/svxlink/reflector/TGHandler.cpp index 78c1bf4..e73ebb1 100644 --- a/src/svxlink/reflector/TGHandler.cpp +++ b/src/svxlink/reflector/TGHandler.cpp @@ -35,6 +35,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include #include #include +#include /**************************************************************************** @@ -164,9 +165,9 @@ bool TGHandler::switchTo(ReflectorClient *client, uint32_t tg) { if (m_id_map.size() >= MAX_ACTIVE_TGS) { - std::cerr << "*** WARNING: Maximum active TG limit (" - << MAX_ACTIVE_TGS << ") reached, rejecting TG #" - << tg << std::endl; + geulog::warn("core", "Maximum active TG limit (", + static_cast(MAX_ACTIVE_TGS), + ") reached, rejecting TG #", tg); return false; } tg_info = new TGInfo(tg); @@ -286,9 +287,9 @@ void TGHandler::setTrunkTalkerForTG(uint32_t tg, const std::string& callsign) if (m_trunk_talkers.find(tg) == m_trunk_talkers.end() && m_trunk_talkers.size() >= MAX_TRUNK_TALKERS) { - std::cerr << "*** WARNING: Maximum trunk talker limit (" - << MAX_TRUNK_TALKERS << ") reached, ignoring TG #" - << tg << std::endl; + geulog::warn("trunk", "Maximum trunk talker limit (", + static_cast(MAX_TRUNK_TALKERS), + ") reached, ignoring TG #", tg); return; } m_trunk_talkers[tg] = callsign; @@ -393,8 +394,8 @@ bool TGHandler::allowTgSelection(ReflectorClient *client, uint32_t tg) } catch (std::regex_error& e) { - std::cerr << "*** WARNING: Regular expression parsing error in " - << ss.str() << "/ALLOW: " << e.what() << std::endl; + geulog::warn("core", "Regular expression parsing error in ", + ss.str(), "/ALLOW: ", e.what()); } return false; } /* TGHandler::allowTgSelection */ @@ -423,8 +424,8 @@ bool TGHandler::allowTgMonitoring(ReflectorClient *client, uint32_t tg) } catch (std::regex_error& e) { - std::cerr << "*** WARNING: Regular expression parsing error in " - << ss.str() << "/ALLOW_MONITOR: " << e.what() << std::endl; + geulog::warn("core", "Regular expression parsing error in ", + ss.str(), "/ALLOW_MONITOR: ", e.what()); } return false; } /* TGHandler::allowTgMonitoring */ @@ -477,15 +478,15 @@ void TGHandler::checkTimers(Async::Timer *t) timersub(&now, &tg_info->last_talker_timestamp, &diff); if (diff.tv_sec > TALKER_AUDIO_TIMEOUT) { - cout << tg_info->talker->callsign() << ": Talker audio timeout on TG #" - << tg_info->id << endl; + geulog::info("core", tg_info->talker->callsign(), + ": Talker audio timeout on TG #", tg_info->id); setTalkerForTG(tg_info->id, 0); } if ((tg_info->sql_timeout_cnt > 0) && (--tg_info->sql_timeout_cnt == 0)) { - cout << tg_info->talker->callsign() << ": Talker audio timeout on TG #" - << tg_info->id << endl; + geulog::info("core", tg_info->talker->callsign(), + ": Talker audio timeout on TG #", tg_info->id); tg_info->talker->setBlock(m_sql_timeout_blocktime); setTalkerForTG(tg_info->id, 0); } @@ -514,25 +515,26 @@ void TGHandler::removeClientP(TGInfo *tg_info, ReflectorClient* client) void TGHandler::printTGStatus(void) { - std::cout << "### ----------- BEGIN ----------------" << std::endl; + geulog::debug("core", "----------- BEGIN ----------------"); for (IdMap::const_iterator it = m_id_map.begin(); it != m_id_map.end(); ++it) { TGInfo *tg_info = it->second; - std::cout << "### " << tg_info->id << ": "; + std::ostringstream line; + line << tg_info->id << ": "; for (ClientSet::const_iterator it = tg_info->clients.begin(); it != tg_info->clients.end(); ++it) { ReflectorClient* client = *it; if (client == tg_info->talker) { - std::cout << "*"; + line << "*"; } - std::cout << client->callsign() << " "; + line << client->callsign() << " "; } - std::cout << std::endl; + geulog::debug("core", line.str()); } - std::cout << "### ------------ END -----------------" << std::endl; + geulog::debug("core", "------------ END -----------------"); } /* TGHandler::printTGStatus */ diff --git a/src/svxlink/reflector/TrunkLink.cpp b/src/svxlink/reflector/TrunkLink.cpp index 53d0399..f71e832 100644 --- a/src/svxlink/reflector/TrunkLink.cpp +++ b/src/svxlink/reflector/TrunkLink.cpp @@ -48,6 +48,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include #include +#include /**************************************************************************** @@ -265,13 +266,6 @@ bool TrunkLink::initialize(void) return false; } - // TRUNK_DEBUG — verbose logging for connection diagnostics - std::string debug_str; - if (m_cfg.getValue("GLOBAL", "TRUNK_DEBUG", debug_str)) - { - m_debug = (debug_str == "1" || debug_str == "true" || debug_str == "yes"); - } - // PEER_ID — name we advertise in our hello (defaults to section name). // Used by the receiving peer as the MQTT topic component for this link. if (!m_cfg.getValue(m_section, "PEER_ID", m_peer_id_config) @@ -335,7 +329,6 @@ bool TrunkLink::initialize(void) cout << " port=" << m_peer_port << " local_prefix=" << joinPrefixes(m_local_prefix) << " remote_prefix=" << joinPrefixes(m_remote_prefix) - << (m_debug ? " [debug on]" : "") << (m_blacklist_filter.empty() ? "" : " [blacklist]") << (m_allow_filter.empty() ? "" : " [whitelist]") << (m_tg_map_in.empty() ? "" : " [tg_map]") @@ -376,7 +369,6 @@ bool TrunkLink::initialize(void) cout << m_section << ": Trunk to " << m_peer_host << ":" << m_peer_port << " local_prefix=" << joinPrefixes(m_local_prefix) << " remote_prefix=" << joinPrefixes(m_remote_prefix) - << (m_debug ? " [debug on]" : "") << (m_blacklist_filter.empty() ? "" : " [blacklist]") << (m_allow_filter.empty() ? "" : " [whitelist]") << (m_tg_map_in.empty() ? "" : " [tg_map]") @@ -547,10 +539,10 @@ void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con, if (m_peer_id_received.empty()) m_peer_id_received = sanitizeIdent(hello.id(), 64); - cout << m_section << ": paired inbound accepted from peer '" - << hello.id() << "' " << con->remoteHost() << ":" - << con->remotePort() << " priority=" << hello.priority() - << " total_inbound=" << m_ib_cons.size() << endl; + geulog::info("trunk", m_section, ": paired inbound accepted from peer '", + hello.id(), "' ", con->remoteHost(), ":", + con->remotePort(), " priority=", hello.priority(), + " total_inbound=", m_ib_cons.size()); m_heartbeat_timer.setEnable(true); @@ -564,18 +556,15 @@ void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con, // Non-paired mode: only one inbound allowed if (m_inbound_con != nullptr) { - cerr << "*** WARNING[" << m_section - << "]: Already have an inbound connection, rejecting new one" << endl; - if (m_debug) - { - cerr << m_section << " [DEBUG]: existing inbound from " - << m_inbound_con->remoteHost() << ":" - << m_inbound_con->remotePort() - << " ib_hello=" << m_ib_hello_received - << " ib_hb_rx=" << m_ib_hb_rx_cnt - << " new inbound from " << con->remoteHost() << ":" - << con->remotePort() << endl; - } + geulog::warn("trunk", "[", m_section, + "]: Already have an inbound connection, rejecting new one"); + geulog::debug("trunk", m_section, ": existing inbound from ", + m_inbound_con->remoteHost(), ":", + m_inbound_con->remotePort(), + " ib_hello=", m_ib_hello_received, + " ib_hb_rx=", m_ib_hb_rx_cnt, + " new inbound from ", con->remoteHost(), ":", + con->remotePort()); con->disconnect(); return; } @@ -594,20 +583,16 @@ void TrunkLink::acceptInboundConnection(Async::FramedTcpConnection* con, mem_fun(*this, &TrunkLink::onFrameReceived)); m_peer_id_received = sanitizeIdent(hello.id(), 64); - cout << m_section << ": Accepted inbound from " << con->remoteHost() - << ":" << con->remotePort() << " peer='" << hello.id() - << "' priority=" << m_peer_priority << endl; + geulog::info("trunk", m_section, ": Accepted inbound from ", + con->remoteHost(), ":", con->remotePort(), + " peer='", hello.id(), "' priority=", m_peer_priority); m_reflector->onTrunkStateChanged(m_section, peerId(), "inbound", true, con->remoteHost().toString(), con->remotePort()); - if (m_debug) - { - cout << m_section << " [DEBUG]: inbound state: ob_connected=" - << m_con.isConnected() << " ob_hello=" << m_ob_hello_received - << " ib_hb_tx=" << m_ib_hb_tx_cnt - << " ib_hb_rx=" << m_ib_hb_rx_cnt << endl; - } + geulog::debug("trunk", m_section, ": inbound state: ob_connected=", + m_con.isConnected(), " ob_hello=", m_ob_hello_received, + " ib_hb_tx=", m_ib_hb_tx_cnt, " ib_hb_rx=", m_ib_hb_rx_cnt); // Send our hello back on the inbound connection sendMsgOnInbound(MsgTrunkHello(m_peer_id_config, @@ -627,26 +612,18 @@ void TrunkLink::onInboundDisconnected(Async::FramedTcpConnection* con, if (con != m_inbound_con) { - if (m_debug) - { - cerr << m_section << " [DEBUG]: onInboundDisconnected for unknown con " - << con->remoteHost() << ":" << con->remotePort() - << " (m_inbound_con=" - << (m_inbound_con ? "set" : "null") << ")" << endl; - } + geulog::debug("trunk", m_section, ": onInboundDisconnected for unknown con ", + con->remoteHost(), ":", con->remotePort(), + " (m_inbound_con=", (m_inbound_con ? "set" : "null"), ")"); return; } - cout << m_section << ": Inbound trunk connection lost" << endl; - - if (m_debug) - { - cout << m_section << " [DEBUG]: inbound lost: ib_hello=" << m_ib_hello_received - << " ib_hb_rx=" << m_ib_hb_rx_cnt - << " ob_connected=" << m_con.isConnected() - << " ob_hello=" << m_ob_hello_received - << " peer_active_tgs=" << m_peer_active_tgs.size() << endl; - } + geulog::info("trunk", m_section, ": Inbound trunk connection lost"); + geulog::debug("trunk", m_section, ": inbound lost: ib_hello=", + m_ib_hello_received, " ib_hb_rx=", m_ib_hb_rx_cnt, + " ob_connected=", m_con.isConnected(), + " ob_hello=", m_ob_hello_received, + " peer_active_tgs=", m_peer_active_tgs.size()); m_inbound_con = nullptr; m_ib_hello_received = false; @@ -742,18 +719,15 @@ void TrunkLink::onLocalFlush(uint32_t tg) void TrunkLink::onConnected(void) { - cout << m_section << ": Outbound connected to " << m_con.remoteHost() - << ":" << m_con.remotePort() << endl; + geulog::info("trunk", m_section, ": Outbound connected to ", + m_con.remoteHost(), ":", m_con.remotePort()); m_reflector->onTrunkStateChanged(m_section, peerId(), "outbound", true, m_con.remoteHost().toString(), m_con.remotePort()); - if (m_debug) - { - cout << m_section << " [DEBUG]: outbound up: ib_connected=" - << (m_inbound_con != nullptr) << " ib_hello=" << m_ib_hello_received - << " sending hello with priority=" << m_priority << endl; - } + geulog::debug("trunk", m_section, ": outbound up: ib_connected=", + (m_inbound_con != nullptr), " ib_hello=", m_ib_hello_received, + " sending hello with priority=", m_priority); m_ob_hello_received = false; m_ob_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; @@ -769,16 +743,12 @@ void TrunkLink::onConnected(void) void TrunkLink::onDisconnected(TcpConnection* con, TcpConnection::DisconnectReason reason) { - cout << m_section << ": Outbound disconnected: " - << TcpConnection::disconnectReasonStr(reason) << endl; - - if (m_debug) - { - cout << m_section << " [DEBUG]: outbound lost: ob_hello=" << m_ob_hello_received - << " ob_hb_rx=" << m_ob_hb_rx_cnt - << " ib_connected=" << (m_inbound_con != nullptr) - << " ib_hello=" << m_ib_hello_received << endl; - } + geulog::info("trunk", m_section, ": Outbound disconnected: ", + TcpConnection::disconnectReasonStr(reason)); + geulog::debug("trunk", m_section, ": outbound lost: ob_hello=", + m_ob_hello_received, " ob_hb_rx=", m_ob_hb_rx_cnt, + " ib_connected=", (m_inbound_con != nullptr), + " ib_hello=", m_ib_hello_received); m_ob_hello_received = false; m_ob_hb_tx_cnt = 0; @@ -808,8 +778,7 @@ void TrunkLink::onFrameReceived(FramedTcpConnection* con, ReflectorMsg header; if (!header.unpack(ss)) { - cerr << "*** ERROR[" << m_section << "]: Failed to unpack trunk message " - "header" << endl; + geulog::error("trunk", "[", m_section, "] Failed to unpack trunk message header"); return; } @@ -822,9 +791,8 @@ void TrunkLink::onFrameReceived(FramedTcpConnection* con, header.type() != MsgTrunkHello::TYPE && header.type() != MsgTrunkHeartbeat::TYPE) { - cerr << "*** WARNING[" << m_section - << "]: Ignoring trunk message type=" << header.type() - << " before hello" << endl; + geulog::warn("trunk", "[", m_section, "] Ignoring trunk message type=", + header.type(), " before hello"); return; } @@ -838,27 +806,10 @@ void TrunkLink::onFrameReceived(FramedTcpConnection* con, m_ob_hb_rx_cnt = HEARTBEAT_RX_CNT_RESET; } - if (m_debug && header.type() != MsgTrunkHeartbeat::TYPE) + if (header.type() != MsgTrunkHeartbeat::TYPE) { - if (header.type() == MsgTrunkAudio::TYPE || - header.type() == MsgTrunkFlush::TYPE) - { - if (m_debug_frame_cnt < 500) - { - cout << m_section << " [DEBUG]: rx " << (is_inbound ? "IB" : "OB") - << " type=" << header.type() << " len=" << data.size() << endl; - if (++m_debug_frame_cnt == 500) - { - cout << m_section << " [DEBUG]: audio frame log limit reached (500)" - << " — suppressing further audio/flush debug" << endl; - } - } - } - else - { - cout << m_section << " [DEBUG]: rx " << (is_inbound ? "IB" : "OB") - << " type=" << header.type() << " len=" << data.size() << endl; - } + geulog::debug("trunk", m_section, ": rx ", (is_inbound ? "IB" : "OB"), + " type=", header.type(), " len=", data.size()); } switch (header.type()) @@ -885,8 +836,8 @@ void TrunkLink::onFrameReceived(FramedTcpConnection* con, handleMsgTrunkNodeList(ss); break; default: - cerr << "*** WARNING[" << m_section - << "]: Unknown trunk message type=" << header.type() << endl; + geulog::warn("trunk", "[", m_section, "] Unknown trunk message type=", + header.type()); break; } } /* TrunkLink::onFrameReceived */ @@ -905,11 +856,7 @@ void TrunkLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) // background reconnect) — ignore it silently. if (is_inbound) { - if (m_debug) - { - cout << m_section << " [DEBUG]: ignoring duplicate hello on inbound" - << endl; - } + geulog::debug("trunk", m_section, ": ignoring duplicate hello on inbound"); return; } @@ -917,15 +864,14 @@ void TrunkLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) MsgTrunkHello msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[" << m_section << "]: Failed to unpack MsgTrunkHello" - << endl; + geulog::error("trunk", "[", m_section, "] Failed to unpack MsgTrunkHello"); return; } if (msg.id().empty()) { - cerr << "*** ERROR[" << m_section - << "]: Peer sent empty trunk ID in MsgTrunkHello" << endl; + geulog::error("trunk", "[", m_section, + "] Peer sent empty trunk ID in MsgTrunkHello"); m_con.disconnect(); return; } @@ -933,9 +879,9 @@ void TrunkLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) // Verify shared secret via HMAC if (!msg.verify(m_secret)) { - cerr << "*** ERROR[" << m_section - << "]: Trunk authentication failed — peer '" << msg.id() - << "' sent invalid secret (HMAC mismatch)" << endl; + geulog::error("trunk", "[", m_section, + "] Trunk authentication failed — peer '", msg.id(), + "' sent invalid secret (HMAC mismatch)"); m_con.disconnect(); return; } @@ -944,18 +890,14 @@ void TrunkLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) m_peer_id_received = sanitizeIdent(msg.id(), 64); m_ob_hello_received = true; - cout << m_section << ": Trunk hello from peer '" << msg.id() - << "' local_prefix=" << msg.localPrefix() - << " priority=" << m_peer_priority - << " (authenticated)" << endl; - - if (m_debug) - { - cout << m_section << " [DEBUG]: hello done: ob_hello=" << m_ob_hello_received - << " ib_connected=" << (m_inbound_con != nullptr) - << " ib_hello=" << m_ib_hello_received - << " isActive=" << isActive() << endl; - } + geulog::info("trunk", m_section, ": Trunk hello from peer '", msg.id(), + "' local_prefix=", msg.localPrefix(), + " priority=", m_peer_priority, " (authenticated)"); + geulog::debug("trunk", m_section, ": hello done: ob_hello=", + m_ob_hello_received, + " ib_connected=", (m_inbound_con != nullptr), + " ib_hello=", m_ib_hello_received, + " isActive=", isActive()); } /* TrunkLink::handleMsgTrunkHello */ @@ -964,8 +906,7 @@ void TrunkLink::handleMsgTrunkTalkerStart(std::istream& is) MsgTrunkTalkerStart msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[" << m_section - << "]: Failed to unpack MsgTrunkTalkerStart" << endl; + geulog::error("trunk", "[", m_section, "] Failed to unpack MsgTrunkTalkerStart"); return; } @@ -989,15 +930,15 @@ void TrunkLink::handleMsgTrunkTalkerStart(std::istream& is) if (m_priority <= m_peer_priority) { // We win — ignore peer's claim - cout << m_section << ": TG #" << local_tg - << " conflict — local wins (our priority=" << m_priority - << " <= peer=" << m_peer_priority << ")" << endl; + geulog::info("trunk", m_section, ": TG #", local_tg, + " conflict — local wins (our priority=", m_priority, + " <= peer=", m_peer_priority, ")"); return; } // We defer — clear local talker and accept remote - cout << m_section << ": TG #" << local_tg - << " conflict — deferring to peer (our priority=" << m_priority - << " > peer=" << m_peer_priority << ")" << endl; + geulog::info("trunk", m_section, ": TG #", local_tg, + " conflict — deferring to peer (our priority=", m_priority, + " > peer=", m_peer_priority, ")"); m_yielded_tgs.insert(local_tg); TGHandler::instance()->setTalkerForTG(local_tg, nullptr); // onTalkerUpdated will fire; Reflector must not re-send TrunkTalkerStart @@ -1016,8 +957,7 @@ void TrunkLink::handleMsgTrunkTalkerStop(std::istream& is) MsgTrunkTalkerStop msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[" << m_section - << "]: Failed to unpack MsgTrunkTalkerStop" << endl; + geulog::error("trunk", "[", m_section, "] Failed to unpack MsgTrunkTalkerStop"); return; } @@ -1045,8 +985,7 @@ void TrunkLink::handleMsgTrunkAudio(std::istream& is) MsgTrunkAudio msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[" << m_section - << "]: Failed to unpack MsgTrunkAudio" << endl; + geulog::error("trunk", "[", m_section, "] Failed to unpack MsgTrunkAudio"); return; } @@ -1093,8 +1032,7 @@ void TrunkLink::handleMsgTrunkFlush(std::istream& is) MsgTrunkFlush msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[" << m_section - << "]: Failed to unpack MsgTrunkFlush" << endl; + geulog::error("trunk", "[", m_section, "] Failed to unpack MsgTrunkFlush"); return; } @@ -1133,8 +1071,8 @@ void TrunkLink::sendMsg(const ReflectorMsg& msg) { if (idx != m_sticky_ob_idx) { - cout << m_section << ": sticky OB switched from #" - << m_sticky_ob_idx << " to #" << idx << endl; + geulog::info("trunk", m_section, ": sticky OB switched from #", + m_sticky_ob_idx, " to #", idx); m_sticky_ob_idx = idx; } sendMsgOnPairedOutbound(idx, msg); @@ -1147,20 +1085,14 @@ void TrunkLink::sendMsg(const ReflectorMsg& msg) { if (m_ib_cons[i]->isConnected() && m_ib_states[i].hello_received) { - if (m_debug) - { - cout << m_section << " [DEBUG]: paired tx fallback to IB#" << i - << " type=" << msg.type() << endl; - } + geulog::debug("trunk", m_section, ": paired tx fallback to IB#", i, + " type=", msg.type()); sendMsgOnPairedInbound(i, msg); return; } } - if (m_debug) - { - cerr << m_section << " [DEBUG]: paired tx dropped type=" << msg.type() - << " (no active connection)" << endl; - } + geulog::debug("trunk", m_section, ": paired tx dropped type=", msg.type(), + " (no active connection)"); return; } @@ -1170,17 +1102,13 @@ void TrunkLink::sendMsg(const ReflectorMsg& msg) } else if (isInboundReady()) { - if (m_debug) - { - cout << m_section << " [DEBUG]: tx fallback to IB type=" - << msg.type() << endl; - } + geulog::debug("trunk", m_section, ": tx fallback to IB type=", msg.type()); sendMsgOnInbound(msg); } - else if (m_debug) + else { - cerr << m_section << " [DEBUG]: tx dropped type=" << msg.type() - << " (no active connection)" << endl; + geulog::debug("trunk", m_section, ": tx dropped type=", msg.type(), + " (no active connection)"); } } /* TrunkLink::sendMsg */ @@ -1191,8 +1119,8 @@ void TrunkLink::sendMsgOnOutbound(const ReflectorMsg& msg) ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { - cerr << "*** ERROR[" << m_section << "]: Failed to pack trunk message " - "type=" << msg.type() << endl; + geulog::error("trunk", "[", m_section, "] Failed to pack trunk message type=", + msg.type()); return; } m_ob_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; @@ -1207,8 +1135,8 @@ void TrunkLink::sendMsgOnInbound(const ReflectorMsg& msg) ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { - cerr << "*** ERROR[" << m_section << "]: Failed to pack trunk message " - "type=" << msg.type() << endl; + geulog::error("trunk", "[", m_section, "] Failed to pack trunk message type=", + msg.type()); return; } m_ib_hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; @@ -1229,23 +1157,20 @@ void TrunkLink::heartbeatTick(Async::Timer* t) any_ob_connected = true; if (--m_ob_states[i].hb_tx_cnt == 0) { - if (m_debug) - { - cout << m_section << " [DEBUG]: paired OB#" << i << " heartbeat tx" - << " hb_rx=" << m_ob_states[i].hb_rx_cnt << endl; - } + geulog::debug("trunk", m_section, ": paired OB#", i, " heartbeat tx", + " hb_rx=", m_ob_states[i].hb_rx_cnt); sendMsgOnPairedOutbound(i, MsgTrunkHeartbeat()); } if (--m_ob_states[i].hb_rx_cnt == 0) { - cerr << "*** ERROR[" << m_section - << "]: Paired outbound #" << i << " heartbeat timeout" << endl; + geulog::error("trunk", "[", m_section, "] Paired outbound #", i, + " heartbeat timeout"); m_ob_cons[i]->disconnect(); } - else if (m_debug && m_ob_states[i].hb_rx_cnt <= 5) + else if (m_ob_states[i].hb_rx_cnt <= 5) { - cerr << m_section << " [DEBUG]: paired OB#" << i - << " heartbeat rx countdown: " << m_ob_states[i].hb_rx_cnt << endl; + geulog::debug("trunk", m_section, ": paired OB#", i, + " heartbeat rx countdown: ", m_ob_states[i].hb_rx_cnt); } } @@ -1258,23 +1183,20 @@ void TrunkLink::heartbeatTick(Async::Timer* t) any_ib_connected = true; if (--m_ib_states[i].hb_tx_cnt == 0) { - if (m_debug) - { - cout << m_section << " [DEBUG]: paired IB#" << i << " heartbeat tx" - << " hb_rx=" << m_ib_states[i].hb_rx_cnt << endl; - } + geulog::debug("trunk", m_section, ": paired IB#", i, " heartbeat tx", + " hb_rx=", m_ib_states[i].hb_rx_cnt); sendMsgOnPairedInbound(i, MsgTrunkHeartbeat()); } if (--m_ib_states[i].hb_rx_cnt == 0) { - cerr << "*** ERROR[" << m_section - << "]: Paired inbound #" << i << " heartbeat timeout" << endl; + geulog::error("trunk", "[", m_section, "] Paired inbound #", i, + " heartbeat timeout"); m_ib_cons[i]->disconnect(); } - else if (m_debug && m_ib_states[i].hb_rx_cnt <= 5) + else if (m_ib_states[i].hb_rx_cnt <= 5) { - cerr << m_section << " [DEBUG]: paired IB#" << i - << " heartbeat rx countdown: " << m_ib_states[i].hb_rx_cnt << endl; + geulog::debug("trunk", m_section, ": paired IB#", i, + " heartbeat rx countdown: ", m_ib_states[i].hb_rx_cnt); } } @@ -1302,23 +1224,19 @@ void TrunkLink::heartbeatTick(Async::Timer* t) { if (--m_ob_hb_tx_cnt == 0) { - if (m_debug) - { - cout << m_section << " [DEBUG]: OB heartbeat tx" - << " ob_hb_rx=" << m_ob_hb_rx_cnt << endl; - } + geulog::debug("trunk", m_section, ": OB heartbeat tx ob_hb_rx=", + m_ob_hb_rx_cnt); sendMsgOnOutbound(MsgTrunkHeartbeat()); } if (--m_ob_hb_rx_cnt == 0) { - cerr << "*** ERROR[" << m_section - << "]: Outbound heartbeat timeout" << endl; + geulog::error("trunk", "[", m_section, "] Outbound heartbeat timeout"); m_con.disconnect(); } - else if (m_debug && m_ob_hb_rx_cnt <= 5) + else if (m_ob_hb_rx_cnt <= 5) { - cerr << m_section << " [DEBUG]: OB heartbeat rx countdown: " - << m_ob_hb_rx_cnt << endl; + geulog::debug("trunk", m_section, ": OB heartbeat rx countdown: ", + m_ob_hb_rx_cnt); } } @@ -1327,23 +1245,19 @@ void TrunkLink::heartbeatTick(Async::Timer* t) { if (--m_ib_hb_tx_cnt == 0) { - if (m_debug) - { - cout << m_section << " [DEBUG]: IB heartbeat tx" - << " ib_hb_rx=" << m_ib_hb_rx_cnt << endl; - } + geulog::debug("trunk", m_section, ": IB heartbeat tx ib_hb_rx=", + m_ib_hb_rx_cnt); sendMsgOnInbound(MsgTrunkHeartbeat()); } if (--m_ib_hb_rx_cnt == 0) { - cerr << "*** ERROR[" << m_section - << "]: Inbound heartbeat timeout" << endl; + geulog::error("trunk", "[", m_section, "] Inbound heartbeat timeout"); m_inbound_con->disconnect(); } - else if (m_debug && m_ib_hb_rx_cnt <= 5) + else if (m_ib_hb_rx_cnt <= 5) { - cerr << m_section << " [DEBUG]: IB heartbeat rx countdown: " - << m_ib_hb_rx_cnt << endl; + geulog::debug("trunk", m_section, ": IB heartbeat rx countdown: ", + m_ib_hb_rx_cnt); } } @@ -1426,8 +1340,8 @@ void TrunkLink::sendMsgOnPairedOutbound(size_t idx, const ReflectorMsg& msg) ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { - cerr << "*** ERROR[" << m_section << "]: Failed to pack trunk message " - "type=" << msg.type() << " for paired outbound #" << idx << endl; + geulog::error("trunk", "[", m_section, "] Failed to pack trunk message type=", + msg.type(), " for paired outbound #", idx); return; } m_ob_states[idx].hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; @@ -1454,8 +1368,8 @@ void TrunkLink::sendMsgOnPairedInbound(size_t idx, const ReflectorMsg& msg) ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { - cerr << "*** ERROR[" << m_section << "]: Failed to pack trunk message " - "type=" << msg.type() << " for paired inbound #" << idx << endl; + geulog::error("trunk", "[", m_section, "] Failed to pack trunk message type=", + msg.type(), " for paired inbound #", idx); return; } m_ib_states[idx].hb_tx_cnt = HEARTBEAT_TX_CNT_RESET; @@ -1479,8 +1393,8 @@ void TrunkLink::onPairedInboundFrame(Async::FramedTcpConnection* con, ReflectorMsg header; if (!header.unpack(ss)) { - cerr << "*** ERROR[" << m_section - << "]: Failed to unpack frame on paired inbound #" << idx << endl; + geulog::error("trunk", "[", m_section, + "] Failed to unpack frame on paired inbound #", idx); return; } @@ -1515,9 +1429,8 @@ void TrunkLink::onPairedInboundFrame(Async::FramedTcpConnection* con, handleMsgTrunkNodeList(ss); break; default: - cerr << "*** WARNING[" << m_section - << "]: Unknown trunk message type=" << header.type() - << " on paired ib#" << idx << endl; + geulog::warn("trunk", "[", m_section, "] Unknown trunk message type=", + header.type(), " on paired ib#", idx); break; } break; @@ -1530,8 +1443,8 @@ void TrunkLink::onPairedInboundDisconnected(Async::FramedTcpConnection* con, { size_t idx = pairedInboundIndex(con); if (idx == SIZE_MAX) return; - cout << m_section << ": paired inbound #" << idx << " disconnected" - << " remaining=" << (m_ib_cons.size() - 1) << endl; + geulog::info("trunk", m_section, ": paired inbound #", idx, " disconnected", + " remaining=", (m_ib_cons.size() - 1)); m_ib_cons.erase(m_ib_cons.begin() + idx); m_ib_states.erase(m_ib_states.begin() + idx); // Reflector owns the connection object — do NOT delete it here. @@ -1548,14 +1461,10 @@ void TrunkLink::onPairedOutboundConnected(FramedTcpClient* client) m_ob_states[idx].hb_rx_cnt = HEARTBEAT_RX_CNT_RESET; m_heartbeat_timer.setEnable(true); - cout << m_section << ": paired outbound #" << idx - << " connected to " << m_peer_hosts[idx] << ":" << m_peer_port << endl; - - if (m_debug) - { - cout << m_section << " [DEBUG]: paired ob#" << idx - << " sending hello with priority=" << m_priority << endl; - } + geulog::info("trunk", m_section, ": paired outbound #", idx, + " connected to ", m_peer_hosts[idx], ":", m_peer_port); + geulog::debug("trunk", m_section, ": paired ob#", idx, + " sending hello with priority=", m_priority); sendMsgOnPairedOutbound(idx, MsgTrunkHello(m_peer_id_config, joinPrefixes(m_local_prefix), @@ -1570,9 +1479,9 @@ void TrunkLink::onPairedOutboundDisconnected(FramedTcpClient* client, size_t idx = pairedClientIndex(client); if (idx == SIZE_MAX) return; - cout << m_section << ": paired outbound #" << idx - << " disconnected (" - << Async::TcpConnection::disconnectReasonStr(reason) << ")" << endl; + geulog::info("trunk", m_section, ": paired outbound #", idx, + " disconnected (", + Async::TcpConnection::disconnectReasonStr(reason), ")"); m_ob_states[idx].hello_received = false; m_ob_states[idx].hb_tx_cnt = 0; @@ -1603,8 +1512,8 @@ void TrunkLink::onPairedOutboundFrame(FramedTcpClient* client, ReflectorMsg header; if (!header.unpack(ss)) { - cerr << "*** ERROR[" << m_section - << "]: Failed to unpack frame on paired outbound #" << idx << endl; + geulog::error("trunk", "[", m_section, + "] Failed to unpack frame on paired outbound #", idx); return; } @@ -1613,9 +1522,8 @@ void TrunkLink::onPairedOutboundFrame(FramedTcpClient* client, header.type() != MsgTrunkHello::TYPE && header.type() != MsgTrunkHeartbeat::TYPE) { - cerr << "*** WARNING[" << m_section - << "]: Ignoring paired ob#" << idx << " msg type=" << header.type() - << " before hello" << endl; + geulog::warn("trunk", "[", m_section, "] Ignoring paired ob#", idx, + " msg type=", header.type(), " before hello"); return; } @@ -1628,17 +1536,16 @@ void TrunkLink::onPairedOutboundFrame(FramedTcpClient* client, if (msg.id().empty()) { - cerr << "*** ERROR[" << m_section - << "]: Peer sent empty ID on paired ob#" << idx << endl; + geulog::error("trunk", "[", m_section, + "] Peer sent empty ID on paired ob#", idx); client->disconnect(); return; } if (!msg.verify(m_secret)) { - cerr << "*** ERROR[" << m_section - << "]: HMAC failed on paired outbound #" << idx - << " (peer='" << msg.id() << "')" << endl; + geulog::error("trunk", "[", m_section, "] HMAC failed on paired outbound #", + idx, " (peer='", msg.id(), "')"); client->disconnect(); return; } @@ -1650,9 +1557,9 @@ void TrunkLink::onPairedOutboundFrame(FramedTcpClient* client, if (m_peer_id_received.empty()) m_peer_id_received = sanitizeIdent(msg.id(), 64); - cout << m_section << ": paired outbound #" << idx - << " hello received (peer='" << msg.id() - << "' priority=" << msg.priority() << " authenticated)" << endl; + geulog::info("trunk", m_section, ": paired outbound #", idx, + " hello received (peer='", msg.id(), + "' priority=", msg.priority(), " authenticated)"); break; } @@ -1682,9 +1589,8 @@ void TrunkLink::onPairedOutboundFrame(FramedTcpClient* client, handleMsgTrunkNodeList(ss); break; default: - cerr << "*** WARNING[" << m_section - << "]: Unknown trunk message type=" << header.type() - << " on paired ob#" << idx << endl; + geulog::warn("trunk", "[", m_section, "] Unknown trunk message type=", + header.type(), " on paired ob#", idx); break; } break; @@ -1762,13 +1668,12 @@ void TrunkLink::reloadConfig(void) } } - 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() - << endl; + geulog::info("trunk", 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()); } /* TrunkLink::reloadConfig */ @@ -1785,8 +1690,7 @@ void TrunkLink::handleMsgTrunkNodeList(std::istream& is) MsgTrunkNodeList msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[" << m_section - << "]: Failed to unpack MsgTrunkNodeList" << endl; + geulog::error("trunk", "[", m_section, "] Failed to unpack MsgTrunkNodeList"); return; } @@ -1827,9 +1731,8 @@ void TrunkLink::handleMsgTrunkNodeList(std::istream& is) } if (dropped > 0) { - cerr << "*** WARN[" << m_section << "]: dropped " << dropped - << " node list entrie(s) with empty/invalid callsign after " - "sanitization" << endl; + geulog::warn("trunk", "[", m_section, "] dropped ", dropped, + " node list entrie(s) with empty/invalid callsign after sanitization"); } m_reflector->onPeerNodeList(peerId(), sanitized); diff --git a/src/svxlink/reflector/TrunkLink.h b/src/svxlink/reflector/TrunkLink.h index 67302b1..af2a38f 100644 --- a/src/svxlink/reflector/TrunkLink.h +++ b/src/svxlink/reflector/TrunkLink.h @@ -181,8 +181,6 @@ class TrunkLink : public sigc::trackable Reflector* m_reflector; Async::Config& m_cfg; std::string m_section; - bool m_debug = false; - unsigned m_debug_frame_cnt = 0; std::string m_peer_host; uint16_t m_peer_port; std::string m_secret; diff --git a/src/svxlink/reflector/TwinLink.cpp b/src/svxlink/reflector/TwinLink.cpp index 6777b2b..25d9f07 100644 --- a/src/svxlink/reflector/TwinLink.cpp +++ b/src/svxlink/reflector/TwinLink.cpp @@ -56,6 +56,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "ReflectorMsg.h" #include "Reflector.h" #include "TGHandler.h" +#include /**************************************************************************** @@ -172,14 +173,13 @@ void TwinLink::acceptInboundConnection(Async::FramedTcpConnection* con, // without a clean FIN). if (!m_inbound_con->isConnected()) { - cout << "TWIN: replacing stale inbound connection" << endl; + geulog::info("twin", "TWIN: replacing stale inbound connection"); m_inbound_con = nullptr; m_ib_hello_received = false; } else { - cerr << "*** WARNING[TWIN]: Already have an inbound connection, " - "rejecting new one" << endl; + geulog::warn("twin", "TWIN: Already have an inbound connection, rejecting new one"); con->disconnect(); return; } @@ -201,7 +201,7 @@ void TwinLink::acceptInboundConnection(Async::FramedTcpConnection* con, Async::TcpConnection::DisconnectReason /*reason*/) { if (m_inbound_con == c) { - cout << "TWIN: inbound disconnected" << endl; + geulog::info("twin", "TWIN: inbound disconnected"); m_inbound_con = nullptr; m_ib_hello_received = false; m_ib_hb_tx_cnt = 0; @@ -210,9 +210,9 @@ void TwinLink::acceptInboundConnection(Async::FramedTcpConnection* con, }); m_peer_id_received = hello.id(); - cout << "TWIN: Accepted inbound from " << con->remoteHost() << ":" - << con->remotePort() << " peer='" << hello.id() - << "' priority=" << m_peer_priority << endl; + geulog::info("twin", "TWIN: Accepted inbound from ", con->remoteHost(), ":", + con->remotePort(), " peer='", hello.id(), + "' priority=", m_peer_priority); // Send our hello back on the inbound connection sendMsgOnInbound(MsgTrunkHello(m_peer_id_config, m_local_prefix, @@ -283,8 +283,7 @@ bool TwinLink::isActive(void) const void TwinLink::onConnected(void) { - cout << "TWIN: outbound connected to " << m_peer_host << ":" - << m_peer_port << endl; + geulog::info("twin", "TWIN: outbound connected to ", m_peer_host, ":", m_peer_port); m_ob_hello_received = false; m_ob_hb_tx_cnt = 0; m_ob_hb_rx_cnt = 0; @@ -299,8 +298,8 @@ void TwinLink::onConnected(void) void TwinLink::onDisconnected(TcpConnection* /*con*/, TcpConnection::DisconnectReason reason) { - cout << "TWIN: outbound disconnected: " - << TcpConnection::disconnectReasonStr(reason) << endl; + geulog::info("twin", "TWIN: outbound disconnected: ", + TcpConnection::disconnectReasonStr(reason)); m_ob_hello_received = false; m_ob_hb_tx_cnt = 0; m_ob_hb_rx_cnt = 0; @@ -328,7 +327,7 @@ void TwinLink::onFrameReceived(FramedTcpConnection* con, ReflectorMsg header; if (!header.unpack(ss)) { - cerr << "*** ERROR[TWIN]: Failed to unpack frame header" << endl; + geulog::error("twin", "TWIN: Failed to unpack frame header"); return; } @@ -337,8 +336,7 @@ void TwinLink::onFrameReceived(FramedTcpConnection* con, header.type() != MsgTrunkHello::TYPE && header.type() != MsgTrunkHeartbeat::TYPE) { - cerr << "*** WARNING[TWIN]: Ignoring message type=" << header.type() - << " before hello" << endl; + geulog::warn("twin", "TWIN: Ignoring message type=", header.type(), " before hello"); return; } @@ -398,14 +396,14 @@ void TwinLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) MsgTrunkHello msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[TWIN]: Failed to unpack MsgTrunkHello" << endl; + geulog::error("twin", "TWIN: Failed to unpack MsgTrunkHello"); return; } if (msg.role() != MsgTrunkHello::ROLE_TWIN) { - cerr << "*** ERROR[TWIN]: peer sent role=" << int(msg.role()) - << " but we expect ROLE_TWIN" << endl; + geulog::error("twin", "TWIN: peer sent role=", int(msg.role()), + " but we expect ROLE_TWIN"); m_con.disconnect(); return; } @@ -413,8 +411,8 @@ void TwinLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) // Verify shared secret via HMAC if (!msg.verify(m_secret)) { - cerr << "*** ERROR[TWIN]: HMAC authentication failed — peer '" << msg.id() - << "' sent invalid secret" << endl; + geulog::error("twin", "TWIN: HMAC authentication failed — peer '", msg.id(), + "' sent invalid secret"); m_con.disconnect(); return; } @@ -422,9 +420,8 @@ void TwinLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) // Both partners must share the same LOCAL_PREFIX if (msg.localPrefix() != m_local_prefix) { - cerr << "*** ERROR[TWIN]: local_prefix mismatch: ours='" - << m_local_prefix << "' theirs='" << msg.localPrefix() << "'" - << endl; + geulog::error("twin", "TWIN: local_prefix mismatch: ours='", + m_local_prefix, "' theirs='", msg.localPrefix(), "'"); m_con.disconnect(); return; } @@ -433,8 +430,8 @@ void TwinLink::handleMsgTrunkHello(std::istream& is, bool is_inbound) m_peer_id_received = msg.id(); m_ob_hello_received = true; - cout << "TWIN: hello from partner '" << msg.id() - << "' priority=" << m_peer_priority << " (authenticated)" << endl; + geulog::info("twin", "TWIN: hello from partner '", msg.id(), + "' priority=", m_peer_priority, " (authenticated)"); } /* TwinLink::handleMsgTrunkHello */ @@ -443,7 +440,7 @@ void TwinLink::handleMsgTrunkTalkerStart(std::istream& is) MsgTrunkTalkerStart msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[TWIN]: Failed to unpack MsgTrunkTalkerStart" << endl; + geulog::error("twin", "TWIN: Failed to unpack MsgTrunkTalkerStart"); return; } // setTrunkTalkerForTG fires trunkTalkerUpdated → onTrunkTalkerUpdated in @@ -457,7 +454,7 @@ void TwinLink::handleMsgTrunkTalkerStop(std::istream& is) MsgTrunkTalkerStop msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[TWIN]: Failed to unpack MsgTrunkTalkerStop" << endl; + geulog::error("twin", "TWIN: Failed to unpack MsgTrunkTalkerStop"); return; } // clearTrunkTalkerForTG fires trunkTalkerUpdated → onTrunkTalkerUpdated, @@ -471,7 +468,7 @@ void TwinLink::handleMsgTrunkAudio(std::istream& is) MsgTrunkAudio msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[TWIN]: Failed to unpack MsgTrunkAudio" << endl; + geulog::error("twin", "TWIN: Failed to unpack MsgTrunkAudio"); return; } if (msg.audio().empty()) return; @@ -486,7 +483,7 @@ void TwinLink::handleMsgTrunkFlush(std::istream& is) MsgTrunkFlush msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[TWIN]: Failed to unpack MsgTrunkFlush" << endl; + geulog::error("twin", "TWIN: Failed to unpack MsgTrunkFlush"); return; } m_reflector->broadcastUdpMsg(MsgUdpFlushSamples(), @@ -506,7 +503,7 @@ void TwinLink::handleMsgTwinExtTalkerStart(std::istream& is) MsgTwinExtTalkerStart msg; if (!msg.unpack(is)) { - cerr << "*** ERROR[TWIN]: Failed to unpack MsgTwinExtTalkerStart" << endl; + geulog::error("twin", "TWIN: Failed to unpack MsgTwinExtTalkerStart"); return; } // setTrunkTalkerForTGViaPeer records peer attribution and fires @@ -544,7 +541,7 @@ void TwinLink::heartbeatTick(Async::Timer* /*t*/) } if (++m_ob_hb_rx_cnt >= TWIN_HB_RX_THRESHOLD) { - cerr << "*** TWIN: outbound RX timeout, disconnecting" << endl; + geulog::warn("twin", "TWIN: outbound RX timeout, disconnecting"); m_con.disconnect(); m_ob_hb_rx_cnt = 0; } @@ -560,7 +557,7 @@ void TwinLink::heartbeatTick(Async::Timer* /*t*/) } if (++m_ib_hb_rx_cnt >= TWIN_HB_RX_THRESHOLD) { - cerr << "*** TWIN: inbound RX timeout, disconnecting" << endl; + geulog::warn("twin", "TWIN: inbound RX timeout, disconnecting"); m_inbound_con->disconnect(); m_inbound_con = nullptr; m_ib_hb_rx_cnt = 0; @@ -600,8 +597,7 @@ void TwinLink::sendMsgOnOutbound(const ReflectorMsg& msg) ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { - cerr << "*** ERROR[TWIN]: Failed to pack message type=" << msg.type() - << endl; + geulog::error("twin", "TWIN: Failed to pack message type=", msg.type()); return; } m_ob_hb_tx_cnt = 0; @@ -616,8 +612,7 @@ void TwinLink::sendMsgOnInbound(const ReflectorMsg& msg) ReflectorMsg header(msg.type()); if (!header.pack(ss) || !msg.pack(ss)) { - cerr << "*** ERROR[TWIN]: Failed to pack message type=" << msg.type() - << endl; + geulog::error("twin", "TWIN: Failed to pack message type=", msg.type()); return; } m_ib_hb_tx_cnt = 0; diff --git a/src/svxlink/reflector/svxreflector.cpp b/src/svxlink/reflector/svxreflector.cpp index 1ae0631..bf1512a 100644 --- a/src/svxlink/reflector/svxreflector.cpp +++ b/src/svxlink/reflector/svxreflector.cpp @@ -67,6 +67,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include #include #include +#include /**************************************************************************** @@ -575,6 +576,12 @@ int main(int argc, const char *argv[]) cfg.getValue("GLOBAL", "TIMESTAMP_FORMAT", tstamp_format); logwriter.setTimestampFormat(tstamp_format); + if (!geulog::configure(cfg)) + { + cerr << "*** ERROR: logging facade configuration failed" << endl; + exit(1); + } + cout << PROGRAM_NAME " v" SVXREFLECTOR_VERSION " Copyright (C) 2003-2025 Tobias Blomberg / SM0SVX\n"; cout << "Modified with server-to-server trunk support by IW1GEU.\n\n"; @@ -623,6 +630,7 @@ int main(int argc, const char *argv[]) tcsetattr(STDIN_FILENO, TCSANOW, &org_termios); } + geulog::shutdown(); return 0; } /* main */ diff --git a/tests/run_tests.sh b/tests/run_tests.sh index dae8166..bd0ec99 100755 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -17,6 +17,9 @@ docker compose -f docker-compose.test.yml up -d --build --wait echo "=== Running integration tests ===" python3 test_trunk.py +echo "=== Logging tests ===" +python3 test_logging.py -v || exit 1 + echo "" echo "==================================" echo "Running TWIN protocol tests" diff --git a/tests/test_logging.py b/tests/test_logging.py new file mode 100644 index 0000000..dfb412b --- /dev/null +++ b/tests/test_logging.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Integration tests for GeuReflector logging facade (geulog::). + +Exercises the LOG PTY commands (SHOW, SET, RESET), level filtering, and +error rejection via the /dev/shm/reflector_ctrl PTY inside a running +reflector container. + +Requires: Python 3.7+, stdlib only. +Docker must be running with the default topology: + cd tests && python3 generate_configs.py + docker compose -f docker-compose.test.yml up -d --build --wait +""" + +import os +import subprocess +import sys +import time +import unittest + +# Ensure tests/ is on the path so topology can be imported +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import topology as T + +TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) +COMPOSE_FILE = "docker-compose.test.yml" + +# All seven subsystems defined by geulog:: (must stay in sync with Log.h) +EXPECTED_SUBSYSTEMS = ["trunk", "satellite", "twin", "client", "mqtt", "redis", "core"] + +# Primary reflector used for all logging tests (sorted first = "a") +PRIMARY = sorted(T.REFLECTORS)[0] + + +# --------------------------------------------------------------------------- +# Helpers (match the idiom in test_trunk.py exactly) +# --------------------------------------------------------------------------- + +def pty_send(reflector_name: str, command: str, timeout: float = 5.0) -> str: + """Write a line to /dev/shm/reflector_ctrl inside a reflector container.""" + svc = T.service_name(reflector_name) + proc = subprocess.run( + ["docker", "compose", "-f", COMPOSE_FILE, + "exec", "-T", svc, + "bash", "-c", f"printf '%s\\n' {repr(command)} > /dev/shm/reflector_ctrl"], + cwd=TESTS_DIR, + capture_output=True, text=True, timeout=timeout, + ) + if proc.returncode != 0: + raise RuntimeError( + f"pty_send to {svc} failed: rc={proc.returncode} " + f"stderr={proc.stderr.strip()}") + return proc.stdout + + +def pty_send_recv(reflector_name: str, command: str, + wait: float = 0.5, timeout: float = 8.0) -> str: + """Write a command to the PTY and capture the response written back. + + Starts a background reader on the PTY slave, sends the command, waits + for the reflector to process and write its response, then returns what + was captured. + """ + svc = T.service_name(reflector_name) + # Start a background cat reading from the PTY slave (response side), + # sleep briefly to let it start, then write the command, wait for the + # reflector to respond, kill the reader and return what was captured. + script = ( + f"timeout {wait} cat /dev/shm/reflector_ctrl > /tmp/pty_resp 2>&1 & " + f"BGPID=$!; " + f"sleep 0.05; " + f"printf '%s\\n' {repr(command)} > /dev/shm/reflector_ctrl; " + f"wait $BGPID; " + f"cat /tmp/pty_resp" + ) + proc = subprocess.run( + ["docker", "compose", "-f", COMPOSE_FILE, + "exec", "-T", svc, "bash", "-c", script], + cwd=TESTS_DIR, + capture_output=True, text=True, timeout=timeout, + ) + return proc.stdout + proc.stderr + + +def docker_logs_since(reflector_name: str, since: str = "5s") -> str: + """Return the stdout/stderr of a reflector container since N seconds ago.""" + svc = T.service_name(reflector_name) + proc = subprocess.run( + ["docker", "compose", "-f", COMPOSE_FILE, + "logs", "--no-color", "--since", since, svc], + cwd=TESTS_DIR, + capture_output=True, text=True, timeout=10.0, + ) + return proc.stdout + proc.stderr + + +# --------------------------------------------------------------------------- +# Test cases +# --------------------------------------------------------------------------- + +class TestLoggingFacade(unittest.TestCase): + + @classmethod + def setUpClass(cls): + """Ensure the primary reflector is reachable before running tests.""" + from urllib.request import urlopen + from urllib.error import URLError + + host = "127.0.0.1" + http_port = T.mapped_http_port(PRIMARY) + url = f"http://{host}:{http_port}/status" + deadline = time.time() + 30.0 + while True: + try: + with urlopen(url, timeout=2.0) as resp: + resp.read() + break + except (URLError, OSError): + if time.time() > deadline: + raise RuntimeError( + f"reflector-{PRIMARY} not reachable at {url}") + time.sleep(0.5) + + # Reset log levels to defaults before the suite runs so tests + # start from a known state regardless of prior runs. + pty_send(PRIMARY, "LOG RESET") + time.sleep(0.2) + + def tearDown(self): + """Restore default log levels after each test.""" + pty_send(PRIMARY, "LOG RESET") + time.sleep(0.1) + + # ------------------------------------------------------------------ + # Test 01: LOG SHOW returns a snapshot containing all subsystems + # ------------------------------------------------------------------ + def test_01_log_show_returns_snapshot(self): + """LOG SHOW returns a = snapshot for every subsystem.""" + out = pty_send_recv(PRIMARY, "LOG SHOW") + for sub in EXPECTED_SUBSYSTEMS: + self.assertIn( + f"{sub}=", out, + f"subsystem '{sub}' missing from LOG SHOW output: {out!r}") + + # ------------------------------------------------------------------ + # Test 02: Setting trunk=debug produces [debug] [trunk] lines + # ------------------------------------------------------------------ + def test_02_set_level_to_debug_produces_debug_lines(self): + """After LOG trunk=debug, heartbeat/peer messages appear at debug level.""" + # Set trunk to debug and record the timestamp + pty_send(PRIMARY, "LOG trunk=debug") + time.sleep(0.2) + t0 = time.time() + + # Wait up to 20 s for a [debug] [trunk] line to appear in docker logs. + # Trunk heartbeats fire every 10 s so we give it enough headroom. + deadline = t0 + 20.0 + found = False + while time.time() < deadline: + # Request fresh logs relative to when we set the level + elapsed = time.time() - t0 + since = f"{int(elapsed) + 2}s" + logs = docker_logs_since(PRIMARY, since=since) + if "[debug] [trunk]" in logs: + found = True + break + time.sleep(1.0) + + self.assertTrue( + found, + "No '[debug] [trunk]' line appeared within 20 s after LOG trunk=debug") + + # ------------------------------------------------------------------ + # Test 03: Setting trunk=error suppresses debug/info lines + # ------------------------------------------------------------------ + def test_03_set_level_to_error_suppresses_lower_levels(self): + """After LOG trunk=error, no [debug] or [info] [trunk] lines appear.""" + # Raise the level to error. + pty_send(PRIMARY, "LOG trunk=error") + + # Wait slightly beyond one full heartbeat cycle (10 s) so that if + # any debug/info lines were going to appear they would have done so. + time.sleep(13.0) + + # Only look at the last 12 s of logs — entirely within the + # error-level window (the level was set >13 s ago so there is at + # least 12 s of error-level coverage captured here). + logs = docker_logs_since(PRIMARY, since="12s") + + low_level_lines = [ + line for line in logs.splitlines() + if "[debug] [trunk]" in line or "[info] [trunk]" in line + ] + self.assertEqual( + low_level_lines, [], + f"Found unexpected low-level trunk lines after LOG trunk=error: " + f"{low_level_lines[:5]}") + + # ------------------------------------------------------------------ + # Test 04: LOG RESET restores the startup snapshot + # ------------------------------------------------------------------ + def test_04_reset_restores_startup_snapshot(self): + """After LOG =debug then LOG RESET, snapshot is back to default.""" + # Change a level + pty_send(PRIMARY, "LOG trunk=debug") + time.sleep(0.2) + + # Verify the change took effect via SHOW + after_change = pty_send_recv(PRIMARY, "LOG SHOW") + self.assertIn("trunk=debug", after_change, + f"Level did not change to debug: {after_change!r}") + + # Reset and read back + pty_send(PRIMARY, "LOG RESET") + time.sleep(0.2) + after_reset = pty_send_recv(PRIMARY, "LOG SHOW") + + # The startup config has no LOG= key so everything defaults to info + self.assertIn( + "trunk=info", after_reset, + f"After RESET, expected trunk=info in snapshot: {after_reset!r}") + + # ------------------------------------------------------------------ + # Test 05: Unknown subsystem is rejected with an error message + # ------------------------------------------------------------------ + def test_05_unknown_subsystem_rejected(self): + """LOG bogus=debug returns an error containing 'unknown subsystem or level'.""" + out = pty_send_recv(PRIMARY, "LOG bogus=debug") + self.assertIn( + "unknown subsystem or level", out, + f"Expected error message not found in PTY response: {out!r}") + + # ------------------------------------------------------------------ + # Test 06: Unknown level is rejected with an error message + # ------------------------------------------------------------------ + def test_06_unknown_level_rejected(self): + """LOG trunk=yelling returns an error containing 'unknown subsystem or level'.""" + out = pty_send_recv(PRIMARY, "LOG trunk=yelling") + self.assertIn( + "unknown subsystem or level", out, + f"Expected error message not found in PTY response: {out!r}") + + +if __name__ == "__main__": + unittest.main(verbosity=2)