tools: map verbosity as upstream and add the path-finding log level

This commit is contained in:
DeFiDude committed 2026-11-10 05:18:02 -07:00
1 parent 1897c8b666
commit a81eee4a72
15 files changed
+196 -123

No files matched your search

+3 -3
View File
@@ -753,7 +753,7 @@ fn spawn_backbone_server_on_listener(
match fast_flap_runtime.admit(peer.ip(), fast_flap_policy) {
FastFlapAdmission::Allowed(connection) => connection,
FastFlapAdmission::Rejected { flaps } => {
tracing::warn!(
tracing::debug!(target: "rns::pathing",
remote_ip = %peer.ip(),
flaps,
"backbone: rejecting fast-flapping connection",
@@ -764,7 +764,7 @@ fn spawn_backbone_server_on_listener(
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
let client_name = format!("{}/client_{}", config.name, client_id);
tracing::info!(
tracing::debug!(target: "rns::pathing",
name = %client_name,
peer = %peer,
"backbone: accepted connection",
@@ -801,7 +801,7 @@ fn spawn_backbone_server_on_listener(
)
.await;
fast_flap_connection.disconnected();
tracing::info!(name = %cname, "backbone client disconnected");
tracing::debug!(target: "rns::pathing", name = %cname, "backbone client disconnected");
// Proactive notify so broadcasts don't target dead tx.
let _ = dereg_tx
.send(TransportMessage::DeregisterInterface { id: client_id })
+1 -6
View File
@@ -211,12 +211,7 @@ pub(crate) async fn main() {
process::exit(2);
}
let level = match (args.verbose as i32) - (args.quiet as i32) {
n if n >= 2 => tracing::Level::DEBUG,
1 => tracing::Level::INFO,
0 => tracing::Level::WARN,
_ => tracing::Level::ERROR,
};
let level = rns_tools::Utility::Rncp.loglevel(None, args.verbose, args.quiet, false);
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
+1 -8
View File
@@ -285,14 +285,7 @@ async fn run(args: Args) -> ExitCode {
return ExitCode::SUCCESS;
}
let target_loglevel = 4 + args.verbose as i32 - args.quiet as i32;
let level = match target_loglevel {
i32::MIN..=1 => tracing::Level::ERROR,
2..=3 => tracing::Level::WARN,
4 => tracing::Level::INFO,
5 => tracing::Level::DEBUG,
_ => tracing::Level::TRACE,
};
let level = rns_tools::Utility::Rnid.loglevel(None, args.verbose, args.quiet, false);
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
+1 -5
View File
@@ -143,11 +143,7 @@ pub(crate) async fn main() -> ExitCode {
return ExitCode::SUCCESS;
}
let level = match args.verbose {
0 => tracing::Level::WARN,
1 => tracing::Level::INFO,
_ => tracing::Level::DEBUG,
};
let level = rns_tools::Utility::Rnpath.loglevel(None, args.verbose, 0, false);
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
+1 -5
View File
@@ -77,11 +77,7 @@ pub(crate) async fn main() {
return;
};
let level = match args.verbose {
0 => tracing::Level::WARN,
1 => tracing::Level::INFO,
_ => tracing::Level::DEBUG,
};
let level = rns_tools::Utility::Rnprobe.loglevel(None, args.verbose, 0, false);
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
+16 -27
View File
@@ -680,8 +680,7 @@ pub(crate) async fn main() {
return;
}
let verbosity = (!args.service).then(|| args.verbose as i32 - args.quiet as i32);
let level = tracing_level(effective_loglevel(&config_dir, verbosity));
let level = effective_loglevel(&config_dir, args.verbose, args.quiet, args.service);
let log_timestamps = rns_tools::config_log_timestamps(&config_dir);
if args.service {
@@ -911,34 +910,23 @@ fn parse_string_literal(value: &str) -> Option<String> {
}
/// Python `Reticulum.__apply_config`: the configured level plus the `-v`/`-q`
/// delta, clamped to 0..=8; without a `loglevel` key the level stays at 3.
/// A missing file is read as the default config the runtime writes first.
fn effective_loglevel(config_dir: &Path, verbosity: Option<i32>) -> i32 {
/// delta. A missing file is read as the default config the runtime writes first.
fn effective_loglevel(
config_dir: &Path,
verbose: u8,
quiet: u8,
service: bool,
) -> rns_tools::LogLevel {
let path = config_dir.join("config");
let config = if path.exists() {
rns_runtime::config::Config::from_file(&path).ok()
} else {
rns_runtime::config::Config::parse(rns_runtime::config::Config::default_config()).ok()
};
match config
let configured = config
.as_ref()
.and_then(|c| c.section("logging")?.get_int("loglevel"))
{
Some(level) => level
.saturating_add(verbosity.unwrap_or(0).into())
.clamp(0, 8) as i32,
None => 3,
}
}
fn tracing_level(verbosity: i32) -> tracing::Level {
match verbosity {
i32::MIN..=1 => tracing::Level::ERROR,
2 => tracing::Level::WARN,
3..=4 => tracing::Level::INFO,
5..=6 => tracing::Level::DEBUG,
7.. => tracing::Level::TRACE,
}
.and_then(|c| c.section("logging")?.get_int("loglevel"));
rns_tools::Utility::Rnsd.loglevel(configured, verbose, quiet, service)
}
fn rotate_log_if_needed(path: &Path) -> std::io::Result<()> {
@@ -1067,14 +1055,15 @@ mod tests {
#[test]
fn verbosity_is_added_to_configured_loglevel_and_clamped() {
use rns_tools::LogLevel;
let dir = std::env::temp_dir().join(format!("rnsd-loglevel-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("config"), "[logging]\nloglevel = 4\n").unwrap();
assert_eq!(effective_loglevel(&dir, Some(5)), 8);
assert_eq!(effective_loglevel(&dir, Some(-9)), 0);
assert_eq!(effective_loglevel(&dir, None), 4);
assert_eq!(effective_loglevel(&dir, 5, 0, false), LogLevel::Extreme);
assert_eq!(effective_loglevel(&dir, 0, 9, false), LogLevel::Critical);
assert_eq!(effective_loglevel(&dir, 3, 0, true), LogLevel::Info);
fs::write(dir.join("config"), "[reticulum]\n").unwrap();
assert_eq!(effective_loglevel(&dir, Some(4)), 3);
assert_eq!(effective_loglevel(&dir, 4, 0, false), LogLevel::Notice);
let _ = fs::remove_dir_all(&dir);
}
+1 -6
View File
@@ -286,12 +286,7 @@ async fn start_reticulum(
}
fn init_logging(verbose: u8, quiet: u8, config_dir: Option<&Path>) {
let level = match (verbose as i32) - (quiet as i32) {
n if n >= 2 => tracing::Level::DEBUG,
1 => tracing::Level::INFO,
0 => tracing::Level::WARN,
_ => tracing::Level::ERROR,
};
let level = rns_tools::Utility::Rnsh.loglevel(None, verbose, quiet, false);
let resolved = resolve_config_dir(config_dir.and_then(|path| path.to_str()));
rns_tools::init_tracing(
level,
+1 -7
View File
@@ -134,13 +134,7 @@ pub(crate) async fn main() -> ExitCode {
return ExitCode::from(2);
}
let verbosity = (args.verbose as i32) - (args.quiet as i32);
let level = match verbosity {
v if v <= -1 => tracing::Level::ERROR,
0 => tracing::Level::WARN,
1 => tracing::Level::INFO,
_ => tracing::Level::DEBUG,
};
let level = rns_tools::Utility::Rnstatus.loglevel(None, args.verbose, args.quiet, false);
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
rns_tools::init_tracing(
level,
+130 -7
View File
@@ -21,21 +21,144 @@ pub fn config_log_timestamps(config_dir: &std::path::Path) -> bool {
.unwrap_or(true)
}
/// Target of the events Python logs at `LOG_PATHING`.
pub const PATHING_TARGET: &str = "rns::pathing";
/// Python RNS log levels (`RNS/__init__.py` `LOG_CRITICAL`..`LOG_EXTREME`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum LogLevel {
Critical = 0,
Error = 1,
Warning = 2,
Notice = 3,
Info = 4,
Verbose = 5,
Debug = 6,
Pathing = 7,
Extreme = 8,
}
impl LogLevel {
const ALL: [LogLevel; 9] = [
LogLevel::Critical,
LogLevel::Error,
LogLevel::Warning,
LogLevel::Notice,
LogLevel::Info,
LogLevel::Verbose,
LogLevel::Debug,
LogLevel::Pathing,
LogLevel::Extreme,
];
/// The level for `level`, clamped to 0..=8 as `Reticulum.__init__` does.
pub fn clamped(level: i64) -> Self {
Self::ALL[level.clamp(0, 8) as usize]
}
pub fn number(self) -> i32 {
self as i32
}
/// Python `loglevelname()` without brackets and padding.
pub fn name(self) -> &'static str {
match self {
LogLevel::Critical => "Critical",
LogLevel::Error => "Error",
LogLevel::Warning => "Warning",
LogLevel::Notice => "Notice",
LogLevel::Info => "Info",
LogLevel::Verbose => "Verbose",
LogLevel::Debug => "Debug",
LogLevel::Pathing => "Pathing",
LogLevel::Extreme => "Extra",
}
}
/// Tracing filter for this level: `Pathing` adds the [`PATHING_TARGET`]
/// debug events to `Debug`, and only `Extreme` enables trace events.
pub fn filter(self) -> tracing_subscriber::filter::Targets {
use tracing_subscriber::filter::{LevelFilter, Targets};
let default = match self {
LogLevel::Critical | LogLevel::Error => LevelFilter::ERROR,
LogLevel::Warning => LevelFilter::WARN,
LogLevel::Notice | LogLevel::Info => LevelFilter::INFO,
LogLevel::Verbose | LogLevel::Debug | LogLevel::Pathing => LevelFilter::DEBUG,
LogLevel::Extreme => LevelFilter::TRACE,
};
let pathing = if self >= LogLevel::Pathing {
default
} else {
LevelFilter::OFF
};
Targets::new()
.with_default(default)
.with_target(PATHING_TARGET, pathing)
}
}
/// The utilities whose log level follows their upstream counterpart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Utility {
Rnsd,
Rnstatus,
Rnpath,
Rnprobe,
Rncp,
Rnid,
Rnsh,
Lxmd,
}
impl Utility {
/// The level the upstream utility runs at. `configured` is the
/// `[logging] loglevel` key, which only rnsd and lxmd (its own config)
/// read; the other utilities pass an explicit level to `RNS.Reticulum`.
/// rnsd ignores `-v`/`-q` in service mode and stays at Notice without a
/// `loglevel` key; lxmd starts at Notice without one and always applies
/// the flags.
pub fn loglevel(
self,
configured: Option<i64>,
verbose: u8,
quiet: u8,
service: bool,
) -> LogLevel {
let delta = i64::from(verbose) - i64::from(quiet);
let level = match self {
Utility::Rnsd => match configured {
Some(level) if service => level,
Some(level) => level.saturating_add(delta),
None => LogLevel::Notice as i64,
},
Utility::Lxmd => configured
.unwrap_or(LogLevel::Notice as i64)
.saturating_add(delta),
Utility::Rnprobe => 2 + delta,
Utility::Rnstatus | Utility::Rnpath | Utility::Rncp => 3 + delta,
Utility::Rnid | Utility::Rnsh => 4 + delta,
};
LogLevel::clamped(level)
}
}
/// Attempt to install the CLI's global tracing subscriber with the supplied
/// level, timestamp, ANSI and writer settings. A false `timestamps` omits the
/// time field. Initialization failure is ignored, so an existing global
/// subscriber is left in place.
pub fn init_tracing<W>(level: tracing::Level, timestamps: bool, ansi: bool, writer: W)
pub fn init_tracing<W>(level: LogLevel, timestamps: bool, ansi: bool, writer: W)
where
W: for<'a> tracing_subscriber::fmt::MakeWriter<'a> + Send + Sync + 'static,
{
let builder = tracing_subscriber::fmt()
.with_max_level(level)
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let layer = tracing_subscriber::fmt::layer()
.with_ansi(ansi)
.with_writer(writer);
if timestamps {
let _ = builder.try_init();
let registry = tracing_subscriber::registry().with(level.filter());
let _ = if timestamps {
registry.with(layer).try_init()
} else {
let _ = builder.without_time().try_init();
}
registry.with(layer.without_time()).try_init()
};
}
+4 -4
View File
@@ -734,7 +734,7 @@ impl TransportActor {
false
};
if interface_rate_blocked {
debug!(
pathing!(
dest = hex::encode(header.destination_hash),
interface = interface_id,
"announce blocked by per-interface rate limit"
@@ -765,7 +765,7 @@ impl TransportActor {
if header.hops > 0 && header.hops - 1 == existing_hops && existing_retries > 0 {
let existing_local_rebroadcasts = existing.local_rebroadcasts + 1;
if existing_local_rebroadcasts >= LOCAL_REBROADCASTS_MAX {
debug!(
trace!(
dest = hex::encode(header.destination_hash),
"announce dedup: local rebroadcast limit reached, removing from table"
);
@@ -779,7 +779,7 @@ impl TransportActor {
if let Some(ae) = self.announce_table.get(&header.destination_hash)
&& now < ae.retransmit_timeout
{
debug!(
trace!(
dest = hex::encode(header.destination_hash),
"announce dedup: passed on by another node, cancelling rebroadcast"
);
@@ -913,7 +913,7 @@ impl TransportActor {
);
}
debug!(
pathing!(
dest = hex::encode(header.destination_hash),
hops = header.hops,
next_hop = ?header.transport_id.map(hex::encode),
@@ -366,9 +366,10 @@ impl TransportActor {
self.path_table.expire(&destination_hash);
}
debug!(
pathing!(
dest = hex::encode(destination_hash),
blocked_interface, "unvalidated link expired -- queued re-discovery"
blocked_interface,
"unvalidated link expired -- queued re-discovery"
);
Some(PendingDiscoveryPathRequest {
@@ -575,7 +576,7 @@ impl TransportActor {
.and_then(|iface| iface.ingress.try_release_held());
if let Some(announce) = released {
debug!(
pathing!(
dest = hex::encode(announce.destination_hash),
interface = iface_id,
"releasing held announce"
@@ -666,7 +667,7 @@ impl TransportActor {
self.recent_announces.remove(hash);
}
self.state_dirty = true;
debug!(
pathing!(
removed = to_drop.len(),
remaining = self.recent_announces.len(),
before,
+2 -2
View File
@@ -2013,7 +2013,7 @@ impl TransportActor {
// Mode-independent gate: a non-local announce whose next-hop interface
// doesn't exist is never rebroadcast (Transport.py:1216-1218).
if !local && from_iface_mode.is_none() {
trace!(
pathing!(
dest = hex::encode(destination_hash),
interface = id,
"blocking announce broadcast: next hop interface doesn't exist"
@@ -2027,7 +2027,7 @@ impl TransportActor {
&& !entry.announces_from_internal
&& from_iface_mode == Some(Some(InterfaceMode::Internal))
{
trace!(
pathing!(
dest = hex::encode(destination_hash),
interface = id,
"blocking announce broadcast: internal-mode next hop interface"
+23 -37
View File
@@ -1,18 +1,6 @@
use super::*;
use crate::now_f64;
/// Python 1.3.8 Transport.PR_LOGLEVEL (Transport.py:220/306): path-request
/// chatter logs at DEBUG on transport nodes, EXTREME (trace) on leaf nodes.
macro_rules! pr_log {
($actor:expr, $($arg:tt)*) => {
if $actor.is_transport_enabled {
debug!($($arg)*);
} else {
trace!($($arg)*);
}
};
}
/// Path-request lengths (Transport.py:3975-3980).
pub(super) const PR_LEGACY_LENGTH: usize = 32;
pub(super) const PR_LENGTH: usize = 48;
@@ -614,8 +602,7 @@ impl TransportActor {
let mut requested_dest = [0u8; 16];
requested_dest.copy_from_slice(&data[..16]);
if data.len() == 16 {
pr_log!(
self,
pathing!(
dest = %hex::encode(requested_dest),
"ignoring tagless path request"
);
@@ -662,12 +649,15 @@ impl TransportActor {
)
});
if !stamp_ok {
trace!(
dest = %hex::encode(requested_dest),
stamped = ext.is_some(),
lenient = ext.as_ref().is_some_and(|ext| ext[1] == 0xFF),
"path request without a valid stamp"
);
if ext.is_some() {
pathing!(
dest = %hex::encode(requested_dest),
lenient = ext.as_ref().is_some_and(|ext| ext[1] == 0xFF),
"path request without a valid stamp"
);
} else {
trace!(dest = %hex::encode(requested_dest), "unstamped path request");
}
if self.stamp_policy.stamps_enforced {
return;
}
@@ -680,7 +670,7 @@ impl TransportActor {
}
if self.local_destinations.contains(&requested_dest) {
debug!(
pathing!(
dest = %hex::encode(requested_dest),
"answering path request — destination is local"
);
@@ -728,14 +718,14 @@ impl TransportActor {
&& path.interface_id == interface_id;
if requestor_is_next_hop {
debug!(
pathing!(
dest = %hex::encode(requested_dest),
"not answering path request — requester is our next hop"
);
return;
}
if same_roaming_interface {
debug!(
pathing!(
dest = %hex::encode(requested_dest),
"not answering path request on roaming interface learned from same interface"
);
@@ -754,8 +744,7 @@ impl TransportActor {
else {
return;
};
pr_log!(
self,
pathing!(
dest = %hex::encode(requested_dest),
hops,
"answering path request — path is known, queueing path response"
@@ -809,8 +798,7 @@ impl TransportActor {
.is_some_and(|iface| iface.recursive_prs || mode_discovers_unknown_paths(iface.mode));
if is_from_local_client {
pr_log!(
self,
pathing!(
dest = %hex::encode(requested_dest),
"forwarding path request from local shared client"
);
@@ -827,7 +815,7 @@ impl TransportActor {
.get_mut(&interface_id)
.is_some_and(|iface| iface.ingress.should_ingress_limit_pr());
if ingress_limited {
debug!(
pathing!(
dest = %hex::encode(requested_dest),
interface_id,
"not forwarding recursive path request — ingress PR burst active"
@@ -855,8 +843,7 @@ impl TransportActor {
);
}
} else if self.has_local_client_interfaces() {
pr_log!(
self,
pathing!(
dest = %hex::encode(requested_dest),
"forwarding path request to local shared clients"
);
@@ -871,8 +858,7 @@ impl TransportActor {
);
}
} else {
pr_log!(
self,
pathing!(
dest = %hex::encode(requested_dest),
interface_id,
"ignoring unknown path request on non-discovery interface"
@@ -1183,13 +1169,13 @@ impl TransportActor {
if tunnel_timebase >= current_timebase {
should_add = true;
} else {
debug!(
pathing!(
dest = hex::encode(dest_hash),
"did not restore tunnel path: existing path is more recent"
);
}
} else {
debug!(
pathing!(
dest = hex::encode(dest_hash),
"did not restore tunnel path: newer path with fewer hops exists"
);
@@ -1197,7 +1183,7 @@ impl TransportActor {
} else if now < tunnel_path.expires {
should_add = true;
} else {
debug!(
pathing!(
dest = hex::encode(dest_hash),
"did not restore tunnel path: expired"
);
@@ -1216,7 +1202,7 @@ impl TransportActor {
self.path_table.insert(*dest_hash, entry);
self.state_dirty = true;
self.fire_path_waiters(dest_hash);
debug!(
pathing!(
dest = hex::encode(dest_hash),
hops = tunnel_path.hops,
"restored tunnel path"
@@ -1230,7 +1216,7 @@ impl TransportActor {
if let Some(tunnel) = self.tunnel_table.get_mut(tunnel_id) {
for dest_hash in &deprecated_paths {
tunnel.tunnel_paths.remove(dest_hash);
debug!(
pathing!(
dest = hex::encode(dest_hash),
tunnel = hex::encode(&tunnel_id[..16]),
"removed deprecated path from tunnel"
@@ -522,11 +522,11 @@ impl ReceiverState {
match result {
CacheLookup::Valid(_) => {
let hits = ReceiverMetrics::increment(&self.metrics.valid_cache_hits);
trace!(hits, "discovery: valid announce cache hit");
pathing!(hits, "discovery: valid announce cache hit");
}
CacheLookup::Invalid => {
let hits = ReceiverMetrics::increment(&self.metrics.invalid_cache_hits);
trace!(hits, "discovery: invalid announce cache hit");
pathing!(hits, "discovery: invalid announce cache hit");
}
CacheLookup::Miss => {}
}
+5
View File
@@ -19,6 +19,11 @@ pub fn now_f64() -> f64 {
.as_secs_f64()
}
/// Events Python logs at `LOG_PATHING` (7): debug events on the `rns::pathing` target.
macro_rules! pathing {
($($arg:tt)*) => { tracing::debug!(target: "rns::pathing", $($arg)*) };
}
pub mod actor;
pub mod announce;
pub mod announce_validation;