1//! Stopping the accept loop, and waiting for the connections that are still2//! being served.3//!4//! `std` cannot install a signal handler without `unsafe`, so the handler comes5//! from one exactly-pinned dependency whose unsafe stays inside it. The handler6//! sets a flag; the accept loop reads the flag; the connections that are7//! already running finish on their own. A second signal is the operator saying8//! that the wait is over, and the process leaves without draining.910use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};11use std::sync::{Arc, Condvar, Mutex};12use std::time::{Duration, Instant};1314/// The pause between two reads of the stop flag. The loop accepts15/// without blocking, so this is the longest that a new connection waits.16constACCEPT_PAUSE: Duration = Duration::from_millis(5);1718/// How long the loop waits for running connections after the flag is set. A19/// job may finish inside its own budget; this bounds only the wait for the20/// accept loop to return.21constDRAIN: Duration = Duration::from_secs(30);2223/// The connection count and the condition that reports it reaching zero.24 #[derive(Default)]25structLive {26 count: Mutex<usize>,27 zero: Condvar,28 }2930implLive {31fnenter(self: &Arc<Self>) -> Active {32 *self.count.lock().expect("the count lock") += 1;33Active {34 live: Arc::clone(self),35 }36 }3738fnleave(&self) {39letmut count = self.count.lock().expect("the count lock");40 *count = count.saturating_sub(1);41if *count == 0 {42self.zero.notify_all();43 }44 }4546fnwait(&self, budget: Duration) -> usize {47let deadline = Instant::now() + budget;48letmut count = self.count.lock().expect("the count lock");49while *count > 0 {50let left = deadline.saturating_duration_since(Instant::now());51if left.is_zero() {52break;53 }54let (next, timeout) = self.zero.wait_timeout(count, left).expect("the count lock");55 count = next;56if timeout.timed_out() {57break;58 }59 }60 *count61 }62 }6364/// One running connection. Dropping it is the signal that the connection is65/// done, which is the only way the count can go down.66pubstructActive {67 live: Arc<Live>,68 }6970implDropforActive {71fndrop(&mutself) {72self.live.leave();73 }74 }7576/// The count of accepted connections, shared by every listener that uses one77/// `Stop`. The web passes the same stop to its Unix and TCP loops, so the cap78/// is one ceiling for the process, not one per listener.79 #[derive(Default)]80structConnections {81 count: AtomicUsize,82 }8384/// One place in the concurrent-connection cap. Dropping it returns the place.85pub(crate) structConnectionSlot {86 connections: Arc<Connections>,87 }8889implDropforConnectionSlot {90fndrop(&mutself) {91self.connections.count.fetch_sub(1, Ordering::AcqRel);92 }93 }9495/// The flag that ends the accept loop, the count of what is still running, and96/// the connection cap that every listener holding this stop shares.97 #[derive(Clone, Default)]98pubstructStop {99 flag: Arc<AtomicBool>,100 live: Arc<Live>,101 signals: Arc<AtomicUsize>,102 connections: Arc<Connections>,103 }104105implStop {106/// A stop that no signal reaches. Tests and supervisors set it themselves.107pubfnnew() -> Stop {108Stop::default()109 }110111/// Installs the handlers for `SIGTERM` and `SIGINT`.112///113/// The first signal asks for a drain; the second one leaves at once. The114/// thread lives for the process, because the handlers are process-wide and115/// a second signal must still be heard while the first is draining.116pubfninstall(&self) -> std::io::Result<()> {117let stop = self.clone();118letmut signals = signal_hook::iterator::Signals::new([119 signal_hook::consts::SIGTERM,120 signal_hook::consts::SIGINT,121 ])?;122 std::thread::spawn(move || {123for _ in signals.forever() {124if stop.signals.fetch_add(1, Ordering::SeqCst) == 0 {125 stop.request();126 } else {127// The operator has said twice. Draining is best effort and128// the second word is the end of the effort.129 std::process::exit(1);130 }131 }132 });133Ok(())134 }135136/// Takes a place in the connection cap, or `None` when the limit is full.137/// The count is shared by every loop that holds this stop.138pub(crate) fnenter_connection(&self, max: usize) -> Option<ConnectionSlot> {139letmut count = self.connections.count.load(Ordering::Relaxed);140loop {141if count >= max {142returnNone;143 }144matchself.connections.count.compare_exchange_weak(145 count,146 count + 1,147Ordering::AcqRel,148Ordering::Relaxed,149 ) {150Ok(_) => {151returnSome(ConnectionSlot {152 connections: Arc::clone(&self.connections),153 });154 }155Err(now) => count = now,156 }157 }158 }159160/// Asks the accept loop to stop. The connections that are running finish.161pubfnrequest(&self) {162self.flag.store(true, Ordering::SeqCst);163 }164165/// Whether the loop has been asked to stop.166pubfnstopping(&self) -> bool {167self.flag.load(Ordering::SeqCst)168 }169170/// Counts one connection for as long as the returned value lives.171pubfnenter(&self) -> Active {172self.live.enter()173 }174175/// Waits for the running connections, and returns the ones that remain176/// when the budget passes.177pubfnwait(&self) -> usize {178self.wait_for(DRAIN)179 }180181/// The same wait with a budget of the caller's choosing. A test that has182/// one connection does not need the drain budget to prove the count.183pubfnwait_for(&self, budget: Duration) -> usize {184self.live.wait(budget)185 }186187/// The pause that the accept loop makes between two reads of the flag.188pubfnpause() -> Duration {189ACCEPT_PAUSE190 }191 }