Skip to content

Commit

Permalink
style: align console messages outside of tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
crazyscot committed Jan 8, 2025
1 parent 16ef7ed commit e9e651a
Show file tree
Hide file tree
Showing 12 changed files with 134 additions and 79 deletions.
113 changes: 65 additions & 48 deletions src/cli/cli_main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
util::setup_tracing,
};

use anstream::{eprintln, println};
use anstream::println;
use indicatif::{MultiProgress, ProgressDrawTarget};
use tracing::error_span;

Expand All @@ -27,6 +27,35 @@ fn trace_level(args: &ClientParameters) -> &str {
}
}

enum MainMode {
Server,
Client(MultiProgress),
ShowConfig,
}

impl From<&CliArgs> for MainMode {
fn from(args: &CliArgs) -> Self {
if args.server {
MainMode::Server
} else if args.show_config {
MainMode::ShowConfig
} else {
MainMode::Client(MultiProgress::with_draw_target(
ProgressDrawTarget::stderr_with_hz(MAX_UPDATE_FPS),
))
}
}
}

impl MainMode {
fn progress(&self) -> Option<&MultiProgress> {
match self {
MainMode::Client(mp) => Some(mp),
_ => None,
}
}
}

/// Main CLI entrypoint
///
/// Call this from `main`. It reads argv.
Expand All @@ -43,64 +72,52 @@ pub async fn cli() -> anyhow::Result<ExitCode> {
);
return Ok(ExitCode::SUCCESS);
}

let progress = (!args.server).then(|| {
MultiProgress::with_draw_target(ProgressDrawTarget::stderr_with_hz(MAX_UPDATE_FPS))
});

if args.config_files {
// do this before attempting to read config, in case it fails
setup_tracing(
trace_level(&args.client_params),
None,
&None,
args.config.time_format.unwrap_or_default(),
)?;
println!("{:?}", Manager::config_files());
return Ok(ExitCode::SUCCESS);
}

// Now fold the arguments in with the CLI config (which may fail)
let config_manager = match Manager::try_from(&args) {
Ok(m) => m,
Err(err) => {
eprintln!("ERROR: {err}");
return Ok(ExitCode::FAILURE);
}
};
let main_mode = MainMode::from(&args); // side-effect: holds progress bar, if we need one

let config = match config_manager.get::<Configuration>() {
Ok(c) => c,
Err(err) => {
eprintln!("ERROR: Failed to parse configuration");
err.into_iter().for_each(|e| eprintln!("{e}"));
return Ok(ExitCode::FAILURE);
}
}
.validate()?;
// Now fold the arguments in with the CLI config (which may fail)
// (to provoke an error here: `qcp host: host2:`)
let config_manager = Manager::try_from(&args)?;
let config = config_manager.get::<Configuration>()?.validate()?;

setup_tracing(
trace_level(&args.client_params),
progress.as_ref(),
main_mode.progress(),
&args.client_params.log_file,
config.time_format,
)
.inspect_err(|e| eprintln!("{e:?}"))?;
)?; // to provoke error: set RUST_LOG=.

if args.show_config {
println!("{}", config_manager.to_display_adapter::<Configuration>());
Ok(ExitCode::SUCCESS)
} else if args.server {
let _span = error_span!("REMOTE").entered();
server_main(&config)
.await
.map(|()| ExitCode::SUCCESS)
.inspect_err(|e| tracing::error!("{e}"))
} else {
client_main(&config, progress.unwrap(), args.client_params)
.await
.inspect_err(|e| tracing::error!("{e}"))
.or_else(|_| Ok(false))
.map(|success| {
if success {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
})
}
match main_mode {
MainMode::ShowConfig => {
println!("{}", config_manager.to_display_adapter::<Configuration>());
return Ok(ExitCode::SUCCESS);
}
MainMode::Server => {
let _span = error_span!("REMOTE").entered();
server_main(&config).await?;
return Ok(ExitCode::SUCCESS);
}
MainMode::Client(progress) => {
return client_main(&config, progress, args.client_params)
.await
.map(|success| {
if success {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
});
}
};
}
2 changes: 1 addition & 1 deletion src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
// (c) 2024 Ross Younger
mod args;
mod cli_main;
pub(crate) mod styles;
pub mod styles;
pub(crate) use args::MODE_OPTIONS;
pub use cli_main::cli;
27 changes: 19 additions & 8 deletions src/cli/styles.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,39 @@
// (c) 2024 Ross Younger
//! CLI output styling
//!
//! Users of this module probably ought to use anstream's `println!` / `eprintln!` macros,
//! Users of this module probably ought to use anstream's `println!` / `eprintln!` macros.
//!
//! This module provides styles for use with those macros, and also a `RESET` constant to reset
//! styling to the default.
#[allow(clippy::enum_glob_use)]
use anstyle::AnsiColor::*;
use anstyle::Color::Ansi;
use clap::builder::styling::Styles;

pub(crate) const ERROR: anstyle::Style = anstyle::Style::new().bold().fg_color(Some(Ansi(Red)));
pub(crate) const WARNING: anstyle::Style =
anstyle::Style::new().bold().fg_color(Some(Ansi(Yellow)));
pub(crate) const INFO: anstyle::Style = anstyle::Style::new().fg_color(Some(Ansi(Cyan)));
/// Error message styling. This can be Displayed directly.
pub const ERROR: anstyle::Style = anstyle::Style::new().bold().fg_color(Some(Ansi(Red)));
/// Warning message styling. This can be Displayed directly.
pub const WARNING: anstyle::Style = anstyle::Style::new().bold().fg_color(Some(Ansi(Yellow)));
/// Informational message styling. This can be Displayed directly.
pub const INFO: anstyle::Style = anstyle::Style::new().fg_color(Some(Ansi(Cyan)));
// pub(crate) const DEBUG: anstyle::Style = anstyle::Style::new().fg_color(Some(Ansi(Blue)));

pub(crate) const CALL_OUT: anstyle::Style = anstyle::Style::new()
pub(crate) const HEADER: anstyle::Style = anstyle::Style::new()
.underline()
.fg_color(Some(Ansi(Yellow)));

pub(crate) const CLAP_STYLES: Styles = Styles::styled()
.usage(CALL_OUT)
.header(CALL_OUT)
.usage(HEADER)
.header(HEADER)
.literal(anstyle::Style::new().bold())
.invalid(WARNING)
.error(ERROR)
.valid(INFO.bold().underline())
.placeholder(INFO);

/// Resets styling to default.
///
/// This is purely for convenience; you can also call `ERROR::render_reset()` (etc.)
///
pub use anstyle::Reset as RESET;
4 changes: 2 additions & 2 deletions src/client/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ impl Channel {
.ok_or(anyhow!("could not access process stdin (can't happen?)"))?;
ClientMessage::write(&mut pipe, &credentials.certificate, connection_type)
.await
.with_context(|| "writing client message")?;
.with_context(|| "failed to write client message")?;

let mut server_output = new1
.process
Expand All @@ -65,7 +65,7 @@ impl Channel {
trace!("waiting for server message");
let message = ServerMessage::read(&mut server_output)
.await
.with_context(|| "reading server message")?;
.with_context(|| "failed to read server message")?;

trace!("Got server message {message:?}");
if let Some(w) = message.warning.as_ref() {
Expand Down
6 changes: 5 additions & 1 deletion src/config/ssh/values.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Individual configured values
// (c) 2024 Ross Younger

use crate::cli::styles::{INFO, RESET};
use figment::{Metadata, Profile, Source};

#[derive(Debug, Clone, PartialEq)]
Expand Down Expand Up @@ -51,7 +52,10 @@ impl figment::Provider for ValueProvider<'_> {
)
.interpolater(|profile, path| {
let key = path.to_vec();
format!("key `{key}` of host `{profile}`", key = key.join("."))
format!(
"key `{INFO}{key}{RESET}` of host `{INFO}{profile}{RESET}`",
key = key.join(".")
)
})
}

Expand Down
13 changes: 7 additions & 6 deletions src/config/structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use serde::{Deserialize, Serialize};
use struct_field_names_as_array::FieldNamesAsSlice;

use crate::{
cli::styles::{INFO, RESET},
transport::CongestionControllerType,
util::{derive_deftly_template_Optionalify, AddressFamily, PortRange, TimeFormat},
};
Expand Down Expand Up @@ -294,29 +295,29 @@ impl Configuration {
pub fn validate(self) -> Result<Self> {
if self.rx() < MINIMUM_BANDWIDTH {
anyhow::bail!(
"The receive bandwidth (rx {}B) is too small; it must be at least {}",
"The receive bandwidth ({INFO}rx {}{RESET}B) is too small; it must be at least {}",
self.rx.with_precision(0),
MINIMUM_BANDWIDTH.to_eng(3)
);
}
if self.tx() < MINIMUM_BANDWIDTH {
anyhow::bail!(
"The transmit bandwidth (rx {}B) is too small; it must be at least {}",
"The transmit bandwidth ({INFO}rx {}{RESET}B) is too small; it must be at least {}",
self.tx.with_precision(0),
MINIMUM_BANDWIDTH.to_eng(3)
);
}
if self.rx().checked_mul(self.rtt.into()).is_none() {
anyhow::bail!(
"The receive bandwidth delay product calculation (rx {}B x rtt {}ms) overflowed",
self.rx,
"The receive bandwidth delay product calculation ({INFO}rx {}{RESET}B x {INFO}rtt {}{RESET}ms) overflowed",
self.rx.with_precision(0),
self.rtt
);
}
if self.tx().checked_mul(self.rtt.into()).is_none() {
anyhow::bail!(
"The transmit bandwidth delay product calculation (rx {}B x rtt {}ms) overflowed",
self.tx,
"The transmit bandwidth delay product calculation ({INFO}rx {}{RESET}B x {INFO}rtt {}{RESET}ms) overflowed",
self.tx.with_precision(0),
self.rtt
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
#![doc = document_features::document_features!()]

mod cli;
pub use cli::cli; // needs to be re-exported for the binary crate
pub use cli::{cli, styles}; // needs to be re-exported for the binary crate

pub mod client;
pub mod config;
Expand Down
16 changes: 14 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
//! qcp utility - main entrypoint
// (c) 2024 Ross Younger

use qcp::styles::{ERROR, RESET};

#[cfg(all(target_env = "musl", target_pointer_width = "64"))]
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;

fn main() -> anyhow::Result<std::process::ExitCode> {
qcp::cli()
fn main() -> std::process::ExitCode {
match qcp::cli() {
Ok(code) => code,
Err(e) => {
if qcp::util::tracing_is_initialised() {
tracing::error!("{e}");
} else {
eprintln!("{ERROR}Error:{RESET} {e}");
}
std::process::ExitCode::FAILURE
}
}
}
15 changes: 8 additions & 7 deletions src/os/unix.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! OS concretions for Unix platforms
// (c) 2024 Ross Younger

use crate::cli::styles::{HEADER, INFO, RESET};
use crate::config::BASE_CONFIG_FILENAME;

use super::SocketOptions;
Expand Down Expand Up @@ -70,21 +71,21 @@ but doing so requires elevated privileges."#
println!(
r#"
To set the kernel limits immediately, run the following command as root:
sysctl -w kern.ipc.maxsockbuf={size}
To have this setting apply at boot, add this line to /etc/sysctl.conf:
kern.ipc.maxsockbuf={size}
{INFO}sysctl -w kern.ipc.maxsockbuf={size}{RESET}
To have this setting apply at boot, add this line to {HEADER}/etc/sysctl.conf{RESET}:
{INFO}kern.ipc.maxsockbuf={size}{RESET}
"#
);
} else {
println!(
r#"
To set the kernel limits immediately, run the following command as root:
sysctl -w net.core.rmem_max={rmem} -w net.core.wmem_max={wmem}
{INFO}sysctl -w net.core.rmem_max={rmem} -w net.core.wmem_max={wmem}{RESET}
To have this setting apply at boot, on most Linux distributions you
can create a file /etc/sysctl.d/20-qcp.conf containing:
net.core.rmem_max={rmem}
net.core.wmem_max={wmem}
can create a file {HEADER}/etc/sysctl.d/20-qcp.conf{RESET} containing:
{INFO}net.core.rmem_max={rmem}
net.core.wmem_max={wmem}{RESET}
"#
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ pub async fn server_main(config: &Configuration) -> anyhow::Result<()> {
trace!("connection completed");
});
} else {
info!("Endpoint was expectedly closed");
info!("Endpoint was unexpectedly closed");
}

// Graceful closedown. Wait for all connections and streams to finish.
Expand Down
2 changes: 1 addition & 1 deletion src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub mod stats;
pub mod time;

mod tracing;
pub use tracing::{setup as setup_tracing, TimeFormat};
pub use tracing::{is_initialized as tracing_is_initialised, setup as setup_tracing, TimeFormat};

mod port_range;
pub use port_range::PortRange;
Expand Down
Loading

0 comments on commit e9e651a

Please sign in to comment.