use std::future::Future;
use std::net::SocketAddr;
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Duration;
use axum::response::IntoResponse as _;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use redup_bootstrap_grpc::{Binder, OpenApiDocument, PlatformServices, bind_platform};
use redup_bootstrap_rest::{BuildError, Transcoder, TranscodingConfig};
use crate::apoptosis::Apoptosis;
use crate::bootstrap_config::BootstrapConfig;
use crate::builder::Assembled;
use crate::dependency::Dependencies;
use crate::error::Error;
use crate::grpc_server::{self, providers};
use crate::halt::{Halt, Stop};
use crate::info_source::InfoSource;
use crate::listener::{Listener, Routes};
use crate::memory;
use crate::panic_error::Panic;
use crate::signals;
use crate::stopper::Stopper;
use crate::telemetry::Telemetry;
use crate::telemetry::journal::{Logging, fatal};
const INFLATION_STEP: u64 = 256 * 1024 * 1024;
const NATIVE_PATHS: &[&str] = &[
"/readyz",
"/health",
"/healthz",
"/readyz/{name}",
"/livez",
"/livez/{name}",
"/metrics",
"/info",
"/info/{name}",
"/config",
"/config/{name}",
"/openapi/{file}",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
Built,
Starting,
Running,
Stopping,
Stopped,
Failed,
}
pub struct Instance {
info: Arc<InfoSource>,
dependencies: Vec<Dependencies>,
config: BootstrapConfig,
telemetry: Arc<Telemetry>,
token: CancellationToken,
halt: Halt,
listener: Option<Listener>,
grpc_listener: Option<Listener>,
transcoding_listener: Option<Listener>,
grpc: Binder,
instance_id: String,
}
fn with_openapi(router: axum::Router, documents: Vec<OpenApiDocument>) -> axum::Router {
let documents: std::collections::HashMap<&'static str, &'static str> = documents
.into_iter()
.map(|document| (document.name(), document.json()))
.collect();
let documents = Arc::new(documents);
let handler = move |axum::extract::Path(file): axum::extract::Path<String>| {
let documents = Arc::clone(&documents);
async move {
let Some(name) = file.strip_suffix(".json") else {
return (axum::http::StatusCode::NOT_FOUND, "Not found").into_response();
};
match documents.get(name) {
Some(json) => (
[(
axum::http::header::CONTENT_TYPE,
"application/json; charset=utf-8",
)],
*json,
)
.into_response(),
None => (axum::http::StatusCode::NOT_FOUND, "Not found").into_response(),
}
}
};
router.route("/openapi/{file}", axum::routing::get(handler))
}
fn fallback(
transcoder: Arc<Transcoder>,
) -> impl Fn(
axum::extract::Request,
) -> futures_util::future::BoxFuture<'static, axum::response::Response>
+ Clone
+ Send
+ Sync
+ 'static {
move |request| {
let transcoder = Arc::clone(&transcoder);
Box::pin(async move { transcoder.handle(request).await })
}
}
async fn isolated<T, F>(point: F) -> Result<T, Panic>
where
F: Future<Output = T> + Send + 'static,
T: Send + 'static,
{
match tokio::spawn(point).await {
Ok(value) => Ok(value),
Err(join) if join.is_panic() => Err(Panic::from_payload(join.try_into_panic().ok())),
Err(_) => Err(Panic(None)),
}
}
impl Instance {
pub(crate) fn new(assembled: Assembled) -> Self {
let Assembled {
entries,
dependencies,
configs,
telemetry,
config,
service,
token,
halt,
instance_id,
grpc,
} = assembled;
let handles = dependencies.iter().map(Dependencies::handles).collect();
let info = Arc::new(InfoSource::new(
service,
entries,
handles,
configs,
telemetry.load(),
));
Self {
info,
dependencies,
config,
telemetry: Arc::new(telemetry),
token,
halt,
listener: None,
grpc_listener: None,
transcoding_listener: None,
grpc,
instance_id,
}
}
pub fn state(&self) -> State {
self.info.state()
}
pub fn snapshot(&self) -> crate::snapshot::Snapshot {
self.info.snapshot()
}
pub fn address(&self) -> Option<SocketAddr> {
self.listener.as_ref().map(Listener::address)
}
pub fn grpc_address(&self) -> Option<SocketAddr> {
self.grpc_listener.as_ref().map(Listener::address)
}
pub fn stopper(&self) -> Stopper {
Stopper::new(self.halt.clone())
}
pub fn apoptosis(&self) -> Apoptosis {
Apoptosis::new(self.config.control().oom().is_some(), self.halt.clone())
}
pub fn logging(&self) -> Logging {
self.telemetry.logging()
}
pub async fn start(&mut self) -> Result<(), Error> {
if self.state() != State::Built {
return Err(Error::State {
action: "be started",
});
}
self.info.set_state(State::Starting);
self.info.mark_started();
self.start_load_average();
let compression = self
.config
.rest()
.map_or(1024, crate::rest_config::RestConfig::compression_threshold);
let concurrent_limit = self.config.rest().map_or(
128,
crate::rest_config::RestConfig::concurrent_requests_limit,
);
let grpc_config = self.config.grpc().cloned();
let grpc_router = match &grpc_config {
Some(grpc) => match self.start_grpc(grpc).await {
Ok(router) => Some(router),
Err(error) => return Err(self.failed(error).await),
},
None => None,
};
let transcoding = grpc_config.as_ref().and_then(|grpc| grpc.transcoding());
let transcoder = match self.build_transcoder(transcoding, grpc_router.as_ref()) {
Ok(transcoder) => transcoder,
Err(error) => return Err(self.failed(error).await),
};
let documents = transcoding
.filter(|config| config.enable_open_api())
.map(|_| self.grpc.openapi_documents())
.filter(|documents| !documents.is_empty());
let rest = self.config.rest().cloned();
let shared_port = match (&rest, transcoding) {
(Some(rest), Some(config)) if transcoder.is_some() && config.port() == rest.port() => {
let host = grpc_config
.as_ref()
.map_or("0.0.0.0", crate::grpc_config::GrpcConfig::host);
if host != rest.host() {
let error = Error::Rest {
source: Box::new(redup_bootstrap_rest::BuildError::new(format!(
"the gRPC host '{host}' and the REST host '{}' must match on a shared port",
rest.host()
))),
};
return Err(self.failed(error).await);
}
true
}
_ => false,
};
if let Some(rest) = &rest {
let routes = Routes {
snapshot: self.snapshot_source(),
telemetry: Arc::clone(&self.telemetry),
info: Arc::clone(&self.info),
};
let mut router = crate::routes::router(routes);
if let Some(transcoder) = &transcoder {
let conflicts = transcoder.conflicts(NATIVE_PATHS);
if conflicts.is_empty() {
router = router.fallback(fallback(Arc::clone(transcoder)));
if shared_port && let Some(documents) = &documents {
router = with_openapi(router, documents.clone());
}
} else if shared_port {
let mut text = String::new();
for conflict in &conflicts {
text.push_str(&format!(
"\n '{}' overlaps the native path '{}'",
conflict.route(),
conflict.native()
));
}
let error = Error::Rest {
source: Box::new(redup_bootstrap_rest::BuildError::new(format!(
"the transcoding routes overlap native REST paths:{text}"
))),
};
return Err(self.failed(error).await);
} else {
tracing::warn!(
routes = ?conflicts
.iter()
.map(|conflict| conflict.route())
.collect::<Vec<_>>(),
"transcoding routes overlap native REST paths: they are served only on \
the transcoding port"
);
}
}
let router = crate::http::wrap(router, compression, concurrent_limit);
match Listener::bind(rest.host(), rest.port(), router, "REST").await {
Ok(listener) => self.listener = Some(listener),
Err(source) => {
let error = Error::Bind {
address: format!("{}:{}", rest.host(), rest.port()),
source,
};
return Err(self.failed(error).await);
}
}
}
if let Some(transcoder) = transcoder.filter(|_| !shared_port) {
let port = transcoding.map_or(8081, redup_bootstrap_rest::TranscodingConfig::port);
let host = grpc_config
.as_ref()
.map_or("0.0.0.0", crate::grpc_config::GrpcConfig::host);
let mut router = axum::Router::new().fallback(fallback(transcoder));
if let Some(documents) = &documents {
router = with_openapi(router, documents.clone());
}
let router = crate::http::wrap(router, compression, concurrent_limit);
match Listener::bind(host, port, router, "transcoding").await {
Ok(listener) => self.transcoding_listener = Some(listener),
Err(source) => {
let error = Error::Bind {
address: format!("{host}:{port}"),
source,
};
return Err(self.failed(error).await);
}
}
}
let entries: Vec<(std::sync::Arc<dyn crate::runtime::Runtime>, &'static str)> = self
.info
.modules()
.iter()
.map(|entry| (Arc::clone(&entry.module), entry.name))
.collect();
for (module, name) in entries {
match isolated(module.start()).await {
Ok(Ok(())) => {
tracing::info!(module = name, "module started");
}
Ok(Err(source)) => {
tracing::error!(module = name, error = %source, "module failed to start");
self.release().await;
self.info.set_state(State::Failed);
return Err(Error::Start {
module: name,
source,
});
}
Err(panic) => {
tracing::warn!(
module = name,
error = %panic,
"module failed to start after a panic recorded above"
);
self.release().await;
self.info.set_state(State::Failed);
return Err(Error::Start {
module: name,
source: Box::new(panic),
});
}
}
}
self.info.set_state(State::Running);
tracing::info!(
service = self.info.service().name(),
version = self.info.service().version(),
modules = self.info.modules().len(),
"the instance is running"
);
Ok(())
}
pub async fn stop(&mut self) {
if matches!(self.state(), State::Stopping | State::Stopped) {
return;
}
let running = self.state() == State::Running;
self.info.set_state(State::Stopping);
if running {
self.drain().await;
}
self.finish().await;
}
async fn stop_fatal(&mut self) {
self.stop_without_drain().await;
}
async fn stop_without_drain(&mut self) {
if matches!(self.state(), State::Stopping | State::Stopped) {
return;
}
self.info.set_state(State::Stopping);
self.finish().await;
}
async fn finish(&mut self) {
self.release().await;
self.info.set_state(State::Stopped);
tracing::info!("the instance is stopped");
#[cfg(feature = "otlp")]
self.telemetry.finish();
}
pub async fn run(mut self) -> ExitCode {
if let Err(error) = self.start().await {
tracing::error!(error = %error, "the instance failed to start");
return ExitCode::from(1);
}
self.listen_to_signals();
match self.halt.wait().await {
Stop::Fatal(reason) => {
fatal!(
reason = reason.as_str(),
"the service stops on a fatal report: continuing may corrupt data"
);
self.stop_fatal().await;
ExitCode::from(1)
}
Stop::Apoptosis(reason) => self.apoptose(reason).await,
Stop::Signal | Stop::Request(_) => {
self.stop().await;
ExitCode::SUCCESS
}
Stop::RequestFast(_) => {
tracing::info!("the instance stops on request without draining");
self.stop_without_drain().await;
ExitCode::SUCCESS
}
}
}
fn listen_to_signals(&self) {
let halt = self.halt.clone();
tokio::spawn(async move {
if let Err(error) = signals::terminate().await {
tracing::error!(
error = %error,
"termination signals are not being listened to; the instance can be stopped \
only by a request"
);
return;
}
if halt.stop(Stop::Signal) {
tracing::info!(
"termination signal received: the instance is stopping. A repeated signal \
exits the process immediately"
);
let _ = signals::terminate().await;
}
std::process::exit(130);
});
}
fn build_transcoder(
&self,
config: Option<TranscodingConfig>,
grpc: Option<&axum::Router>,
) -> Result<Option<Arc<Transcoder>>, Error> {
let Some(config) = config else {
return Ok(None);
};
let routes = self.grpc.http_routes();
if routes.is_empty() {
return Ok(None);
}
let Some(grpc) = grpc else {
return Err(Error::Rest {
source: Box::new(BuildError::new(
"transcoding is configured, but the grpc section is absent",
)),
});
};
let timeout = self
.config
.grpc()
.map_or(std::time::Duration::from_secs(15), |grpc| {
grpc.default_time_out()
});
let transcoder = Transcoder::build(
routes,
self.grpc.descriptors(),
config,
grpc.clone(),
timeout,
)
.map_err(|source| Error::Rest {
source: Box::new(source),
})?;
Ok(Some(Arc::new(transcoder)))
}
async fn failed(&mut self, error: Error) -> Error {
tracing::error!(error = %error, "the instance failed to start");
self.release().await;
self.info.set_state(State::Failed);
error
}
async fn start_grpc(
&mut self,
config: &crate::grpc_config::GrpcConfig,
) -> Result<axum::Router, Error> {
let mut names: Vec<String> = self
.grpc
.services()
.iter()
.map(|service| service.name().to_owned())
.collect();
for name in [
"grpc.health.v1.Health",
"redup.bootstrap.v1.Info",
"redup.bootstrap.v1.Metrics",
"redup.bootstrap.v1.Control",
"grpc.reflection.v1.ServerReflection",
"grpc.reflection.v1alpha.ServerReflection",
] {
names.push(name.to_owned());
}
let services = PlatformServices {
health: Arc::new(providers::HealthState::new(Arc::clone(&self.info), names)),
info: Arc::new(providers::InfoState::new(
Arc::clone(&self.info),
self.grpc.services(),
)),
metrics: Arc::new(providers::MetricsState::new(
Arc::clone(&self.info),
Arc::clone(&self.telemetry),
)),
control: Arc::new(providers::ControlState::new(
Stopper::new(self.halt.clone()),
Apoptosis::new(self.config.control().oom().is_some(), self.halt.clone()),
self.telemetry.logging(),
self.token.child_token(),
)),
};
bind_platform(&self.grpc, services).map_err(|source| Error::Grpc {
source: Box::new(source),
})?;
self.start_health_watch();
let state = grpc_server::State {
binder: self.grpc.clone(),
telemetry: Arc::clone(&self.telemetry),
service_name: self.info.service().name().to_owned(),
instance_id: self.instance_id.clone(),
exposure: config.errors().exposure(),
debug_info: config.errors().debug_info(),
token: self.token.child_token(),
};
let router = grpc_server::router(self.grpc.take_routes(), state);
let listener = Listener::bind(config.host(), config.port(), router.clone(), "gRPC")
.await
.map_err(|source| Error::Bind {
address: format!("{}:{}", config.host(), config.port()),
source,
})?;
self.grpc_listener = Some(listener);
Ok(router)
}
fn start_health_watch(&self) {
for entry in self.info.modules() {
let Some(health) = entry.health.clone() else {
continue;
};
let mut changes = health.subscribe();
let info = Arc::clone(&self.info);
let token = self.token.child_token();
tokio::spawn(async move {
loop {
tokio::select! {
_ = token.cancelled() => return,
changed = changes.changed() => {
if changed.is_err() {
return;
}
info.notify();
}
}
}
});
}
}
fn start_load_average(&self) {
let token = self.token.child_token();
let averages = self.telemetry.clone();
tokio::spawn(async move {
averages.run(token).await;
});
}
fn snapshot_source(&self) -> crate::listener::SnapshotSource {
let info = Arc::clone(&self.info);
Arc::new(move || info.snapshot())
}
async fn drain(&self) {
let timeout = self.config.control().drain_timeout();
let mut tasks: Vec<(&'static str, JoinHandle<()>)> = Vec::new();
for entry in self.info.modules() {
let module = Arc::clone(&entry.module);
let name = entry.name;
tasks.push((
name,
tokio::spawn(async move {
match tokio::time::timeout(timeout, module.drain()).await {
Ok(Ok(())) => {}
Ok(Err(source)) => {
tracing::warn!(module = name, error = %source, "module failed to drain")
}
Err(_) => tracing::warn!(
module = name,
timeout = ?timeout,
"module did not finish draining within the drain timeout"
),
}
}),
));
}
for (name, task) in tasks {
if task.await.is_err() {
tracing::warn!(module = name, "module panicked while draining");
}
}
}
async fn stop_modules(&self, timeout: Option<Duration>) {
let stopping = async {
for entry in self.info.modules().iter().rev() {
let module = Arc::clone(&entry.module);
let name = entry.name;
match isolated(module.stop()).await {
Ok(Ok(())) => {}
Ok(Err(source)) => {
tracing::error!(module = name, error = %source, "module failed to stop")
}
Err(panic) => {
tracing::warn!(
module = name,
error = %panic,
"module failed to stop after a panic recorded above"
);
}
}
}
};
match timeout {
None => stopping.await,
Some(limit) => {
if tokio::time::timeout(limit, stopping).await.is_err() {
tracing::warn!(
limit = ?limit,
"modules did not stop within the timeout; proceeding without them"
);
}
}
}
}
async fn release(&mut self) {
self.token.cancel();
self.stop_modules(None).await;
for dependencies in &mut self.dependencies {
dependencies.shutdown().await;
}
if let Some(listener) = self.listener.take() {
listener.shutdown().await;
}
if let Some(listener) = self.grpc_listener.take() {
listener.shutdown().await;
}
if let Some(listener) = self.transcoding_listener.take() {
listener.shutdown().await;
}
}
async fn apoptose(&mut self, reason: String) -> ExitCode {
fatal!(
reason,
memory = memory::resident_bytes(),
limit = memory::container_limit(),
"apoptosis: the service cannot recover from the memory shortage and will be unloaded"
);
self.info.set_state(State::Stopping);
let timeout = self
.config
.control()
.oom()
.map(|oom| oom.modules_shutdown_timeout());
self.token.cancel();
self.stop_modules(timeout).await;
for dependencies in &mut self.dependencies {
dependencies.shutdown().await;
}
let Some(limit) = memory::container_limit() else {
tracing::error!("the container has no memory limit; the process exits with code 137");
return ExitCode::from(137);
};
let mut target = limit;
loop {
match memory::inflate(target).await {
Ok(()) => target = target.saturating_add(INFLATION_STEP),
Err(error) => {
tracing::error!(
%error,
"memory inflation stopped before the limit; the process exits with code 137"
);
return ExitCode::from(137);
}
}
}
}
}