use std::sync::Arc;
use std::time::Duration;
use redup_abstractions::Phase;
use redup_bootstrap_grpc::contracts::grpc::health::v1::health_check_response::ServingStatus;
use redup_bootstrap_grpc::contracts::redup::bootstrap::v1::instance_info::module_info::ModuleType;
use redup_bootstrap_grpc::contracts::redup::bootstrap::v1::instance_info::{
BootstrapInfo, LoadAverageInfo, ModuleInfo,
};
use redup_bootstrap_grpc::contracts::redup::bootstrap::v1::{
ChangeGlobalLoggingCommand, HaltCommand, InstanceInfo, LogLevel, LogMessage,
MemoryDiagnosticsRequest, MemoryInfo,
};
use redup_bootstrap_grpc::{
ControlProvider, HealthProvider, InfoProvider, LogStream, MetricsProvider,
};
use tonic::Status;
use crate::apoptosis::Apoptosis;
use crate::info_source::InfoSource;
use crate::memory;
use crate::stopper::Stopper;
use crate::telemetry::Telemetry;
use crate::telemetry::journal::Logging;
use crate::telemetry::level::Level;
use crate::telemetry::load::LoadKind;
const HALT_CONFLICT: &str = "inflateMemory and failFast are incompatible";
const BUILD_TIME: i64 = match i64::from_str_radix(env!("REDUP_BUILD_TIME"), 10) {
Ok(seconds) => seconds,
Err(_) => 0,
};
pub(crate) struct HealthState {
info: Arc<InfoSource>,
services: Vec<String>,
}
impl HealthState {
pub(crate) fn new(info: Arc<InfoSource>, services: Vec<String>) -> Self {
Self { info, services }
}
}
impl HealthProvider for HealthState {
fn status(&self, name: &str) -> Option<ServingStatus> {
let snapshot = self.info.snapshot();
match name {
"" | "*" | "readiness" => Some(serving(snapshot.readiness())),
"liveness" => Some(serving(snapshot.liveness())),
_ => {
if let Some(module) = self
.info
.modules()
.iter()
.find(|module| module.name == name)
{
return Some(serving(crate::info_source::module_phase(
module.health.as_ref(),
)));
}
if self.services.iter().any(|service| service == name) {
return Some(serving(snapshot.readiness()));
}
None
}
}
}
fn names(&self) -> Vec<String> {
let mut names = vec![
String::new(),
"*".to_owned(),
"readiness".to_owned(),
"liveness".to_owned(),
];
names.extend(
self.info
.modules()
.iter()
.map(|module| module.name.to_owned()),
);
names.extend(self.services.iter().cloned());
names
}
fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
self.info.subscribe()
}
}
pub(crate) struct InfoState {
info: Arc<InfoSource>,
services: Vec<redup_bootstrap_grpc::ServiceInfo>,
}
impl InfoState {
pub(crate) fn new(
info: Arc<InfoSource>,
services: Vec<redup_bootstrap_grpc::ServiceInfo>,
) -> Self {
Self { info, services }
}
}
impl InfoProvider for InfoState {
fn instance_info(&self) -> InstanceInfo {
let modules = self
.info
.modules()
.iter()
.map(|module| {
let exposed: Vec<String> = self
.services
.iter()
.filter(|service| service.module() == module.name)
.map(|service| service.name().to_owned())
.collect();
let problems = module
.health
.as_ref()
.map(|health| {
health
.snapshot()
.problems()
.iter()
.map(|problem| format!("{}: {}", problem.source(), problem.message()))
.collect()
})
.unwrap_or_default();
ModuleInfo {
name: module.name.to_owned(),
version: self.info.service().version().to_owned(),
build_time: Some(prost_types::Timestamp {
seconds: BUILD_TIME,
nanos: 0,
}),
maintainers: Vec::new(),
r#type: if exposed.is_empty() {
ModuleType::Unspecified as i32
} else {
ModuleType::GrpcService as i32
},
exposed_grpc_services: exposed,
exposed_rest_endpoints: Vec::new(),
problems,
used_config_names: module.config.iter().cloned().collect(),
running_requests: i32::try_from(
self.services
.iter()
.filter(|service| service.module() == module.name)
.map(redup_bootstrap_grpc::ServiceInfo::running)
.sum::<u64>(),
)
.unwrap_or(i32::MAX),
details: std::sync::Arc::clone(&module.module)
.details()
.into_iter()
.collect(),
}
})
.collect();
let configs = self
.info
.configs()
.iter()
.map(|config| (config.name.clone(), config.text.clone()))
.collect();
InstanceInfo {
bootstrap: Some(BootstrapInfo {
version: env!("CARGO_PKG_VERSION").to_owned(),
build_time: Some(prost_types::Timestamp {
seconds: BUILD_TIME,
nanos: 0,
}),
up_time: Some(duration(self.info.uptime())),
}),
modules,
configs,
instance_id: self.info.instance_id().to_owned(),
incoming_load_average: Some(average(&self.info, LoadKind::Incoming)),
outgoing_load_average: Some(average(&self.info, LoadKind::Outgoing)),
work_load_average: Some(average(&self.info, LoadKind::Worker)),
}
}
}
fn average(info: &InfoSource, kind: LoadKind) -> LoadAverageInfo {
let average = info.load().average(kind);
LoadAverageInfo {
load1: average.one_minute(),
load5: average.five_minutes(),
load15: average.fifteen_minutes(),
}
}
pub(crate) struct MetricsState {
info: Arc<InfoSource>,
telemetry: Arc<Telemetry>,
}
impl MetricsState {
pub(crate) fn new(info: Arc<InfoSource>, telemetry: Arc<Telemetry>) -> Self {
Self { info, telemetry }
}
}
impl MetricsProvider for MetricsState {
fn metrics_text(&self) -> String {
self.telemetry.render(&self.info.dependency_metrics())
}
}
pub(crate) struct ControlState {
stopper: Stopper,
apoptosis: Apoptosis,
logging: Logging,
token: tokio_util::sync::CancellationToken,
}
impl ControlState {
pub(crate) fn new(
stopper: Stopper,
apoptosis: Apoptosis,
logging: Logging,
token: tokio_util::sync::CancellationToken,
) -> Self {
Self {
stopper,
apoptosis,
logging,
token,
}
}
}
impl ControlProvider for ControlState {
fn halt(&self, command: HaltCommand) -> Result<(), Status> {
if command.fail_fast && command.inflate_memory {
return Err(Status::invalid_argument(HALT_CONFLICT));
}
let reason = command
.message
.clone()
.unwrap_or_else(|| "the stop is requested by Control.Halt".to_owned());
if command.inflate_memory {
if !self.apoptosis.is_enabled() {
return Err(Status::failed_precondition(
"memory inflating is off: the control.oom section is absent",
));
}
self.apoptosis.report(reason);
return Ok(());
}
let delay = command.delay.as_ref().map(from_proto_duration);
let stopper = self.stopper.clone();
let fail_fast = command.fail_fast;
if delay.is_none_or(|delay| delay.is_zero()) {
if fail_fast {
stopper.stop_fast(reason);
} else {
stopper.stop(reason);
}
return Ok(());
}
let delay = delay.unwrap_or_default();
tokio::spawn(async move {
tokio::time::sleep(delay).await;
if fail_fast {
stopper.stop_fast(reason);
} else {
stopper.stop(reason);
}
});
Ok(())
}
fn change_logging(&self, command: ChangeGlobalLoggingCommand) -> Result<(), Status> {
if let Ok(level) = LogLevel::try_from(command.level)
&& let Some(level) = level_of(level)
{
self.logging.set_level(level);
}
if let Some(template) = command.template {
let template = match template.as_str() {
"auto" => crate::telemetry::Template::Auto,
"human" => crate::telemetry::Template::Human,
"json" => crate::telemetry::Template::Json,
"file" => {
return Err(Status::invalid_argument(
"the file template is not supported: the journal writes to stdout",
));
}
other => {
return Err(Status::invalid_argument(format!(
"the journal template '{other}' is unknown"
)));
}
};
self.logging.set_template(template);
}
Ok(())
}
fn memory(&self, request: MemoryDiagnosticsRequest) -> MemoryInfo {
if request.collect {
tracing::warn!(
"the memory collection is not supported: the platform uses the system allocator"
);
}
MemoryInfo {
working_set: memory::resident_bytes().unwrap_or(0),
gc_memory: 0,
pinned_objects_count: 0,
finalization_pending_count: 0,
pause_time_ratio: 0.0,
small_object_heap_generations: vec![0; 3],
large_object_heap: 0,
pinned_object_heap: 0,
current_collection: None,
}
}
fn logs(&self, min_level: LogLevel) -> LogStream {
let level = level_of(min_level).unwrap_or(Level::Trace);
let mut capture = self.logging.capture(level);
let token = self.token.clone();
let (sender, receiver) = tokio::sync::mpsc::channel(64);
tokio::spawn(async move {
loop {
let message = tokio::select! {
_ = token.cancelled() => return,
message = capture.next() => message,
};
let Some(message) = message else {
return;
};
let message = LogMessage {
timestamp: Some(timestamp(message.timestamp())),
level: log_level(message.level()) as i32,
message: message.message().to_owned(),
correlation_id: message.correlation_id().map(str::to_owned),
exception: message.exception().map(str::to_owned),
};
if sender.send(Ok(message)).await.is_err() {
return;
}
}
});
Box::pin(tokio_stream::wrappers::ReceiverStream::new(receiver))
}
}
fn serving(phase: Phase) -> ServingStatus {
match phase {
Phase::Serving => ServingStatus::Serving,
_ => ServingStatus::NotServing,
}
}
fn level_of(level: LogLevel) -> Option<Level> {
match level {
LogLevel::Unspecified => None,
LogLevel::Trace => Some(Level::Trace),
LogLevel::Debug => Some(Level::Debug),
LogLevel::Info => Some(Level::Info),
LogLevel::Warn => Some(Level::Warn),
LogLevel::Error => Some(Level::Error),
LogLevel::Fatal => Some(Level::Fatal),
}
}
fn log_level(level: Level) -> LogLevel {
match level {
Level::Trace => LogLevel::Trace,
Level::Debug => LogLevel::Debug,
Level::Info => LogLevel::Info,
Level::Warn => LogLevel::Warn,
Level::Error => LogLevel::Error,
Level::Fatal | Level::Off => LogLevel::Fatal,
}
}
fn duration(value: Duration) -> prost_types::Duration {
prost_types::Duration {
seconds: i64::try_from(value.as_secs()).unwrap_or(i64::MAX),
nanos: i32::try_from(value.subsec_nanos()).unwrap_or(0),
}
}
fn from_proto_duration(value: &prost_types::Duration) -> Duration {
let seconds = u64::try_from(value.seconds).unwrap_or(0);
let nanos = u32::try_from(value.nanos).unwrap_or(0);
Duration::new(seconds, nanos)
}
fn timestamp(value: time::OffsetDateTime) -> prost_types::Timestamp {
prost_types::Timestamp {
seconds: value.unix_timestamp(),
nanos: i32::try_from(value.nanosecond()).unwrap_or(0),
}
}