use crate::load_balancer;
use crate::placement;
use crossbeam_utils::sync::ShardedLock;
use fxhash::FxHashMap;
use lazy_static::*;
use std::thread;
use std::time::Duration;
#[derive(Debug)]
pub struct LoadBalancer;
impl LoadBalancer {
pub fn amql_generation() {
thread::Builder::new()
.name("bastion-load-balancer-thread".to_string())
.spawn(move || {
loop {
if let Ok(mut stats) = load_balancer::stats().try_write() {
stats.mean_level = stats
.smp_queues
.values()
.sum::<usize>()
.wrapping_div(*core_retrieval());
}
thread::sleep(Duration::from_millis(245));
thread::yield_now();
}
})
.expect("load-balancer couldn't start");
}
}
#[derive(Clone, Debug)]
pub struct Stats {
pub(crate) global_run_queue: usize,
pub(crate) mean_level: usize,
pub(crate) smp_queues: FxHashMap<usize, usize>,
}
unsafe impl Send for Stats {}
unsafe impl Sync for Stats {}
#[inline]
pub fn stats() -> &'static ShardedLock<Stats> {
lazy_static! {
static ref LB_STATS: ShardedLock<Stats> = {
let stats = Stats {
global_run_queue: 0,
mean_level: 0,
smp_queues: FxHashMap::with_capacity_and_hasher(
placement::get_core_ids().unwrap().len(),
Default::default()
)
};
LoadBalancer::amql_generation();
ShardedLock::new(stats)
};
}
&*LB_STATS
}
#[inline]
pub fn core_retrieval() -> &'static usize {
lazy_static! {
static ref CORE_COUNT: usize = { placement::get_core_ids().unwrap().len() };
}
&*CORE_COUNT
}