#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
use std::path::{Path, PathBuf};
use anyhow::{Context as _, bail};
use clap::{Parser, Subcommand};
use nitr::{Config, Server};
use nitr_cli::apidef;
mod bundle;
mod cmd;
mod diag;
mod scaffold;
const DEFAULT_CONFIG_FILE: &str = "nitr.toml";
#[derive(Parser)]
#[command(
name = "nitr",
disable_version_flag = true,
after_help = "Signals:\n SIGHUP Zero-downtime reload: rebuilds the Lua runtime pool and re-reads TLS certificates"
)]
struct Cli {
#[arg(short = 'v', long = "version", global = true)]
version: bool,
#[arg(short = 'c', long = "config", global = true, value_name = "PATH")]
config: Option<PathBuf>,
#[arg(long, global = true)]
dev: bool,
#[command(subcommand)]
command: Option<Command>,
}
#[derive(Subcommand)]
enum Command {
Run {
#[arg(long)]
migrate: bool,
},
Dev {
#[arg(long)]
migrate: bool,
},
Check {
#[arg(long)]
print_config: bool,
},
Test {
#[arg(long, value_name = "SUBSTRING")]
filter: Option<String>,
#[arg(long)]
bail: bool,
#[arg(long)]
list: bool,
#[arg(long)]
watch: bool,
#[arg(long, value_enum, default_value = "pretty")]
reporter: cmd::test::Reporter,
#[arg(short, long, value_name = "FILE")]
output: Option<PathBuf>,
#[arg(long)]
nocapture: bool,
},
Openapi {
#[arg(short, long, value_name = "PATH")]
output: Option<PathBuf>,
#[arg(long)]
check: bool,
#[arg(long, value_name = "DIR")]
ui: Option<PathBuf>,
},
Migrate {
#[arg(long)]
status: bool,
},
Init {
dir: Option<PathBuf>,
#[arg(long)]
minimal: bool,
},
Build {
#[arg(short, long, value_name = "PATH")]
output: PathBuf,
},
Reload,
HashPassword,
}
fn load_config(cli: &Cli) -> anyhow::Result<(Config, Vec<String>)> {
let mut env_base = PathBuf::from(".");
let bundled = bundle::load()?;
let is_bundle = bundled.is_some();
if is_bundle && cli.config.is_some() {
anyhow::bail!(
"this executable carries a bundle with its own configuration; --config is not \
accepted (values that must differ per deployment come from the environment)"
);
}
let mut warnings = Vec::new();
let mut cfg = match bundled {
Some((cfg, bundle_warnings)) => {
warnings = bundle_warnings;
cfg
}
None => match &cli.config {
Some(path) => {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
env_base = parent.to_path_buf();
}
Config::from_file(path)?
}
None => {
let default = Path::new(DEFAULT_CONFIG_FILE);
if default.is_file() {
Config::from_file(default)?
} else {
Config::default()
}
}
},
};
cfg.load_env_file(&env_base)?;
cfg.apply_env()?;
if cli.dev || matches!(cli.command, Some(Command::Dev { .. })) {
cfg.dev_mode = true;
}
if is_bundle {
warnings.extend(bundle::seal(&mut cfg));
}
Ok((cfg, warnings))
}
fn logs_to_stderr(command: &Option<Command>) -> bool {
match command {
Some(Command::Openapi { .. }) => true,
Some(Command::Test {
reporter, output, ..
}) => *reporter != cmd::test::Reporter::Pretty && output.is_none(),
_ => false,
}
}
#[derive(Clone, Copy)]
struct TestLogs {
capture: bool,
console: bool,
}
fn test_logs(command: &Option<Command>, cfg: &Config) -> Option<TestLogs> {
match command {
Some(Command::Test { nocapture, .. }) if cfg.testing.capture => Some(TestLogs {
capture: true,
console: *nocapture,
}),
_ => None,
}
}
fn init_logging(
cfg: Option<&Config>,
dev: bool,
to_stderr: bool,
test: Option<TestLogs>,
) -> anyhow::Result<()> {
let fallback = || -> anyhow::Result<tracing_subscriber::EnvFilter> {
let configured = cfg.and_then(|c| c.log.level.clone());
let level = configured.unwrap_or_else(|| {
if dev || cfg.is_some_and(|c| c.dev_mode) {
"debug".into()
} else {
"info".into()
}
});
let is_level =
|word: &str| word.eq_ignore_ascii_case("off") || word.parse::<tracing::Level>().is_ok();
let directive_ok = |directive: &str| directive.contains('=') || is_level(directive.trim());
if !level.split(',').all(directive_ok) {
anyhow::bail!(
"[log] level = {level:?} is not a level (error, warn, info, debug, trace, \
off) or a `target=level` list"
);
}
tracing_subscriber::EnvFilter::try_new(&level)
.map_err(|err| anyhow::anyhow!("[log] level = {level:?} is not a valid filter: {err}"))
};
let filter = match tracing_subscriber::EnvFilter::try_from_default_env() {
Ok(filter) => filter,
Err(_) => fallback()?,
};
let json = matches!(cfg.map(|c| c.log.format), Some(nitr::LogFormat::Json));
use std::io::IsTerminal as _;
let stream_is_terminal = if to_stderr {
std::io::stderr().is_terminal()
} else {
std::io::stdout().is_terminal()
};
let colors =
!json && stream_is_terminal && std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty());
nitr::diag::set_console_colors(colors);
if let Some(test) = test {
init_test_logging(filter, test, json, colors, to_stderr);
return Ok(());
}
let builder = tracing_subscriber::fmt()
.with_env_filter(filter)
.with_span_events(tracing_subscriber::fmt::format::FmtSpan::CLOSE);
if to_stderr {
finish_logging(builder.with_writer(std::io::stderr), json, colors);
} else {
finish_logging(builder, json, colors);
}
Ok(())
}
fn finish_logging<W>(
builder: tracing_subscriber::fmt::SubscriberBuilder<
tracing_subscriber::fmt::format::DefaultFields,
tracing_subscriber::fmt::format::Format,
tracing_subscriber::EnvFilter,
W,
>,
json: bool,
colors: bool,
) where
W: for<'w> tracing_subscriber::fmt::MakeWriter<'w> + Send + Sync + 'static,
{
if json {
builder.json().init();
} else if colors {
builder
.event_format(diag::PaintedFormat(
tracing_subscriber::fmt::format().with_ansi(true),
))
.init();
} else {
builder.with_ansi(false).init();
}
}
fn init_test_logging(
console_filter: tracing_subscriber::EnvFilter,
test: TestLogs,
json: bool,
colors: bool,
to_stderr: bool,
) {
use tracing_subscriber::Layer as _;
use tracing_subscriber::layer::SubscriberExt as _;
use tracing_subscriber::util::SubscriberInitExt as _;
let capture_filter = tracing_subscriber::EnvFilter::new(console_filter.to_string())
.add_directive(
"lua=debug"
.parse()
.unwrap_or_else(|_| tracing::Level::DEBUG.into()),
);
let console = test.console.then(|| {
let base = tracing_subscriber::fmt::layer()
.with_span_events(tracing_subscriber::fmt::format::FmtSpan::CLOSE);
let layer: Box<dyn tracing_subscriber::Layer<tracing_subscriber::Registry> + Send + Sync> =
match (json, colors, to_stderr) {
(true, _, false) => base.json().boxed(),
(true, _, true) => base.json().with_writer(std::io::stderr).boxed(),
(false, true, false) => base
.event_format(diag::PaintedFormat(
tracing_subscriber::fmt::format().with_ansi(true),
))
.boxed(),
(false, true, true) => base
.event_format(diag::PaintedFormat(
tracing_subscriber::fmt::format().with_ansi(true),
))
.with_writer(std::io::stderr)
.boxed(),
(false, false, false) => base.with_ansi(false).boxed(),
(false, false, true) => base.with_ansi(false).with_writer(std::io::stderr).boxed(),
};
layer.with_filter(console_filter)
});
let capture = test
.capture
.then(|| cmd::test::capture::CaptureLayer.with_filter(capture_filter));
tracing_subscriber::registry()
.with(console)
.with(capture)
.init();
}
struct Pidfile(PathBuf);
impl Pidfile {
fn write(path: &Path) -> anyhow::Result<Self> {
use std::io::Write as _;
let create = || {
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
};
let mut file = match create() {
Ok(file) => file,
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
if let Some(pid) = read_pid(path)
&& pid != std::process::id()
&& process_alive(pid)
{
bail!(
"the pidfile {} names a running process ({pid}); is another \
instance already up? Stop it, or point `pidfile` elsewhere",
path.display()
);
}
std::fs::remove_file(path).with_context(|| {
format!("cannot replace the stale pidfile {}", path.display())
})?;
create().with_context(|| format!("cannot create the pidfile {}", path.display()))?
}
Err(err) => {
return Err(err)
.with_context(|| format!("cannot create the pidfile {}", path.display()));
}
};
writeln!(file, "{}", std::process::id())
.with_context(|| format!("cannot write the pidfile {}", path.display()))?;
Ok(Self(path.to_path_buf()))
}
}
fn read_pid(path: &Path) -> Option<u32> {
std::fs::read_to_string(path).ok()?.trim().parse().ok()
}
#[cfg(unix)]
fn process_alive(pid: u32) -> bool {
if Path::new("/proc/self").exists() {
return Path::new(&format!("/proc/{pid}")).exists();
}
match std::process::Command::new("kill")
.args(["-0", &pid.to_string()])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
{
Ok(status) => status.success(),
Err(_) => true,
}
}
#[cfg(unix)]
fn is_nitr_process(pid: u32) -> bool {
if !Path::new("/proc/self").exists() {
return true;
}
if let Ok(exe) = std::fs::read_link(format!("/proc/{pid}/exe")) {
let exe = PathBuf::from(
exe.to_string_lossy()
.trim_end_matches(" (deleted)")
.to_string(),
);
if std::env::current_exe().is_ok_and(|own| own == exe) {
return true;
}
if let Ok(Some(_)) = bundle::read_appended(&exe) {
return true;
}
}
let own_comm = std::fs::read_to_string("/proc/self/comm")
.map(|s| s.trim().to_string())
.unwrap_or_default();
match std::fs::read_to_string(format!("/proc/{pid}/comm")) {
Ok(comm) => comm.trim().contains("nitr") || comm.trim() == own_comm,
Err(_) => true,
}
}
#[cfg(not(unix))]
fn process_alive(_pid: u32) -> bool {
false
}
impl Drop for Pidfile {
fn drop(&mut self) {
std::fs::remove_file(&self.0).ok();
}
}
fn reload(cfg: &Config) -> anyhow::Result<()> {
let path = cfg.pidfile.as_ref().context(
"no `pidfile` is configured: set `pidfile` in nitr.toml so `nitr reload` \
can find the running server",
)?;
let raw = std::fs::read_to_string(path).with_context(|| {
format!(
"cannot read the pidfile {} (is the server running?)",
path.display()
)
})?;
let pid: u32 = raw
.trim()
.parse()
.with_context(|| format!("the pidfile {} does not contain a pid", path.display()))?;
if pid < 2 || pid == std::process::id() {
bail!(
"the pidfile {} names pid {pid}, which cannot be a running server",
path.display()
);
}
#[cfg(unix)]
{
if !is_nitr_process(pid) {
bail!(
"pid {pid} from the pidfile {} does not look like a nitr server. If the \
server is a `nitr build` artifact, run `reload` from that artifact; if \
it is not running any more, remove the stale pidfile",
path.display()
);
}
let status = std::process::Command::new("kill")
.args(["-HUP", &pid.to_string()])
.status()
.context("cannot run `kill`")?;
if !status.success() {
bail!("kill -HUP {pid} failed: is the server still running?");
}
println!("sent SIGHUP to pid {pid}: the server is rebuilding its runtime pool");
Ok(())
}
#[cfg(not(unix))]
{
let _ = pid;
bail!("`nitr reload` needs Unix signals, which this platform does not have");
}
}
#[tokio::main]
async fn main() {
if let Err(err) = run_main().await {
diag::report(&err);
std::process::exit(1);
}
}
async fn run_main() -> anyhow::Result<()> {
let cli = Cli::parse();
if cli.version {
println!("nitr {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
if let Some(Command::Init { dir, minimal }) = &cli.command {
init_logging(None, cli.dev, logs_to_stderr(&cli.command), None)?;
return scaffold::init(dir.as_deref().unwrap_or(Path::new(".")), *minimal);
}
if let Some(Command::HashPassword) = &cli.command {
init_logging(None, cli.dev, logs_to_stderr(&cli.command), None)?;
return cmd::hash_password::hash_password().await;
}
let cfg = match load_config(&cli) {
Ok((cfg, warnings)) => {
init_logging(
Some(&cfg),
cli.dev,
logs_to_stderr(&cli.command),
test_logs(&cli.command, &cfg),
)?;
for warning in warnings {
tracing::warn!("{warning}");
}
cfg
}
Err(err) => {
init_logging(None, cli.dev, logs_to_stderr(&cli.command), None)?;
return Err(err);
}
};
match cli.command.unwrap_or(Command::Run { migrate: false }) {
#[allow(clippy::unreachable)]
Command::Init { .. } | Command::HashPassword => unreachable!("handled above"),
Command::Run { migrate } | Command::Dev { migrate } => {
if migrate {
cmd::migrate::migrate(&cfg, false)?;
}
let pidfile_path = cfg.pidfile.clone();
let server = Server::builder().config(cfg).build().await?;
let pidfile = pidfile_path.as_deref().map(Pidfile::write).transpose()?;
let result = server.serve().await;
drop(pidfile);
result?;
}
Command::Check { print_config } => {
if print_config {
print!("{}", cfg.effective_toml()?);
return Ok(());
}
cmd::check::check(cfg).await?;
}
Command::Test {
filter,
bail,
list,
watch,
reporter,
output,
nocapture,
} => {
let args = cmd::test::TestArgs {
filter,
bail,
list,
watch,
reporter,
output,
nocapture,
};
if args.watch {
cmd::test::watch(cfg, &args).await?;
std::process::exit(0);
}
if cmd::test::run(cfg, &args).await?.failed() {
std::process::exit(1);
}
}
Command::Migrate { status } => cmd::migrate::migrate(&cfg, status)?,
Command::Openapi { output, check, ui } => {
let args = cmd::openapi::OpenapiArgs { output, check, ui };
if cmd::openapi::run(cfg, args).await? == cmd::openapi::Outcome::Drift {
std::process::exit(1);
}
}
Command::Build { output } => {
let cfg_path = cli
.config
.as_deref()
.unwrap_or(Path::new(DEFAULT_CONFIG_FILE));
if !cfg_path.is_file() {
bail!(
"`nitr build` needs a configuration file ({} not found): the \
bundle records it as the application manifest",
cfg_path.display()
);
}
bundle::build(cfg_path, &cfg, &output)?;
}
Command::Reload => reload(&cfg)?,
}
Ok(())
}