crates/edge/server/src/stop.rs 6.1 KiB 191 lines Raw
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.9 10 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};11 use std::sync::{Arc, Condvar, Mutex};12 use std::time::{Duration, Instant};13 14 /// The pause between two reads of the stop flag. The loop accepts15 /// without blocking, so this is the longest that a new connection waits.16 const ACCEPT_PAUSE: Duration = Duration::from_millis(5);17 18 /// 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.21 const DRAIN: Duration = Duration::from_secs(30);22 23 /// The connection count and the condition that reports it reaching zero.24 #[derive(Default)]25 struct Live {26     count: Mutex<usize>,27     zero: Condvar,28 }29 30 impl Live {31     fn enter(self: &Arc<Self>) -> Active {32         *self.count.lock().expect("the count lock") += 1;33         Active {34             live: Arc::clone(self),35         }36     }37 38     fn leave(&self) {39         let mut count = self.count.lock().expect("the count lock");40         *count = count.saturating_sub(1);41         if *count == 0 {42             self.zero.notify_all();43         }44     }45 46     fn wait(&self, budget: Duration) -> usize {47         let deadline = Instant::now() + budget;48         let mut count = self.count.lock().expect("the count lock");49         while *count > 0 {50             let left = deadline.saturating_duration_since(Instant::now());51             if left.is_zero() {52                 break;53             }54             let (next, timeout) = self.zero.wait_timeout(count, left).expect("the count lock");55             count = next;56             if timeout.timed_out() {57                 break;58             }59         }60         *count61     }62 }63 64 /// One running connection. Dropping it is the signal that the connection is65 /// done, which is the only way the count can go down.66 pub struct Active {67     live: Arc<Live>,68 }69 70 impl Drop for Active {71     fn drop(&mut self) {72         self.live.leave();73     }74 }75 76 /// 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)]80 struct Connections {81     count: AtomicUsize,82 }83 84 /// One place in the concurrent-connection cap. Dropping it returns the place.85 pub(crate) struct ConnectionSlot {86     connections: Arc<Connections>,87 }88 89 impl Drop for ConnectionSlot {90     fn drop(&mut self) {91         self.connections.count.fetch_sub(1, Ordering::AcqRel);92     }93 }94 95 /// 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)]98 pub struct Stop {99     flag: Arc<AtomicBool>,100     live: Arc<Live>,101     signals: Arc<AtomicUsize>,102     connections: Arc<Connections>,103 }104 105 impl Stop {106     /// A stop that no signal reaches. Tests and supervisors set it themselves.107     pub fn new() -> Stop {108         Stop::default()109     }110 111     /// 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.116     pub fn install(&self) -> std::io::Result<()> {117         let stop = self.clone();118         let mut signals = signal_hook::iterator::Signals::new([119             signal_hook::consts::SIGTERM,120             signal_hook::consts::SIGINT,121         ])?;122         std::thread::spawn(move || {123             for _ in signals.forever() {124                 if 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         });133         Ok(())134     }135 136     /// 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.138     pub(crate) fn enter_connection(&self, max: usize) -> Option<ConnectionSlot> {139         let mut count = self.connections.count.load(Ordering::Relaxed);140         loop {141             if count >= max {142                 return None;143             }144             match self.connections.count.compare_exchange_weak(145                 count,146                 count + 1,147                 Ordering::AcqRel,148                 Ordering::Relaxed,149             ) {150                 Ok(_) => {151                     return Some(ConnectionSlot {152                         connections: Arc::clone(&self.connections),153                     });154                 }155                 Err(now) => count = now,156             }157         }158     }159 160     /// Asks the accept loop to stop. The connections that are running finish.161     pub fn request(&self) {162         self.flag.store(true, Ordering::SeqCst);163     }164 165     /// Whether the loop has been asked to stop.166     pub fn stopping(&self) -> bool {167         self.flag.load(Ordering::SeqCst)168     }169 170     /// Counts one connection for as long as the returned value lives.171     pub fn enter(&self) -> Active {172         self.live.enter()173     }174 175     /// Waits for the running connections, and returns the ones that remain176     /// when the budget passes.177     pub fn wait(&self) -> usize {178         self.wait_for(DRAIN)179     }180 181     /// 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.183     pub fn wait_for(&self, budget: Duration) -> usize {184         self.live.wait(budget)185     }186 187     /// The pause that the accept loop makes between two reads of the flag.188     pub fn pause() -> Duration {189         ACCEPT_PAUSE190     }191 }