Files
sorsfonalak/crates/service-kit/src/lib.rs
T

95 lines
3.9 KiB
Rust
Raw Normal View History

//! Plumbing shared by every HTTP service.
//!
//! Environment:
//! * `BIND_ADDR` listen address (each service has its own default)
//! * `LOG_FORMAT` `text` (default) or `json`; `RUST_LOG` sets the level
//! * `LOG_DIR` also write the log there, as JSON, one file a day
//! (`<LOG_NAME>.YYYY-MM-DD.log`), keeping `LOG_KEEP_DAYS` (default 30) files
//! * `LOG_NAME` the file name prefix (default: the service's name)
use std::net::SocketAddr;
use std::time::Duration;
use anyhow::Context;
/// Days of log files kept in `LOG_DIR` by default.
const LOG_KEEP_DAYS: usize = 30;
/// Initializes `tracing` from `RUST_LOG` and `LOG_FORMAT`, and the log files
/// in `LOG_DIR` (named after `LOG_NAME`, else `name`), so the log outlives the
/// container.
pub fn init_logging(name: &str) {
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Layer, fmt};
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info,tower_http=info"));
let json = std::env::var("LOG_FORMAT").is_ok_and(|f| f.eq_ignore_ascii_case("json"));
let stdout = if json { fmt::layer().json().boxed() } else { fmt::layer().boxed() };
let mut problem = None;
let file = std::env::var("LOG_DIR").ok().filter(|d| !d.trim().is_empty()).and_then(|dir| {
let prefix =
std::env::var("LOG_NAME").ok().filter(|n| !n.trim().is_empty()).unwrap_or_else(|| name.to_string());
let keep = std::env::var("LOG_KEEP_DAYS").ok().and_then(|d| d.parse().ok()).unwrap_or(LOG_KEEP_DAYS);
let appender = tracing_appender::rolling::Builder::new()
.rotation(tracing_appender::rolling::Rotation::DAILY)
.filename_prefix(prefix)
.filename_suffix("log")
.max_log_files(keep.max(1))
.build(&dir);
match appender {
Ok(appender) => Some(fmt::layer().json().with_ansi(false).with_writer(appender).boxed()),
Err(e) => {
problem = Some(format!("cannot write the log files in {dir}: {e}"));
None
}
}
});
tracing_subscriber::registry().with(filter).with(stdout).with(file).init();
if let Some(problem) = problem {
tracing::warn!("{problem}; logging to stdout only");
}
}
/// Listen address from `BIND_ADDR`, or `default`.
pub fn bind_addr(default: &str) -> anyhow::Result<SocketAddr> {
let raw = std::env::var("BIND_ADDR").unwrap_or_else(|_| default.into());
raw.parse().with_context(|| format!("invalid BIND_ADDR '{raw}'"))
}
/// Minimal HTTP GET against `/healthz` of the local service, so scratch
/// images need no curl. Used by the `healthcheck` subcommand.
pub fn healthcheck(mut addr: SocketAddr) -> anyhow::Result<()> {
use std::io::{Read, Write};
if addr.ip().is_unspecified() {
addr.set_ip([127, 0, 0, 1].into());
}
let mut stream = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(2))?;
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
stream.write_all(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")?;
let mut response = String::new();
stream.read_to_string(&mut response)?;
anyhow::ensure!(response.starts_with("HTTP/1.1 200"), "unhealthy: {}", response.lines().next().unwrap_or(""));
Ok(())
}
/// Resolves on Ctrl+C or SIGTERM (graceful shutdown in Docker).
pub async fn shutdown_signal() {
let ctrl_c = async {
let _ = tokio::signal::ctrl_c().await;
};
#[cfg(unix)]
let terminate = async {
if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
s.recv().await;
}
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
tracing::info!("shutting down");
}