use std::future::Future;
use std::net::SocketAddr;
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Duration;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use redup_bootstrap_grpc::{Binder, PlatformServices, bind_platform};
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;
#[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>,
grpc: Binder,
instance_id: String,
}
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,
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();
if let Some(rest) = self.config.rest() {
let routes = Routes {
snapshot: self.snapshot_source(),
telemetry: Arc::clone(&self.telemetry),
info: Arc::clone(&self.info),
};
let listener = Listener::bind(
rest.host(),
rest.port(),
crate::routes::router(routes),
"REST",
)
.await
.map_err(|source| Error::Bind {
address: format!("{}:{}", rest.host(), rest.port()),
source,
});
match listener {
Ok(listener) => self.listener = Some(listener),
Err(error) => {
tracing::error!(error = %error, "the instance failed to start");
self.release().await;
self.info.set_state(State::Failed);
return Err(error);
}
}
}
if let Some(grpc) = self.config.grpc().cloned()
&& let Err(error) = self.start_grpc(&grpc).await
{
tracing::error!(error = %error, "the instance failed to start");
self.release().await;
self.info.set_state(State::Failed);
return Err(error);
}
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);
});
}
async fn start_grpc(&mut self, config: &crate::grpc_config::GrpcConfig) -> Result<(), 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, "gRPC")
.await
.map_err(|source| Error::Bind {
address: format!("{}:{}", config.host(), config.port()),
source,
})?;
self.grpc_listener = Some(listener);
Ok(())
}
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;
}
}
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);
}
}
}
}
}