65 lines
2.3 KiB
Rust
65 lines
2.3 KiB
Rust
//! 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
|
||
|
|
|
||
|
|
use std::net::SocketAddr;
|
||
|
|
use std::time::Duration;
|
||
|
|
|
||
|
|
use anyhow::Context;
|
||
|
|
|
||
|
|
/// Initializes `tracing` from `RUST_LOG` and `LOG_FORMAT`.
|
||
|
|
pub fn init_logging() {
|
||
|
|
use tracing_subscriber::EnvFilter;
|
||
|
|
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info,tower_http=info"));
|
||
|
|
let builder = tracing_subscriber::fmt().with_env_filter(filter);
|
||
|
|
if std::env::var("LOG_FORMAT").is_ok_and(|f| f.eq_ignore_ascii_case("json")) {
|
||
|
|
builder.json().init();
|
||
|
|
} else {
|
||
|
|
builder.init();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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");
|
||
|
|
}
|