Skip to content

Commit

Permalink
feat: is initialized
Browse files Browse the repository at this point in the history
  • Loading branch information
apskhem committed Jan 13, 2025
1 parent e6b1287 commit 7096faa
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions catalyst-gateway/bin/src/metrics/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
use std::{
alloc::System,
sync::{Arc, Mutex},
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
thread,
time::Duration,
};
Expand All @@ -16,6 +19,9 @@ lazy_static::lazy_static! {
static ref GLOBAL_METRICS: Arc<Mutex<MemoryMetrics>> = Arc::new(Mutex::new(MemoryMetrics::default()));
}

/// This is to prevent the init function from accidentially being called multiple times.
static IS_INITIALIZED: AtomicBool = AtomicBool::new(false);

/// Interval for updating memory metrics, in milliseconds.
const UPDATE_INTERVAL_MILLI: u64 = 1000;

Expand Down Expand Up @@ -57,16 +63,31 @@ impl MemoryMetrics {
///
/// # Returns
/// * A clone of the `MemoryMetrics` structure containing the latest metrics.
pub(crate) fn retrieve_metrics() -> Self {
let metrics = GLOBAL_METRICS.lock().unwrap();
metrics.clone()
#[allow(dead_code)]
pub(crate) fn retrieve_metrics() -> Result<Self, String> {
match GLOBAL_METRICS.lock() {
Ok(metrics) => Ok(metrics.clone()),
Err(err) => {
let msg = format!("Failed to retrieve memory usage info: {err:?}");

error!("{err:?}");

Err(msg)
},
}
}

/// Starts a background thread to periodically update memory metrics.
///
/// This function spawns a thread that updates the global `MemoryMetrics`
/// structure at regular intervals defined by `UPDATE_INTERVAL_MILLI`.
pub(crate) fn start_metrics_updater() {
if IS_INITIALIZED.load(Ordering::SeqCst) {
return;
}

IS_INITIALIZED.store(true, Ordering::SeqCst);

let stats = Region::new(GLOBAL);

thread::spawn(move || {
Expand Down

0 comments on commit 7096faa

Please sign in to comment.