use std::collections::VecDeque;
use std::future::Future;
use std::io::ErrorKind;
use std::iter::Iterator;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::Duration;
use std::{env, thread};
use crossbeam_channel::{bounded, Receiver, Sender};
use bastion_utils::math;
use lazy_static::lazy_static;
use lightproc::lightproc::LightProc;
use lightproc::proc_stack::ProcStack;
use lightproc::recoverable_handle::RecoverableHandle;
use crate::placement::CoreId;
use crate::{load_balancer, placement};
const DEFAULT_LOW_WATERMARK: u64 = 2;
const MANAGER_POLL_INTERVAL: u64 = 200;
const FREQUENCY_QUEUE_SIZE: usize = 10;
const EMA_COEFFICIENT: f64 = 2_f64 / (FREQUENCY_QUEUE_SIZE as f64 + 1_f64);
static FREQUENCY: AtomicU64 = AtomicU64::new(0);
static MAX_THREADS: AtomicU64 = AtomicU64::new(10_000);
struct Pool {
sender: Sender<LightProc>,
receiver: Receiver<LightProc>,
}
lazy_static! {
static ref POOL: Pool = {
for _ in 0..*low_watermark() {
thread::Builder::new()
.name("bastion-blocking-driver".to_string())
.spawn(|| {
self::affinity_pinner();
for task in &POOL.receiver {
task.run();
}
})
.expect("cannot start a thread driving blocking tasks");
}
thread::Builder::new()
.name("bastion-pool-manager".to_string())
.spawn(|| {
let poll_interval = Duration::from_millis(MANAGER_POLL_INTERVAL);
loop {
scale_pool();
thread::sleep(poll_interval);
}
})
.expect("thread pool manager cannot be started");
let (sender, receiver) = bounded(0);
Pool { sender, receiver }
};
static ref ROUND_ROBIN_PIN: Mutex<CoreId> = Mutex::new(CoreId { id: 0 });
static ref FREQ_QUEUE: Mutex<VecDeque<u64>> = {
Mutex::new(VecDeque::with_capacity(FREQUENCY_QUEUE_SIZE.saturating_add(1)))
};
static ref POOL_SIZE: Mutex<u64> = Mutex::new(*low_watermark());
}
#[inline]
fn calculate_ema(freq_queue: &VecDeque<u64>) -> f64 {
freq_queue.iter().enumerate().fold(0_f64, |acc, (i, freq)| {
acc + ((*freq as f64) * ((1_f64 - EMA_COEFFICIENT).powf(i as f64) as f64))
}) * EMA_COEFFICIENT as f64
}
fn scale_pool() {
let current_frequency = FREQUENCY.swap(0, Ordering::SeqCst);
let mut freq_queue = FREQ_QUEUE.lock().unwrap();
if freq_queue.len() == 0 {
freq_queue.push_back(0);
}
let frequency = (current_frequency as f64 / MANAGER_POLL_INTERVAL as f64) as u64;
let prev_ema_frequency = calculate_ema(&freq_queue);
freq_queue.push_back(frequency);
if freq_queue.len() == FREQUENCY_QUEUE_SIZE.saturating_add(1) {
freq_queue.pop_front();
}
let curr_ema_frequency = calculate_ema(&freq_queue);
if curr_ema_frequency > prev_ema_frequency {
let scale_by: f64 = curr_ema_frequency - prev_ema_frequency;
let scale = num_cpus::get().min(
((DEFAULT_LOW_WATERMARK as f64 * scale_by) + DEFAULT_LOW_WATERMARK as f64) as usize,
);
(0..scale).for_each(|_| {
create_blocking_thread();
});
} else if (curr_ema_frequency - prev_ema_frequency).abs() < std::f64::EPSILON
&& current_frequency != 0
{
(0..DEFAULT_LOW_WATERMARK).for_each(|_| {
create_blocking_thread();
});
}
}
fn create_blocking_thread() {
{
let pool_size = *POOL_SIZE.lock().unwrap();
if pool_size >= MAX_THREADS.load(Ordering::SeqCst) {
MAX_THREADS.store(10_000, Ordering::SeqCst);
return;
}
}
let rand_sleep_ms = 1000_u64
.checked_add(u64::from(math::random(10_000)))
.expect("shouldn't overflow");
let _ = thread::Builder::new()
.name("bastion-blocking-driver-dynamic".to_string())
.spawn(move || {
self::affinity_pinner();
let wait_limit = Duration::from_millis(rand_sleep_ms);
*POOL_SIZE.lock().unwrap() += 1;
while let Ok(task) = POOL.receiver.recv_timeout(wait_limit) {
task.run();
}
*POOL_SIZE.lock().unwrap() -= 1;
})
.map_err(|err| {
match err.kind() {
ErrorKind::WouldBlock => {
let guarded_count = POOL_SIZE
.lock()
.unwrap()
.checked_sub(1)
.expect("shouldn't underflow");
MAX_THREADS.store(guarded_count, Ordering::SeqCst);
}
_ => eprintln!(
"cannot start a dynamic thread driving blocking tasks: {}",
err
),
}
});
}
fn schedule(t: LightProc) {
FREQUENCY.fetch_add(1, Ordering::Acquire);
if let Err(err) = POOL.sender.try_send(t) {
POOL.sender.send(err.into_inner()).unwrap();
}
}
pub fn spawn_blocking<F, R>(future: F, stack: ProcStack) -> RecoverableHandle<R>
where
F: Future<Output = R> + Send + 'static,
R: Send + 'static,
{
let (task, handle) = LightProc::recoverable(future, schedule, stack);
task.schedule();
handle
}
#[inline]
pub fn low_watermark() -> &'static u64 {
lazy_static! {
static ref LOW_WATERMARK: u64 = {
env::var_os("BASTION_BLOCKING_THREADS")
.map(|x| x.to_str().unwrap().parse::<u64>().unwrap())
.unwrap_or(DEFAULT_LOW_WATERMARK)
};
}
&*LOW_WATERMARK
}
#[inline]
pub fn affinity_pinner() {
if 1 != *load_balancer::core_retrieval() {
let mut core = ROUND_ROBIN_PIN.lock().unwrap();
placement::set_for_current(*core);
core.id = (core.id + 1) % *load_balancer::core_retrieval();
}
}