Skip to main content

kumo_server_common/
start.rs

1use 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            // This log line is depended upon by the integration
78            // test harness. Do not change or remove it without
79            // making appropriate adjustments over there!
80            tracing::info!("initialization complete");
81            error
82        })?;
83
84        let final_result = life_cycle.wait_for_shutdown().await;
85
86        // after waiting for those to idle out, shut down logging
87        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! {
103/// The sum of the system-wide CPU usage for each CPU in the system, can add up to more than 100%.
104///
105/// Each CPU has a value from 0-100% busy; a value of 100% in this metric
106/// indicates that the load is equivalent to one fully utilized CPU.
107///
108/// A multi-CPU system can report more than 100% in this metric; a dual-CPU
109/// system reporting 200% indicates that both CPUs are fully utilized.
110///
111/// See system_cpu_usage_normalized for a version of this metric that scales from
112/// 0% (totally idle) to 100% (totally saturated).
113///
114/// This metric is scoped to the system, reflecting the total load on the
115/// system, not just from the kumo related process(es).
116static SYS_CPU_USAGE: IntGauge("system_cpu_usage_sum");
117}
118
119declare_metric! {
120/// The sum of the system-wide CPU usage for each CPU in the system, divided by the number of CPUs.
121///
122/// 100% in this metric indicates that all CPU cores are 100% busy.
123///
124/// This metric is scoped to the system, reflecting the total load on the
125/// system, not just from the kumo related process(es).
126static SYS_CPU_USAGE_NORM: IntGauge("system_cpu_usage_normalized");
127}
128
129declare_metric! {
130/// The sum of the process CPU usage for each CPU in the system, can add up to more than 100%.
131///
132/// Each CPU has a value from 0-100% busy; a value of 100% in this metric
133/// indicates that the load is equivalent to one fully utilized CPU.
134///
135/// A multi-CPU system can report more than 100% in this metric; a dual-CPU
136/// system reporting 200% indicates that both CPUs are fully utilized.
137///
138/// See process_cpu_usage_normalized for a version of this metric that scales from
139/// 0% (totally idle) to 100% (totally saturated).
140///
141/// This metric is scoped to the service process, reflecting the CPU used only
142/// by the process and not the system as a whole.
143static PROC_CPU_USAGE: IntGauge("process_cpu_usage_sum");
144}
145
146declare_metric! {
147/// The sum of the process CPU usage for each CPU in the system, divided by the number of CPUs.
148///
149/// 100% in this metric indicates that all CPU cores are 100% busy.
150///
151/// This metric is scoped to the service process, reflecting the CPU used only
152/// by the process and not the system as a whole.
153static 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        // Do two initial updates so that we have sufficient data for
172        // computing a delta; one here outside the loop, and another
173        // at the top of the loop.
174        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}