use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use tokio::sync::watch;
use redup_abstractions::{Health, Phase};
use crate::config_record::ConfigRecord;
use crate::dependency::DependencyHandle;
use crate::entry::Entry;
use crate::instance::State;
use crate::memory;
use crate::snapshot::{ModuleSnapshot, Snapshot};
use crate::telemetry::load::Load;
use crate::telemetry::metrics::platform::DependencyMetric;
use crate::telemetry::pages;
use crate::telemetry::service::Service;
pub(crate) struct InfoSource {
service: Service,
instance_id: String,
entries: Arc<[Entry]>,
dependencies: Arc<[Vec<DependencyHandle>]>,
configs: Arc<[ConfigRecord]>,
load: Load,
state: Arc<Mutex<State>>,
started: Arc<Mutex<Option<Instant>>>,
notifier: watch::Sender<u64>,
}
impl InfoSource {
pub(crate) fn new(
service: Service,
entries: Vec<Entry>,
dependencies: Vec<Vec<DependencyHandle>>,
configs: Vec<ConfigRecord>,
load: Load,
) -> Self {
Self {
service,
instance_id: uuid::Uuid::new_v4().to_string(),
entries: entries.into(),
dependencies: dependencies.into(),
configs: configs.into(),
load,
state: Arc::new(Mutex::new(State::Built)),
started: Arc::new(Mutex::new(None)),
notifier: watch::channel(0).0,
}
}
pub(crate) fn service(&self) -> &Service {
&self.service
}
pub(crate) fn modules(&self) -> &[Entry] {
&self.entries
}
pub(crate) fn state(&self) -> State {
locked(&self.state, |state| *state)
}
pub(crate) fn set_state(&self, state: State) {
locked(&self.state, |current| *current = state);
self.notify();
}
pub(crate) fn notify(&self) {
self.notifier.send_modify(|generation| *generation += 1);
}
pub(crate) fn subscribe(&self) -> watch::Receiver<u64> {
self.notifier.subscribe()
}
pub(crate) fn instance_id(&self) -> &str {
&self.instance_id
}
pub(crate) fn configs(&self) -> &[ConfigRecord] {
&self.configs
}
pub(crate) fn load(&self) -> Load {
self.load.clone()
}
pub(crate) fn mark_started(&self) {
locked(&self.started, |started| *started = Some(Instant::now()));
}
pub(crate) fn snapshot(&self) -> Snapshot {
let state = self.state();
let modules: Vec<ModuleSnapshot> = self
.entries
.iter()
.map(|entry| ModuleSnapshot::new(entry.name, module_phase(entry.health.as_ref())))
.collect();
let readiness = if state == State::Running {
Phase::worst(modules.iter().map(ModuleSnapshot::phase))
} else {
Phase::NotServing
};
let liveness = if modules.iter().any(|module| module.phase() == Phase::Failed) {
Phase::Failed
} else {
Phase::Serving
};
Snapshot::new(readiness, liveness, modules)
}
pub(crate) fn dependency_metrics(&self) -> Vec<DependencyMetric<'_>> {
self.entries
.iter()
.zip(self.dependencies.iter())
.flat_map(|(entry, handles)| {
handles.iter().map(move |handle| DependencyMetric {
module: entry.name,
name: handle.name.as_str(),
info: handle.info(),
})
})
.collect()
}
pub(crate) fn info(&self) -> pages::Info {
use crate::telemetry::load::LoadKind;
let snapshot = self.snapshot();
let average = |kind| {
let average = self.load.average(kind);
pages::Load {
one_minute: average.one_minute(),
five_minutes: average.five_minutes(),
fifteen_minutes: average.fifteen_minutes(),
}
};
let modules = self
.entries
.iter()
.zip(self.dependencies.iter())
.map(|(entry, handles)| pages::Module {
name: entry.name.to_owned(),
phase: module_phase(entry.health.as_ref()),
problems: entry
.health
.as_ref()
.map(|health| {
health
.snapshot()
.problems()
.iter()
.map(|problem| {
(problem.source().to_owned(), problem.message().to_owned())
})
.collect()
})
.unwrap_or_default(),
dependencies: handles
.iter()
.map(|handle| (handle.name.clone(), handle.info()))
.collect(),
details: entry.module.clone().details(),
config: entry.config.clone(),
})
.collect();
let configs = self
.configs
.iter()
.map(|config| pages::Config {
name: config.name.clone(),
text: config.text.clone(),
warnings: config.warnings.clone(),
})
.collect();
pages::Info {
service: pages::Service {
name: self.service.name().to_owned(),
version: self.service.version().to_owned(),
},
platform_version: env!("CARGO_PKG_VERSION").to_owned(),
hostname: crate::telemetry::service::hostname(),
instance_id: self.instance_id.clone(),
uptime: self.uptime(),
state: format!("{:?}", self.state()),
readiness: snapshot.readiness(),
liveness: snapshot.liveness(),
load: [
average(LoadKind::Incoming),
average(LoadKind::Outgoing),
average(LoadKind::Worker),
],
memory: pages::Memory {
resident_bytes: memory::resident_bytes(),
container_limit_bytes: memory::container_limit(),
},
cpus: std::thread::available_parallelism().map_or(0, usize::from),
modules,
configs,
}
}
pub(crate) fn uptime(&self) -> Duration {
locked(&self.started, |started| {
started.map_or(Duration::ZERO, |started| started.elapsed())
})
}
}
pub(crate) fn module_phase(health: Option<&Health>) -> Phase {
health.map_or(Phase::Serving, |health| health.snapshot().phase())
}
fn locked<T, R>(mutex: &Mutex<T>, read: impl FnOnce(&mut T) -> R) -> R {
let mut guard: MutexGuard<'_, T> = mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
read(&mut guard)
}