bastion_executor/
pool.rs

1//!
2//! Pool of threads to run lightweight processes
3//!
4//! We spawn futures onto the pool with [`spawn`] method of global run queue or
5//! with corresponding [`Worker`]'s spawn method.
6//!
7//! [`spawn`]: crate::pool::spawn
8//! [`Worker`]: crate::run_queue::Worker
9
10use crate::thread_manager::{DynamicPoolManager, DynamicRunner};
11use crate::worker;
12use crossbeam_channel::{unbounded, Receiver, Sender};
13use lazy_static::lazy_static;
14use lightproc::lightproc::LightProc;
15use lightproc::proc_stack::ProcStack;
16use lightproc::recoverable_handle::RecoverableHandle;
17use once_cell::sync::{Lazy, OnceCell};
18use std::future::Future;
19use std::iter::Iterator;
20use std::sync::Arc;
21use std::time::Duration;
22use std::{env, thread};
23use tracing::trace;
24
25///
26/// Spawn a process (which contains future + process stack) onto the executor from the global level.
27///
28/// # Example
29/// ```rust
30/// use bastion_executor::prelude::*;
31/// use lightproc::prelude::*;
32///
33/// # #[cfg(feature = "tokio-runtime")]
34/// # #[tokio::main]
35/// # async fn main() {
36/// #    start();    
37/// # }
38/// #
39/// # #[cfg(not(feature = "tokio-runtime"))]
40/// # fn main() {
41/// #    start();    
42/// # }
43/// #
44/// # fn start() {
45/// let pid = 1;
46/// let stack = ProcStack::default().with_pid(pid);
47///
48/// let handle = spawn(
49///     async {
50///         panic!("test");
51///     },
52///     stack.clone(),
53/// );
54///
55/// run(
56///     async {
57///         handle.await;
58///     },
59///     stack.clone(),
60/// );
61/// # }
62/// ```
63pub fn spawn<F, T>(future: F, stack: ProcStack) -> RecoverableHandle<T>
64where
65    F: Future<Output = T> + Send + 'static,
66    T: Send + 'static,
67{
68    let (task, handle) = LightProc::recoverable(future, worker::schedule, stack);
69    task.schedule();
70    handle
71}
72
73/// Spawns a blocking task.
74///
75/// The task will be spawned onto a thread pool specifically dedicated to blocking tasks.
76pub fn spawn_blocking<F, R>(future: F, stack: ProcStack) -> RecoverableHandle<R>
77where
78    F: Future<Output = R> + Send + 'static,
79    R: Send + 'static,
80{
81    let (task, handle) = LightProc::recoverable(future, schedule, stack);
82    task.schedule();
83    handle
84}
85
86///
87/// Acquire the static Pool reference
88#[inline]
89pub fn get() -> &'static Pool {
90    &*POOL
91}
92
93impl Pool {
94    ///
95    /// Spawn a process (which contains future + process stack) onto the executor via [Pool] interface.
96    pub fn spawn<F, T>(&self, future: F, stack: ProcStack) -> RecoverableHandle<T>
97    where
98        F: Future<Output = T> + Send + 'static,
99        T: Send + 'static,
100    {
101        // Log this `spawn` operation.
102        let _child_id = stack.get_pid() as u64;
103        let _parent_id = worker::get_proc_stack(|t| t.get_pid() as u64).unwrap_or(0);
104
105        let (task, handle) = LightProc::recoverable(future, worker::schedule, stack);
106        task.schedule();
107        handle
108    }
109}
110
111/// Enqueues work, attempting to send to the thread pool in a
112/// nonblocking way and spinning up needed amount of threads
113/// based on the previous statistics without relying on
114/// if there is not a thread ready to accept the work or not.
115pub(crate) fn schedule(t: LightProc) {
116    if let Err(err) = POOL.sender.try_send(t) {
117        // We were not able to send to the channel without
118        // blocking.
119        POOL.sender.send(err.into_inner()).unwrap();
120    }
121    // Add up for every incoming scheduled task
122    DYNAMIC_POOL_MANAGER.get().unwrap().increment_frequency();
123}
124
125///
126/// Low watermark value, defines the bare minimum of the pool.
127/// Spawns initial thread set.
128/// Can be configurable with env var `BASTION_BLOCKING_THREADS` at runtime.
129#[inline]
130fn low_watermark() -> &'static u64 {
131    lazy_static! {
132        static ref LOW_WATERMARK: u64 = {
133            env::var_os("BASTION_BLOCKING_THREADS")
134                .map(|x| x.to_str().unwrap().parse::<u64>().unwrap())
135                .unwrap_or(DEFAULT_LOW_WATERMARK)
136        };
137    }
138
139    &*LOW_WATERMARK
140}
141
142/// If low watermark isn't configured this is the default scaler value.
143/// This value is used for the heuristics of the scaler
144const DEFAULT_LOW_WATERMARK: u64 = 2;
145
146/// Pool interface between the scheduler and thread pool
147#[derive(Debug)]
148pub struct Pool {
149    sender: Sender<LightProc>,
150    receiver: Receiver<LightProc>,
151}
152
153struct AsyncRunner {
154    // We keep a handle to the tokio runtime here to make sure
155    // it will never be dropped while the DynamicPoolManager is alive,
156    // In case we need to spin up some threads.
157    #[cfg(feature = "tokio-runtime")]
158    runtime_handle: tokio::runtime::Handle,
159}
160
161impl DynamicRunner for AsyncRunner {
162    fn run_static(&self, park_timeout: Duration) -> ! {
163        loop {
164            for task in &POOL.receiver {
165                trace!("static: running task");
166                self.run(task);
167            }
168
169            trace!("static: empty queue, parking with timeout");
170            thread::park_timeout(park_timeout);
171        }
172    }
173    fn run_dynamic(&self, parker: &dyn Fn()) -> ! {
174        loop {
175            while let Ok(task) = POOL.receiver.try_recv() {
176                trace!("dynamic thread: running task");
177                self.run(task);
178            }
179            trace!(
180                "dynamic thread: parking - {:?}",
181                std::thread::current().id()
182            );
183            parker();
184        }
185    }
186    fn run_standalone(&self) {
187        while let Ok(task) = POOL.receiver.try_recv() {
188            self.run(task);
189        }
190        trace!("standalone thread: quitting.");
191    }
192}
193
194impl AsyncRunner {
195    fn run(&self, task: LightProc) {
196        #[cfg(feature = "tokio-runtime")]
197        {
198            self.runtime_handle.spawn_blocking(|| task.run());
199        }
200        #[cfg(not(feature = "tokio-runtime"))]
201        {
202            task.run();
203        }
204    }
205}
206
207static DYNAMIC_POOL_MANAGER: OnceCell<DynamicPoolManager> = OnceCell::new();
208
209static POOL: Lazy<Pool> = Lazy::new(|| {
210    #[cfg(feature = "tokio-runtime")]
211    {
212        let runner = Arc::new(AsyncRunner {
213            // We use current() here instead of try_current()
214            // because we want bastion to crash as soon as possible
215            // if there is no available runtime.
216            runtime_handle: tokio::runtime::Handle::current(),
217        });
218
219        DYNAMIC_POOL_MANAGER
220            .set(DynamicPoolManager::new(*low_watermark() as usize, runner))
221            .expect("couldn't create dynamic pool manager");
222    }
223    #[cfg(not(feature = "tokio-runtime"))]
224    {
225        let runner = Arc::new(AsyncRunner {});
226
227        DYNAMIC_POOL_MANAGER
228            .set(DynamicPoolManager::new(*low_watermark() as usize, runner))
229            .expect("couldn't create dynamic pool manager");
230    }
231
232    DYNAMIC_POOL_MANAGER
233        .get()
234        .expect("couldn't get static pool manager")
235        .initialize();
236
237    let (sender, receiver) = unbounded();
238    Pool { sender, receiver }
239});