kumo_server_common/
start.rs1use crate::diagnostic_logging::LoggingConfig;
2use crate::nodeid::NodeId;
3use anyhow::Context;
4use chrono::Utc;
5use config::RegisterFunc;
6use kumo_chrono_helper::DateTime;
7use kumo_machine_info::MachineInfo;
8use kumo_prometheus::declare_metric;
9use kumo_server_lifecycle::LifeCycle;
10use kumo_server_runtime::rt_spawn;
11use parking_lot::Mutex;
12use std::future::Future;
13use std::path::Path;
14use std::sync::LazyLock;
15
16pub static ONLINE_SINCE: LazyLock<DateTime<Utc>> = LazyLock::new(DateTime::now);
17pub static MACHINE_INFO: LazyLock<Mutex<Option<MachineInfo>>> = LazyLock::new(|| Mutex::new(None));
18
19pub struct StartConfig<'a> {
20 pub logging: LoggingConfig<'a>,
21 pub lua_funcs: &'a [RegisterFunc],
22 pub policy: &'a Path,
23}
24
25impl StartConfig<'_> {
26 pub async fn run<INIT, FINI>(
27 self,
28 init_future: INIT,
29 shutdown_future: FINI,
30 ) -> anyhow::Result<()>
31 where
32 INIT: Future<Output = anyhow::Result<()>> + Send + 'static,
33 FINI: Future<Output = ()> + Send + 'static,
34 {
35 LazyLock::force(&ONLINE_SINCE);
36 self.logging.init()?;
37
38 start_cpu_usage_monitor();
39 crate::log_backlog::start_monitor();
40
41 rustls::crypto::aws_lc_rs::default_provider()
42 .install_default()
43 .map_err(|_| anyhow::anyhow!("failed to install default crypto provider"))?;
44
45 kumo_server_memory::setup_memory_limit().context("setup_memory_limit")?;
46
47 prometheus::register(Box::new(
48 tokio_metrics_collector::default_runtime_collector(),
49 ))
50 .context("failed to configure tokio-metrics-collector")?;
51
52 for &func in self.lua_funcs {
53 config::register(func);
54 }
55
56 config::set_policy_path(self.policy.to_path_buf())
57 .await
58 .with_context(|| format!("Error evaluating policy file {:?}", self.policy))?;
59
60 tokio::spawn(async move {
61 let mut info = MachineInfo::new();
62 info.node_id.replace(NodeId::get().uuid.to_string());
63 info.query_cloud_provider().await;
64 *MACHINE_INFO.lock() = Some(info);
65 });
66
67 let mut life_cycle = LifeCycle::new();
68
69 let init_handle = rt_spawn("initialize", async move {
70 let mut error = None;
71 if let Err(err) = init_future.await {
72 let err = format!("{err:#}");
73 tracing::error!("problem initializing: {err}");
74 LifeCycle::request_shutdown(Ok(())).await;
75 error.replace(err);
76 }
77 tracing::info!("initialization complete");
81 error
82 })?;
83
84 let final_result = life_cycle.wait_for_shutdown().await;
85
86 shutdown_future.await;
88 crate::acct::shutdown().await;
89
90 tracing::info!("Shutdown completed OK!");
91
92 if let Some(error) = init_handle.await? {
93 anyhow::bail!("Initialization raised an error: {error}");
94 }
95 if let Some(Err(error)) = final_result {
96 anyhow::bail!("Shutdown due to error: {error}");
97 }
98 Ok(())
99 }
100}
101
102declare_metric! {
103static SYS_CPU_USAGE: IntGauge("system_cpu_usage_sum");
117}
118
119declare_metric! {
120static SYS_CPU_USAGE_NORM: IntGauge("system_cpu_usage_normalized");
127}
128
129declare_metric! {
130static PROC_CPU_USAGE: IntGauge("process_cpu_usage_sum");
144}
145
146declare_metric! {
147static PROC_CPU_USAGE_NORM: IntGauge("process_cpu_usage_normalized");
154}
155
156fn start_cpu_usage_monitor() {
157 std::thread::spawn(|| {
158 use std::time::Duration;
159 use sysinfo::{
160 get_current_pid, CpuRefreshKind, ProcessRefreshKind, ProcessesToUpdate, RefreshKind,
161 System,
162 };
163
164 let mut sys = System::new_with_specifics(
165 RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()),
166 );
167
168 let my_pid = get_current_pid().expect("failed to get own pid!?");
169
170 let update_interval = Duration::from_secs(3).max(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
171 sys.refresh_cpu_usage();
175 std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
176
177 loop {
178 sys.refresh_cpu_usage();
179 sys.refresh_processes_specifics(
180 ProcessesToUpdate::Some(&[my_pid]),
181 true,
182 ProcessRefreshKind::everything().without_tasks(),
183 );
184
185 let num_cpus = sys.cpus().len() as i64;
186
187 let sys_usage = sys.cpus().iter().map(|cpu| cpu.cpu_usage()).sum::<f32>() as i64;
188 SYS_CPU_USAGE.set(sys_usage);
189 SYS_CPU_USAGE_NORM.set(sys_usage / num_cpus);
190
191 if let Some(p) = sys.process(my_pid) {
192 let proc_usage = p.cpu_usage() as i64;
193 PROC_CPU_USAGE.set(proc_usage);
194 PROC_CPU_USAGE_NORM.set(proc_usage / num_cpus);
195 }
196
197 std::thread::sleep(update_interval);
198 }
199 });
200}