Skip to content

Commit

Permalink
Make logging race-free using a global lock & macro (#309)
Browse files Browse the repository at this point in the history
* Make logging race-free using a global lock & macro

* Fix clippy complaint

* Fix import for MacOS

* Make `mt_log` expand to an expression
  • Loading branch information
cyqsimon authored Oct 20, 2023
1 parent 0c4987a commit 89e1140
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 11 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ simplelog = "0.12.1"
clap-verbosity-flag = "2.0.1"
derivative = "2.2.0"
itertools = "0.11.0"
once_cell = "1.18.0"

[target.'cfg(target_os="windows")'.dependencies]
netstat2 = "0.9.1"
Expand Down
14 changes: 8 additions & 6 deletions src/display/ui_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ use std::{
net::{IpAddr, Ipv4Addr, Ipv6Addr},
};

use log::warn;

use crate::network::{Connection, LocalSocket, Utilization};
use crate::{
mt_log,
network::{Connection, LocalSocket, Utilization},
};

static RECALL_LENGTH: usize = 5;
static MAX_BANDWIDTH_ITEMS: usize = 1000;
Expand Down Expand Up @@ -141,12 +142,13 @@ impl UIState {
},
) {
Some((lookalike, name)) => {
warn!(
mt_log!(
warn,
r#""{name}" owns a similar looking connection, but its local ip doesn't match."#
);
warn!("Looking for: {local_socket}; found: {lookalike}");
mt_log!(warn, "Looking for: {local_socket}; found: {lookalike}");
}
None => warn!("Cannot determine which process owns {local_socket}."),
None => mt_log!(warn, "Cannot determine which process owns {local_socket}."),
};
}
}
Expand Down
16 changes: 16 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use network::{
dns::{self, IpTable},
LocalSocket, Sniffer, Utilization,
};
use once_cell::sync::Lazy;
use pnet::datalink::{DataLinkReceiver, NetworkInterface};
use ratatui::backend::{Backend, CrosstermBackend};
use simplelog::WriteLogger;
Expand All @@ -36,6 +37,21 @@ use crate::cli::Opt;

const DISPLAY_DELTA: Duration = Duration::from_millis(1000);

/// Lock guard to prevent races during logging.
static LOG_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

/// Thread-safe log macro with a global Mutex guard.
#[macro_export]
macro_rules! mt_log {
($log_macro: ident, $($fmt_args:expr),*) => {{
let guard = $crate::LOG_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
log::$log_macro!($($fmt_args,)*);
drop(guard);
}};
}

fn main() -> anyhow::Result<()> {
let opts = Opt::parse();

Expand Down
21 changes: 16 additions & 5 deletions src/os/lsof_utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use std::{ffi::OsStr, net::IpAddr, process::Command, sync::OnceLock};

use log::warn;
use regex::Regex;

use crate::network::{LocalSocket, Protocol};
use crate::{
mt_log,
network::{LocalSocket, Protocol},
};

#[allow(dead_code)]
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -120,15 +122,24 @@ impl RawConnection {
let process = &self.process_name;

let Some(ip) = self.get_local_ip() else {
warn!(r#"Failed to get the local IP of a connection belonging to "{process}"."#);
mt_log!(
warn,
r#"Failed to get the local IP of a connection belonging to "{process}"."#
);
return None;
};
let Some(port) = self.get_local_port() else {
warn!(r#"Failed to get the local port of a connection belonging to "{process}"."#);
mt_log!(
warn,
r#"Failed to get the local port of a connection belonging to "{process}"."#
);
return None;
};
let Some(protocol) = self.get_protocol() else {
warn!(r#"Failed to get the protocol of a connection belonging to "{process}"."#);
mt_log!(
warn,
r#"Failed to get the protocol of a connection belonging to "{process}"."#
);
return None;
};

Expand Down

0 comments on commit 89e1140

Please sign in to comment.