1use std::any::{Any, TypeId};
2use std::collections::VecDeque;
3use std::sync::{Arc, atomic::AtomicBool, atomic::AtomicUsize, atomic::Ordering};
4use std::time::{Duration, Instant};
5use std::{cell::RefCell, fmt, future::Future, panic, pin::Pin, rc::Rc};
6
7use async_channel::{Receiver, Sender, unbounded};
8use futures_timer::Delay;
9use parking_lot::{Mutex, RwLock};
10
11use crate::arbiter::Arbiter;
12use crate::pool::ThreadPool;
13use crate::{BlockingResult, Builder, Handle, HashMap, HashSet, Runner, SystemRunner};
14
15static SYSTEM_COUNT: AtomicUsize = AtomicUsize::new(0);
16
17thread_local!(
18 static PINGS: RefCell<HashMap<Id, VecDeque<PingRecord>>> =
19 RefCell::new(HashMap::default());
20);
21
22#[derive(Default)]
23struct Arbiters {
24 all: HashMap<Id, Arbiter>,
25 list: Vec<Arbiter>,
26}
27
28#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
30pub struct Id(pub(crate) usize);
31
32pub struct System(Arc<SystemInner>);
34
35struct SystemInner {
36 id: usize,
37 arbiter: Arbiter,
38 config: SystemConfig,
39 sender: Sender<SystemCommand>,
40 receiver: Receiver<SystemCommand>,
41 storage: RwLock<HashMap<TypeId, Box<dyn Any + Sync + Send>>>,
42 arbiters: Mutex<Arbiters>,
43 signals: AtomicBool,
44 pool: ThreadPool,
45}
46
47#[derive(Clone)]
48pub struct SystemConfig {
49 pub(super) name: String,
50 pub(super) stack_size: usize,
51 pub(super) stop_on_panic: bool,
52 pub(super) ping_interval: usize,
53 #[allow(dead_code)]
54 pub(super) ping_threshold: usize,
55 pub(super) pool_limit: usize,
56 pub(super) pool_recv_timeout: Duration,
57 pub(super) testing: bool,
58 pub(super) runner: Arc<dyn Runner>,
59}
60
61thread_local!(
62 static CURRENT: RefCell<Option<System>> = const { RefCell::new(None) };
63);
64
65impl Clone for System {
66 fn clone(&self) -> Self {
67 Self(self.0.clone())
68 }
69}
70
71impl System {
72 pub(super) fn start(config: SystemConfig) -> (Self, oneshot::Receiver<i32>) {
74 let id = SYSTEM_COUNT.fetch_add(1, Ordering::SeqCst);
75 let (sender, receiver) = unbounded();
76
77 let pool =
78 ThreadPool::new(&config.name, config.pool_limit, config.pool_recv_timeout);
79 let (arbiter, controller) = Arbiter::new_system(id, config.name.clone());
80
81 let mut arbiters = Arbiters::default();
82 arbiters.all.insert(arbiter.id(), arbiter.clone());
83 arbiters.list.push(arbiter.clone());
84
85 let sys = System(Arc::new(SystemInner {
86 id,
87 config,
88 arbiter,
89 sender,
90 receiver,
91 pool,
92 arbiters: Mutex::new(arbiters),
93 storage: RwLock::new(HashMap::default()),
94 signals: AtomicBool::new(false),
95 }));
96 System::set_current(sys.clone());
97
98 let (stop_tx, stop) = oneshot::channel();
99
100 crate::spawn(SystemSupport::new(&sys, stop_tx).run());
102 crate::spawn(controller.run(sys.clone()));
103
104 (sys, stop)
105 }
106
107 pub fn build() -> Builder {
112 Builder::new()
113 }
114
115 #[allow(clippy::new_ret_no_self)]
116 pub fn new<R: Runner>(name: &str, runner: R) -> SystemRunner {
120 Self::build().name(name).build(runner)
121 }
122
123 #[allow(clippy::new_ret_no_self)]
124 pub fn with_config(name: &str, config: SystemConfig) -> SystemRunner {
128 Self::build().name(name).build_with(config)
129 }
130
131 pub fn current() -> System {
137 CURRENT.with(|cell| match *cell.borrow() {
138 Some(ref sys) => sys.clone(),
139 None => panic!("System is not running"),
140 })
141 }
142
143 pub fn try_current() -> Option<System> {
145 CURRENT.with(|cell| cell.borrow().as_ref().map(Clone::clone))
146 }
147
148 #[doc(hidden)]
150 pub fn set_current(sys: System) {
151 CURRENT.with(|s| {
152 *s.borrow_mut() = Some(sys);
153 });
154 }
155
156 pub(crate) fn register_arbiter(&self, arb: Arbiter) {
157 CURRENT.with(|s| {
158 *s.borrow_mut() = Some(self.clone());
159 });
160 let mut arbiters = self.0.arbiters.lock();
161 arbiters.all.insert(arb.id(), arb.clone());
162 arbiters.list.push(arb);
163 }
164
165 pub(crate) fn unregister_arbiter(&self, id: Id) {
166 CURRENT.with(|s| {
167 *s.borrow_mut() = None;
168 });
169 let mut arbiters = self.0.arbiters.lock();
170 if let Some(hnd) = arbiters.all.remove(&id) {
171 for (idx, arb) in arbiters.list.iter().enumerate() {
172 if &hnd == arb {
173 arbiters.list.remove(idx);
174 break;
175 }
176 }
177 }
178 }
179
180 pub(super) fn remove_current() {
181 CURRENT.with(|cell| {
182 cell.borrow_mut().take();
183 });
184 }
185
186 pub fn id(&self) -> Id {
188 Id(self.0.id)
189 }
190
191 pub fn name(&self) -> &str {
193 &self.0.config.name
194 }
195
196 pub fn stop(&self) {
198 self.stop_with_code(0);
199 }
200
201 pub fn stop_with_code(&self, code: i32) {
203 let _ = self.0.sender.try_send(SystemCommand::Exit(code));
204 }
205
206 pub fn stop_on_panic(&self) -> bool {
211 self.0.config.stop_on_panic
212 }
213
214 pub fn signals(&self) -> bool {
216 self.0.signals.load(Ordering::Relaxed)
217 }
218
219 pub fn enable_signals(&self) {
221 if !self.signals() {
222 crate::signals::start(self);
223 self.0.signals.store(true, Ordering::Relaxed);
224 }
225 }
226
227 pub fn disable_signals(&self) {
229 if self.signals() {
230 crate::signals::stop(self);
231 self.0.signals.store(false, Ordering::Relaxed);
232 }
233 }
234
235 pub fn arbiter(&self) -> Arbiter {
241 self.0.arbiter.clone()
242 }
243
244 pub fn list_arbiters<F, R>(&self, f: F) -> R
249 where
250 F: FnOnce(&[Arbiter]) -> R,
251 {
252 f(&self.0.arbiters.lock().list)
253 }
254
255 pub fn list_arbiter_pings<F, R>(id: Id, f: F) -> R
260 where
261 F: FnOnce(Option<&VecDeque<PingRecord>>) -> R,
262 {
263 PINGS.with(|pings| {
264 if let Some(recs) = pings.borrow().get(&id) {
265 f(Some(recs))
266 } else {
267 f(None)
268 }
269 })
270 }
271
272 #[cfg(target_os = "linux")]
273 #[doc(hidden)]
274 pub fn set_latency_callback<F: Fn(ntex_error::Backtrace) + 'static>(f: F) {
281 unsafe {
282 ARB_CB = Some(Box::new(f));
283 }
284 }
285
286 pub fn config(&self) -> SystemConfig {
288 self.0.config.clone()
289 }
290
291 #[inline]
292 pub fn handle(&self) -> Handle {
294 self.arbiter().handle().clone()
295 }
296
297 pub fn testing(&self) -> bool {
299 self.0.config.testing()
300 }
301
302 pub fn spawn_blocking<F, R>(&self, f: F) -> BlockingResult<R>
306 where
307 F: FnOnce() -> R + Send + 'static,
308 R: Send + 'static,
309 {
310 self.0.pool.execute(f)
311 }
312
313 pub fn get_value<T>(&self, f: impl FnOnce() -> T) -> T
318 where
319 T: Clone + Send + Sync + 'static,
320 {
321 if let Some(boxed) = self.0.storage.read().get(&TypeId::of::<T>())
322 && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
323 {
324 val.clone()
325 } else {
326 let val = f();
327 self.0
328 .storage
329 .write()
330 .insert(TypeId::of::<T>(), Box::new(val.clone()));
331 val
332 }
333 }
334}
335
336impl SystemConfig {
337 #[inline]
338 pub fn testing(&self) -> bool {
340 self.testing
341 }
342}
343
344impl fmt::Debug for System {
345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346 f.debug_struct("System")
347 .field("id", &self.0.id)
348 .field("config", &self.0.config)
349 .field("signals", &self.signals())
350 .field("pool", &self.0.pool)
351 .finish()
352 }
353}
354
355impl fmt::Debug for SystemConfig {
356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357 f.debug_struct("SystemConfig")
358 .field("name", &self.name)
359 .field("testing", &self.testing)
360 .field("stack_size", &self.stack_size)
361 .field("stop_on_panic", &self.stop_on_panic)
362 .finish()
363 }
364}
365
366#[derive(Debug)]
367pub(super) enum SystemCommand {
368 Exit(i32),
369}
370
371#[derive(Debug)]
372struct SystemSupport {
373 sys: System,
374 stop: Option<oneshot::Sender<i32>>,
375 commands: Receiver<SystemCommand>,
376}
377
378impl SystemSupport {
379 fn new(sys: &System, stop: oneshot::Sender<i32>) -> Self {
380 Self {
381 sys: sys.clone(),
382 stop: Some(stop),
383 commands: sys.0.receiver.clone(),
384 }
385 }
386
387 async fn run(mut self) {
388 if self.sys.0.config.ping_interval != 0 {
389 crate::spawn(ping_arbiters(self.sys.clone()));
390 }
391
392 loop {
393 match self.commands.recv().await {
394 Ok(SystemCommand::Exit(code)) => {
395 log::debug!("Stopping system with {code} code");
396
397 let mut arbiters = self.sys.0.arbiters.lock();
399 for arb in arbiters.list.drain(..) {
400 arb.stop();
401 }
402 arbiters.all.clear();
403
404 if let Some(stop) = self.stop.take() {
406 let _ = stop.send(code);
407 }
408 }
409 Err(_) => {
410 log::debug!("System stopped");
411 return;
412 }
413 }
414 }
415 }
416}
417
418#[derive(Copy, Clone, Debug)]
419pub struct PingRecord {
420 pub start: Instant,
422 pub rtt: Option<Duration>,
424}
425
426async fn ping_arbiters(sys: System) {
427 let pings = Rc::new(RefCell::new(HashSet::default()));
428 let interval = Duration::from_millis(sys.0.config.ping_interval as u64);
429 #[cfg(target_os = "linux")]
430 let threshold = Duration::from_millis(sys.0.config.ping_threshold as u64);
431
432 loop {
433 Delay::new(interval).await;
435
436 {
438 pings.borrow_mut().clear();
439
440 let start = Instant::now();
441 let arbiters = sys.0.arbiters.lock();
442
443 for arb in &arbiters.list {
444 let id = arb.id();
445 let pings = pings.clone();
446 let fut = arb.handle().spawn(async move {
447 yield_to().await;
448 });
449
450 PINGS.with(|pings| {
452 let mut p = pings.borrow_mut();
453 let recs = p.entry(arb.id()).or_default();
454 recs.push_front(PingRecord { start, rtt: None });
455 recs.truncate(10);
456 });
457
458 crate::spawn(async move {
459 if fut.await.is_ok() {
460 pings.borrow_mut().insert(id);
461
462 PINGS.with(|pings| {
463 pings
464 .borrow_mut()
465 .get_mut(&id)
466 .unwrap()
467 .front_mut()
468 .unwrap()
469 .rtt = Some(start.elapsed());
470 });
471 }
472 });
473 }
474 }
475
476 #[cfg(target_os = "linux")]
478 {
479 const SPIN: Duration = Duration::from_micros(100);
480
481 Delay::new(threshold).await;
483
484 let mut no_pongs = Vec::new();
485 {
486 for arb in &sys.0.arbiters.lock().list {
487 let pong = pings.borrow_mut().remove(&arb.id());
488 if !pong {
489 no_pongs.push(arb.clone());
490 }
491 }
492 }
493
494 for arb in no_pongs {
495 log::error!("Arbiter {}({:?}) did not return pong", arb.name(), arb.id());
497
498 *CAPTURED.lock() = None;
500 EXPECTED_TID.store(arb.tid(), Ordering::Release);
501 unsafe {
502 libc::syscall(
503 libc::SYS_tgkill,
504 libc::getpid(),
505 arb.tid(),
506 libc::SIGUSR2,
507 );
508 }
509
510 for _ in 0..1000 {
512 Delay::new(SPIN).await;
513 if let Some(bt) = CAPTURED.lock().take() {
514 let bt = ntex_error::Backtrace::from(bt);
515 #[allow(static_mut_refs)]
516 if let Some(f) = unsafe { ARB_CB.as_ref() } {
517 f(bt);
518 } else {
519 bt.resolver().resolve();
520 log::error!(
521 "Worker does not returned pong within {interval:?} time.\n{bt:?}"
522 );
523 }
524 break;
525 }
526 }
527 }
528 }
529 }
530}
531
532async fn yield_to() {
533 use std::task::{Context, Poll};
534
535 struct Yield {
536 completed: bool,
537 }
538
539 impl Future for Yield {
540 type Output = ();
541
542 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
543 if self.completed {
544 return Poll::Ready(());
545 }
546 self.completed = true;
547 cx.waker().wake_by_ref();
548 Poll::Pending
549 }
550 }
551
552 Yield { completed: false }.await;
553}
554
555#[cfg(target_os = "linux")]
556static mut ARB_CB: Option<Box<dyn Fn(ntex_error::Backtrace)>> = None;
557
558#[cfg(target_os = "linux")]
559static EXPECTED_TID: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
560#[cfg(target_os = "linux")]
561static CAPTURED: Mutex<Option<ntex_error::BacktraceRaw>> = Mutex::new(None);
562
563#[track_caller]
564#[cfg(target_family = "unix")]
565pub(crate) fn sig_usr2() {
566 #[cfg(target_os = "linux")]
567 #[allow(clippy::cast_possible_truncation)]
568 {
569 let tid = unsafe { libc::syscall(libc::SYS_gettid) } as i32;
570 if EXPECTED_TID.load(Ordering::Acquire) == tid {
571 let bt = ntex_error::BacktraceRaw::new(panic::Location::caller());
574 *CAPTURED.lock() = Some(bt);
575 }
576 }
577}