use std::{
error::Error,
fmt,
io::{self, Write},
path::PathBuf,
process::ExitCode,
};
use serde::Serialize;
use troll_core::{ConfigError, OperationError, ProbeError, Refused, StoreError, UpdateError};
#[derive(Debug)]
pub enum CliError {
Usage(clap::Error),
MissingConfigHome,
MissingStateHome,
MissingDataHome,
ReadConfig(PathBuf, io::Error),
Config(PathBuf, ConfigError),
RegistryHome(PathBuf, io::Error),
Store(StoreError),
Operation(OperationError),
Probe(ProbeError),
EphemeralRange(ProbeError),
WithSetup(&'static str, io::Error),
Serve(&'static str, io::Error),
InitRequiresTerminal,
InvalidInit(String),
InitConfigChanged(PathBuf),
InitZoneConflictsChanged,
ServicePortListening(u16),
OtherRegistryServicePort(u16),
ServiceIdentityUnknown {
port: u16,
pid: u32,
},
NoServicePort(u16),
SetupIo(&'static str, PathBuf, io::Error),
UnitExists(PathBuf),
InvalidExecutablePath(PathBuf),
PluginExists(PathBuf, &'static str),
#[allow(dead_code)] Unsupported(&'static str),
Json(serde_json::Error),
Output(io::Error),
Timestamp(time::error::Format),
}
impl fmt::Display for CliError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Usage(error) => error.fmt(f),
Self::MissingConfigHome => f.write_str(
"set XDG_CONFIG_HOME or HOME to an absolute path to locate troll's configuration",
),
Self::MissingDataHome => f.write_str(
"set XDG_DATA_HOME or HOME to an absolute path to locate troll's data directory",
),
Self::MissingStateHome => f.write_str(
"set XDG_STATE_HOME or HOME to an absolute path to locate troll's state directory",
),
Self::ReadConfig(path, error) => write!(
f,
"could not read configuration '{}': {error}",
path.display()
),
Self::Config(path, error) => {
write!(f, "invalid configuration '{}': {error}", path.display())
}
Self::RegistryHome(path, error) => write!(
f,
"could not create registry home '{}': {error}",
path.display()
),
Self::Store(error) => {
write!(f, "{error}")?;
if let Some(source) = error.source() {
write!(f, ": {source}")?;
}
Ok(())
}
Self::Operation(error) => error.fmt(f),
Self::Probe(error) => error.fmt(f),
Self::EphemeralRange(error) => {
write!(
f,
"could not determine the Linux ephemeral port range: {error}"
)
}
Self::WithSetup(operation, error) | Self::Serve(operation, error) => {
write!(f, "could not {operation}: {error}")
}
Self::InitRequiresTerminal => {
f.write_str("`troll init` requires a terminal; use `troll init --yes` for defaults")
}
Self::InvalidInit(message) => f.write_str(message),
Self::InitConfigChanged(path) => write!(
f,
"configuration {:?} changed during init; review it and rerun `troll init`",
path
),
Self::InitZoneConflictsChanged => f.write_str(
"well-known zone conflicts changed during init; rerun `troll init` to review them",
),
Self::ServicePortListening(port) => write!(f, "port {port} is already listening"),
Self::OtherRegistryServicePort(port) => write!(
f,
"a troll service for another registry is running on this port ({port})"
),
Self::ServiceIdentityUnknown { port, pid } => write!(
f,
"a troll service started by an earlier version is running on port {port} (pid {pid}); in a terminal, stop that process (with `systemctl --user stop troll.service` if it runs as the installed unit), run `troll init` and enter port {port} at the service port prompt to keep it, then start the dashboard again with the upgraded troll; without a terminal, leave the process running and report this to the user"
),
Self::NoServicePort(first) => write!(
f,
"no free service port from {first} through {} outside the lease and ephemeral ranges",
u16::MAX
),
Self::SetupIo(operation, path, error) => {
write!(f, "could not {operation} {path:?}: {error}")
}
Self::UnitExists(path) => write!(
f,
"systemd user unit {path:?} already exists with different content; use `troll setup service --force` to replace it"
),
Self::InvalidExecutablePath(path) => write!(
f,
"systemd cannot load the executable path {path:?}. Please install troll under a plain path (absolute UTF-8 without quotes, backslashes, control characters or the glob characters '*', '?' and '[')."
),
Self::PluginExists(path, host) => write!(
f,
"plugin file {path:?} already exists with different content; use `troll setup {host} --force` to replace it"
),
Self::Unsupported(message) => f.write_str(message),
Self::Json(error) => write!(f, "could not encode JSON output: {error}"),
Self::Output(error) => write!(f, "could not write output: {error}"),
Self::Timestamp(error) => write!(f, "could not format timestamp: {error}"),
}
}
}
impl From<StoreError> for CliError {
fn from(error: StoreError) -> Self {
Self::Store(error)
}
}
impl From<UpdateError<OperationError>> for CliError {
fn from(error: UpdateError<OperationError>) -> Self {
match error {
UpdateError::Store(error) => Self::Store(error),
UpdateError::Operation(error) => Self::Operation(error),
}
}
}
impl From<OperationError> for CliError {
fn from(error: OperationError) -> Self {
Self::Operation(error)
}
}
impl From<Refused> for CliError {
fn from(reason: Refused) -> Self {
OperationError::from(reason).into()
}
}
impl From<ProbeError> for CliError {
fn from(error: ProbeError) -> Self {
Self::Probe(error)
}
}
impl From<io::Error> for CliError {
fn from(error: io::Error) -> Self {
Self::Output(error)
}
}
impl From<time::error::Format> for CliError {
fn from(error: time::error::Format) -> Self {
Self::Timestamp(error)
}
}
#[derive(Serialize)]
pub(crate) struct ErrorOutput<'a> {
schema: u32,
error: ErrorBody<'a>,
}
impl<'a> ErrorOutput<'a> {
pub(crate) fn new(kind: &'static str, message: &'a str, exit_code: u8) -> Self {
Self {
schema: crate::output::SCHEMA,
error: ErrorBody {
kind,
message,
exit_code,
},
}
}
}
#[derive(Serialize)]
struct ErrorBody<'a> {
kind: &'static str,
message: &'a str,
exit_code: u8,
}
impl CliError {
pub(crate) fn invalid_request(message: impl Into<String>) -> Self {
OperationError::InvalidRequest(message.into()).into()
}
pub(crate) fn kind_and_code(&self) -> (&'static str, u8) {
match self {
Self::Usage(error) => (
"Usage",
u8::try_from(error.exit_code()).expect("clap exit code"),
),
Self::MissingConfigHome => ("MissingConfigHome", 1),
Self::MissingDataHome => ("MissingDataHome", 1),
Self::MissingStateHome => ("MissingStateHome", 1),
Self::ReadConfig(..) => ("ConfigIo", 1),
Self::Config(..) => ("InvalidConfig", 1),
Self::RegistryHome(..) => ("RegistryHomeIo", 1),
Self::Store(error) => match error {
StoreError::Io { .. } => ("RegistryIo", 1),
StoreError::Parse { .. } => ("RegistryParse", 1),
StoreError::Invalid { .. } => ("InvalidRegistry", 1),
StoreError::InvalidChange { .. } => ("InvalidRequest", 2),
StoreError::Locked { .. } => ("Locked", 4),
StoreError::NewerSchema { .. } => ("NewerSchema", 1),
StoreError::Serialize { .. } => ("RegistrySerialize", 1),
StoreError::RegistryMissingBackupPresent { .. } => {
("RegistryMissingBackupPresent", 1)
}
StoreError::ChangedDuringUpdate { .. } => ("ChangedDuringUpdate", 1),
StoreError::CommittedNotDurable { .. } => ("CommittedNotDurable", 1),
},
Self::Operation(error) => match error {
OperationError::Refused(reason) => {
let kind = match reason {
Refused::PortTaken { .. } => "PortTaken",
Refused::RangeExhausted { .. } => "RangeExhausted",
Refused::NotHolder { .. } => "NotHolder",
Refused::SharedService { .. } => "SharedService",
Refused::ServiceHasDependents { .. } => "ServiceHasDependents",
Refused::NotFound { .. } => "NotFound",
Refused::Changed { .. } => "Changed",
Refused::Stale { .. }
| Refused::StaleZone { .. }
| Refused::StaleApp { .. }
| Refused::StaleGroup { .. } => "Stale",
Refused::DurationTooLong { .. } => "DurationTooLong",
Refused::Ambiguous { .. } => "Ambiguous",
Refused::AllocationExhausted { .. } => "AllocationExhausted",
Refused::InZone { .. } => "InZone",
Refused::ZoneExists { .. } => "ZoneExists",
Refused::ZoneNotFound { .. } => "ZoneNotFound",
Refused::AppAlreadyExists { .. } => "AppAlreadyExists",
Refused::AppNotFound { .. } => "AppNotFound",
Refused::ComponentNotFound { .. } => "ComponentNotFound",
Refused::ConfirmationMismatch { .. } => "ConfirmationMismatch",
Refused::AppHasDependents { .. } => "AppHasDependents",
Refused::GroupNotFound { .. } => "GroupNotFound",
Refused::HistoryNotFound { .. } => "HistoryNotFound",
Refused::PoolNotFound { .. } => "PoolNotFound",
Refused::OsExcluded { .. } => "OsExcluded",
};
(kind, 3)
}
OperationError::Probe(_) => ("Probe", 1),
OperationError::InvalidRequest(_) => ("InvalidRequest", 2),
OperationError::InvalidPolicy(_) => ("InvalidPolicy", 1),
OperationError::NonPositiveDuration => ("NonPositiveDuration", 1),
OperationError::TimestampOutOfRange => ("TimestampOutOfRange", 1),
},
Self::Probe(_) => ("Probe", 1),
Self::EphemeralRange(_) => ("EphemeralRange", 1),
Self::WithSetup(..) => ("WithSetup", 1),
Self::Serve(..) => ("Serve", 1),
Self::InitRequiresTerminal => ("Usage", 2),
Self::InvalidInit(..) => ("InvalidRequest", 2),
Self::InitConfigChanged(..) => ("ConfigChanged", 3),
Self::InitZoneConflictsChanged => ("ZoneConflictsChanged", 3),
Self::ServicePortListening(..) | Self::OtherRegistryServicePort(..) => ("PortTaken", 3),
Self::ServiceIdentityUnknown { .. } => ("ServiceIdentityUnknown", 3),
Self::NoServicePort(..) => ("NoServicePort", 3),
Self::SetupIo(..) => ("SetupIo", 1),
Self::UnitExists(..) => ("UnitExists", 3),
Self::InvalidExecutablePath(..) => ("InvalidExecutablePath", 3),
Self::PluginExists(..) => ("PluginExists", 3),
Self::Unsupported(..) => ("Unsupported", 1),
Self::Json(_) => ("Json", 1),
Self::Output(_) => ("Output", 1),
Self::Timestamp(_) => ("Timestamp", 1),
}
}
pub fn report(self, json: bool) -> ExitCode {
let (kind, exit_code) = self.kind_and_code();
let message = self.to_string();
let message = message.trim_end();
let _ = writeln!(io::stderr().lock(), "{message}");
if json {
let output = ErrorOutput::new(kind, message, exit_code);
let mut stdout = io::stdout().lock();
if serde_json::to_writer(&mut stdout, &output).is_ok() {
let _ = writeln!(stdout);
}
}
ExitCode::from(exit_code)
}
pub fn report_for_with(self, json: bool) -> ExitCode {
if !json {
return self.report(false);
}
let (kind, exit_code) = self.kind_and_code();
let message = self.to_string();
let output = ErrorOutput::new(kind, message.trim_end(), exit_code);
crate::output::stderr_json(&output);
ExitCode::from(exit_code)
}
}
#[cfg(test)]
mod tests {
use std::{fs, time::Duration};
use clap::error::ErrorKind;
use time::{Date, Month, SignedDuration, format_description::well_known::Rfc3339};
use troll_core::{Config, DEFAULT_BIND, Lease, PolicyError};
use crate::test_support::TempDir;
use super::*;
fn assert_mapping(error: impl Into<CliError>, expected: (&str, u8)) {
assert_eq!(error.into().kind_and_code(), expected);
}
#[test]
fn maps_every_refusal_to_exit_three() {
let port = 8123;
let refusals = [
(
Refused::PortTaken {
port,
by: "project".into(),
},
"PortTaken",
),
(
Refused::RangeExhausted {
range: 20000..=24999,
},
"RangeExhausted",
),
(
Refused::NotHolder {
port,
holder: "another-user".into(),
},
"NotHolder",
),
(
Refused::SharedService {
port,
used_by: vec!["app".into()],
},
"SharedService",
),
(Refused::NotFound { port }, "NotFound"),
(Refused::Changed { port }, "Changed"),
(
Refused::DurationTooLong {
max: SignedDuration::hours(1),
},
"DurationTooLong",
),
(Refused::Ambiguous { port }, "Ambiguous"),
(
Refused::ServiceHasDependents { port },
"ServiceHasDependents",
),
(Refused::Stale { port }, "Stale"),
(
Refused::StaleZone {
label: "zone".into(),
},
"Stale",
),
(Refused::StaleApp { app: "app".into() }, "Stale"),
(
Refused::AllocationExhausted {
range: 10000..=10001,
wanted: 3,
},
"AllocationExhausted",
),
(
Refused::InZone {
port,
label: "zone".into(),
},
"InZone",
),
(
Refused::ZoneExists {
label: "zone".into(),
},
"ZoneExists",
),
(
Refused::ZoneNotFound {
label: "zone".into(),
},
"ZoneNotFound",
),
(
Refused::AppAlreadyExists { app: "app".into() },
"AppAlreadyExists",
),
(Refused::AppNotFound { app: "app".into() }, "AppNotFound"),
(
Refused::ComponentNotFound {
app: "app".into(),
component: "api".into(),
},
"ComponentNotFound",
),
(
Refused::ConfirmationMismatch { app: "app".into() },
"ConfirmationMismatch",
),
(
Refused::AppHasDependents {
app: "app".into(),
port,
used_by: vec!["other".into()],
},
"AppHasDependents",
),
(
Refused::GroupNotFound {
group: "g-example".into(),
},
"GroupNotFound",
),
];
for (refusal, name) in refusals {
assert_mapping(
UpdateError::Operation(OperationError::Refused(refusal)),
(name, 3),
);
}
}
#[test]
fn maps_operational_failures_to_exit_one() {
for (error, name) in [
(
OperationError::InvalidPolicy(PolicyError::ZeroPort),
"InvalidPolicy",
),
(OperationError::NonPositiveDuration, "NonPositiveDuration"),
(OperationError::TimestampOutOfRange, "TimestampOutOfRange"),
(OperationError::Probe("test".into()), "Probe"),
] {
assert_mapping(UpdateError::Operation(error), (name, 1));
}
}
#[test]
fn maps_invalid_request_to_exit_two() {
assert_mapping(
UpdateError::Operation(OperationError::InvalidRequest("test".into())),
("InvalidRequest", 2),
);
}
#[test]
fn maps_every_store_error_and_reserves_exit_four_for_the_lock() {
let dir = TempDir::new();
let path = dir.path().join("registry.toml");
let store = crate::platform::open_store(dir.path());
fs::write(&path, "schema =").unwrap();
assert_mapping(store.load().unwrap_err(), ("RegistryParse", 1));
fs::write(&path, "schema = 0").unwrap();
assert_mapping(store.load().unwrap_err(), ("InvalidRegistry", 1));
fs::write(&path, "schema = 1").unwrap();
let date = Date::from_calendar_date(-1, Month::January, 1).unwrap();
let leased_at = date.midnight().assume_utc();
let error = store
.update::<_, OperationError>(|registry| {
registry.lease.push(Lease {
port: 20000,
protocol: troll_core::Protocol::Tcp,
bind: DEFAULT_BIND,
project: "test".into(),
purpose: "test".into(),
holder: "test".into(),
holder_pid: None,
leased_at,
expires_at: leased_at + SignedDuration::hours(1),
component: None,
group: None,
});
Ok(())
})
.unwrap_err();
assert_mapping(error, ("RegistrySerialize", 1));
let other_errors = [
(
StoreError::Io {
path: path.clone(),
operation: "read",
source: io::Error::other("test"),
},
("RegistryIo", 1),
),
(
StoreError::Locked {
path: dir.path().join("registry.lock"),
timeout: Duration::ZERO,
},
("Locked", 4),
),
(
StoreError::NewerSchema {
path: path.clone(),
found: 2,
},
("NewerSchema", 1),
),
(
StoreError::RegistryMissingBackupPresent {
registry: path.clone(),
backup: path.with_extension("bak"),
},
("RegistryMissingBackupPresent", 1),
),
(
StoreError::ChangedDuringUpdate { path: path.clone() },
("ChangedDuringUpdate", 1),
),
(
StoreError::CommittedNotDurable {
path,
source: io::Error::other("test"),
},
("CommittedNotDurable", 1),
),
];
for (error, expected) in other_errors {
assert_mapping(UpdateError::Store(error), expected);
}
}
#[test]
fn maps_every_cli_error_including_clap_usage() {
let path = PathBuf::from("config.toml");
let config_error = Config::parse(&path, "unknown_key = true", None).unwrap_err();
let io_error = || io::Error::other("test");
let other_errors = [
(
CliError::Usage(clap::Error::raw(ErrorKind::InvalidValue, "test")),
("Usage", 2),
),
(CliError::MissingConfigHome, ("MissingConfigHome", 1)),
(
CliError::ReadConfig(path.clone(), io_error()),
("ConfigIo", 1),
),
(
CliError::Config(path.clone(), config_error),
("InvalidConfig", 1),
),
(
CliError::RegistryHome(path, io_error()),
("RegistryHomeIo", 1),
),
(CliError::Probe(ProbeError::new("test")), ("Probe", 1)),
(
CliError::EphemeralRange(ProbeError::new("test")),
("EphemeralRange", 1),
),
(
CliError::Json(<serde_json::Error as serde::ser::Error>::custom("test")),
("Json", 1),
),
(CliError::Output(io_error()), ("Output", 1)),
(
CliError::Timestamp(
Date::MIN
.midnight()
.assume_utc()
.format(&Rfc3339)
.unwrap_err(),
),
("Timestamp", 1),
),
];
for (error, expected) in other_errors {
assert_mapping(error, expected);
}
}
}