tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

1012 lignes · 40492 octetsBrut · Historique
1//! Distribution's transport (ADR 0072, *Transport*): the `louise-dist`
2//! thread, which keeps one mutual-TLS connection per peer node and carries
3//! frames over it. Payloads are opaque here: the codec encodes a message
4//! frame before [`Transport::send`], and an [`Inbound`] handler decodes
5//! what arrives. The bytes on the connection are specified in
6//! `docs/wire-format.md`, *Handshake*.
7//!
8//! - **Only when started.** Nothing here is reachable from a program that
9//! does not start distribution: [`start_program`] is its only entry
10//! from the runtime, and the scheduler reaches [`stop_program`] only
11//! through the pointer it registers (`dist::shutdown`), so
12//! `--gc-sections` drops the transport and rustls otherwise.
13//! - **Its own thread and poll**, as the signals thread (ADR 0060):
14//! heartbeats never wait for the schedulers, so a busy node is not taken
15//! for a dead one. Senders queue frames and wake it ([`mio::Waker`]).
16//! Nor do they wait for the handler: what arrives goes to it on a second
17//! thread, in order (`relay`), whose backlog per peer pauses reading that
18//! peer's connection.
19//! - **mTLS both ways, no plaintext path.** Every connection presents and
20//! requires a certificate from the cluster's authorities (no default
21//! roots), TLS 1.3 only, ALPN `louise-dist`. A node name is a DNS name
22//! checked against the peer's certificate (`tls::has_name`) on both
23//! sides; the dialing side also has rustls check it as the server name.
24//! - **The handshake** then exchanges the protocol version, capability
25//! flags, the cluster, the node name, its incarnation and the schema
26//! hash, which must match ([`Reason`] says why one is refused).
27//! - **A capability flag per op family** added since stage 1
28//! ([`frame::needs`]): every node sets those it implements, and a
29//! signal frame of such an op is queued only for a peer whose hello set
30//! its flag ([`SendError::Unsupported`]), so an older runtime is never
31//! sent one. [`Transport::lacks`] lets a sender ask first.
32//! - **At most `max_peers` peers**, connections past their hello: past
33//! that, a node that is neither a seed nor [`Transport::connect`]ed is
34//! refused ([`Reason::Full`]). Seeds count, and are never refused.
35//! - **Full-mesh discovery, opt-in** (`mesh`): peers that both set
36//! [`frame::FLAG_PEERS`] send each other their lists of nodes up, with
37//! the addresses to dial them at, and dial the nodes they did not know
38//! (*discovered*). An address is a hint: TLS checks the dialed name, so
39//! a lying peer only wastes dials, each lister's address being tried in
40//! turn. A discovered node is dialed again while a peer lists it, and
41//! forgotten once none has for `node_down_after_ms` ×
42//! [`thread::FORGET_AFTER`]; at most `max_peers` are known, shared among
43//! the peers that list them (`thread`, *Discovery*).
44//! - **One connection per peer, one ordered stream.** Simultaneous dials
45//! resolve to the connection the smaller node name initiated; a new
46//! incarnation of a connected node replaces it (the old one is down).
47//! Messages and signals leave in the order they were sent. Heartbeats
48//! and their echoes are a control lane: written between the stream's
49//! frames, ahead of what is queued, so a long queue delays neither the
50//! peer's liveness nor the round-trip time measured from them.
51//! - **Back-pressure.** A peer's queue holds `max_queue` bytes of messages
52//! and spawn requests (or one larger one); past that a frame is given
53//! back ([`SendError::Full`]), and a sender that passed a [`Waiter`] is
54//! woken ([`Inbound::drained`]) once the thread takes the queue to write
55//! it, or the node is down. Other signals, small, are not capped.
56//! - **Down** after `node_down_after_ms` without a byte from the peer
57//! (heartbeats keep an idle connection alive; one the relay paused is not
58//! read, so not timed), or when the connection
59//! fails or breaks the protocol: [`Inbound::node_down`], and the
60//! connection is closed. A frame for a node that is not up is refused
61//! ([`SendError::NotConnected`]): delivery is at most once.
62//! - **Untrusted until the handshake.** Before it, a connection is held
63//! for `node_down_after_ms` at most, its frames are 1 KiB at most, and
64//! at most [`MAX_UNAUTHENTICATED`] accepted connections are open before
65//! their hello, [`MAX_UNAUTHENTICATED_PER_SOURCE`] from one address: a
66//! new one closes its own source's oldest, or the oldest of the source
67//! holding the most, so a flood from one host closes only its own.
68//! Their failures are logged at most every 10 s ([`Throttle`]).
69//! No peer input is unwrapped; every buffer is bounded by a frame limit.
70//!
71//! `tl_dist_start` (`node.rs`) starts it, with the handler that decodes
72//! messages and answers lookups.
73
74mod frame;
75mod relay;
76mod thread;
77
78#[cfg(test)]
79mod tests;
80
81use std::collections::{HashMap, VecDeque};
82use std::net::SocketAddr;
83use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
84use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
85use std::thread::JoinHandle;
86
87use louise_rt_prims::wire::{HEADER_LEN, MAX_DELAY_MS, MAX_PEERS, MessageHeader, check_node_name};
88pub(crate) use louise_rt_prims::wire::{MAX_FRAME, MIN_FRAME};
89
90pub(crate) use crate::dist::{Node, Waiter};
91use crate::sched::Shared;
92use frame::Entry;
93#[cfg(test)]
94pub(crate) use frame::needs;
95
96/// Accepted connections whose hello has not arrived: past this, a new one
97/// closes the oldest of the source that holds the most.
98pub(crate) const MAX_UNAUTHENTICATED: usize = 128;
99
100/// Accepted connections whose hello has not arrived, from one source (an
101/// IPv4 address, or an IPv6 /64): past this, a new one closes its source's
102/// oldest. A host flooding a node with connections then evicts only its
103/// own, however slow a real node's handshake (a distant one's, say).
104pub(crate) const MAX_UNAUTHENTICATED_PER_SOURCE: usize = 8;
105
106/// A log line at most every [`Throttle::PERIOD`], for what an
107/// unauthenticated host can make happen at its own rate (a connection that
108/// fails before its hello, an accept that fails): the first at once, then
109/// one per period, which says how many were held back meanwhile.
110#[derive(Default)]
111pub(crate) struct Throttle {
112 last: Option<std::time::Instant>,
113 held: u64,
114}
115
116impl Throttle {
117 pub(crate) const PERIOD: std::time::Duration = std::time::Duration::from_secs(10);
118
119 /// Whether to log now: `Some(held)`, the lines held back since the
120 /// last one; `None`, hold this one back.
121 pub(crate) fn admit(&mut self, now: std::time::Instant) -> Option<u64> {
122 match self.last {
123 Some(last) if now.saturating_duration_since(last) < Self::PERIOD => {
124 self.held += 1;
125 None
126 }
127 _ => {
128 self.last = Some(now);
129 Some(std::mem::take(&mut self.held))
130 }
131 }
132 }
133
134 /// What a line [`Throttle::admit`]ted adds about those held back.
135 pub(crate) fn held_back(held: u64) -> String {
136 match held {
137 0 => String::new(),
138 n => format!(" ({n} more since the last such line, not logged)"),
139 }
140 }
141}
142
143/// What a node is started with: plain values, which `std/dist` reads from
144/// the environment and `[cluster]`.
145#[derive(Clone, Debug)]
146pub(crate) struct Config {
147 /// This node's name: a lowercase DNS name its certificate is valid for.
148 pub(crate) node: String,
149 /// Nodes of other clusters are refused. A node name's syntax.
150 pub(crate) cluster: String,
151 pub(crate) listen: SocketAddr,
152 /// Where peers can dial this node, which its lists of peers say
153 /// (`mesh`): `None`, `listen` unless it is unspecified (`0.0.0.0`,
154 /// `::`), with the port the OS chose for port 0; else nothing, a
155 /// node only other nodes' dials do not reach.
156 pub(crate) advertise: Option<SocketAddr>,
157 /// Nodes to connect to at start, and again whenever their connection
158 /// is lost.
159 pub(crate) seeds: Vec<(String, SocketAddr)>,
160 /// Full-mesh discovery: lists of peers are exchanged with the peers
161 /// that also discover, and the nodes they list are dialed. Otherwise
162 /// only seeds and `connect`ed nodes are.
163 pub(crate) mesh: bool,
164 /// This node's certificate chain and key (PEM), presented both as a
165 /// server and as a client.
166 pub(crate) cert_file: String,
167 pub(crate) key_file: String,
168 /// The cluster's authorities (PEM): a peer's certificate must chain to
169 /// one. Never the system's roots.
170 pub(crate) ca_files: Vec<String>,
171 /// The program's schema hash: peers must have the same (stage 1).
172 pub(crate) schema_hash: u64,
173 /// A heartbeat goes out to each peer this often, in the control lane;
174 /// its echo gives the round-trip time.
175 pub(crate) heartbeat_ms: u64,
176 /// A peer silent for this long is down (it also bounds a handshake).
177 pub(crate) node_down_after_ms: u64,
178 /// The largest frame this node accepts, announced in its handshake:
179 /// a larger one closes the connection.
180 pub(crate) max_frame: u32,
181 /// The message bytes (headers and payloads) queued per peer before
182 /// [`SendError::Full`]; an empty queue takes one message of any size
183 /// within the peer's frame limit. Signals are not counted (ADR 0072,
184 /// *Back-pressure*).
185 pub(crate) max_queue: usize,
186 /// Connections past their hello kept before a peer that is neither a
187 /// seed nor `connect`ed is refused ([`Reason::Full`]); also how many
188 /// down nodes' statistics are kept ([`PeerStats`]).
189 pub(crate) max_peers: usize,
190 /// The first delay before connecting again to a known node; it doubles
191 /// on each failure, up to 32 times.
192 pub(crate) reconnect_ms: u64,
193}
194
195impl Config {
196 /// A configuration with the defaults: heartbeats every second, down
197 /// after 10 s, frames of 8 MiB, 64 MiB queued per peer, 256 peers.
198 pub(crate) fn new(node: &str, cluster: &str, listen: SocketAddr) -> Config {
199 Config {
200 node: node.to_owned(),
201 cluster: cluster.to_owned(),
202 listen,
203 advertise: None,
204 seeds: Vec::new(),
205 mesh: false,
206 cert_file: String::new(),
207 key_file: String::new(),
208 ca_files: Vec::new(),
209 schema_hash: 0,
210 heartbeat_ms: 1_000,
211 node_down_after_ms: 10_000,
212 max_frame: 8 << 20,
213 max_queue: 64 << 20,
214 max_peers: 256,
215 reconnect_ms: 1_000,
216 }
217 }
218
219 /// Refuse what cannot work, before anything is opened.
220 fn check(&self) -> Result<(), String> {
221 for (what, name) in [("node", &self.node), ("cluster", &self.cluster)]
222 .into_iter()
223 .chain(self.seeds.iter().map(|(n, _)| ("seed", n)))
224 {
225 if !check_node_name(name.as_bytes()) {
226 return Err(format!("{what} name {name:?} is not a lowercase DNS name"));
227 }
228 }
229 if self.seeds.iter().any(|(n, _)| *n == self.node) {
230 return Err(format!("{} is this node, not a seed", self.node));
231 }
232 if let Some(addr) = self.advertise
233 && !frame::dialable(addr)
234 {
235 return Err(format!(
236 "cannot advertise {addr}: an address peers can dial needs a port, and is not unspecified, multicast or broadcast"
237 ));
238 }
239 if self.ca_files.is_empty() {
240 return Err("no cluster authority: give the CA files peers are signed by".into());
241 }
242 if !(MIN_FRAME..=MAX_FRAME).contains(&self.max_frame) {
243 return Err(format!(
244 "max_frame must be between {MIN_FRAME} and {MAX_FRAME} bytes"
245 ));
246 }
247 if self.heartbeat_ms == 0 || self.node_down_after_ms <= self.heartbeat_ms {
248 return Err("node_down_after_ms must exceed heartbeat_ms, which must not be 0".into());
249 }
250 if !(1..=MAX_PEERS).contains(&self.max_peers) {
251 return Err(format!("max_peers must be between 1 and {MAX_PEERS}"));
252 }
253 if self.reconnect_ms == 0 {
254 return Err("reconnect_ms must not be 0".into());
255 }
256 if self.node_down_after_ms.max(self.reconnect_ms) > MAX_DELAY_MS {
257 return Err(format!(
258 "node_down_after_ms and reconnect_ms must be at most {MAX_DELAY_MS} (a day)"
259 ));
260 }
261 Ok(())
262 }
263}
264
265/// Why a connection was refused or closed. Peer-supplied text is kept as
266/// sent and escaped when shown.
267#[derive(Clone, Debug, PartialEq)]
268pub(crate) enum Reason {
269 /// TLS failed: the handshake (an unknown authority, a certificate not
270 /// valid for the dialed name...) or a record (rustls's message).
271 Tls(String),
272 /// The connection did not negotiate ALPN `louise-dist`.
273 Alpn,
274 /// The peer speaks another protocol version.
275 Version(u16),
276 /// The peer is of another cluster (its name).
277 Cluster(String),
278 /// The peer was built with another schema (its hash).
279 Schema(u64),
280 /// The peer's claimed name is not valid for its certificate, not the
281 /// name it was dialed as, or this node's own.
282 Name(String),
283 /// Another connection to the same node is kept: simultaneous dials,
284 /// or one already up.
285 Duplicate,
286 /// A malformed or unexpected frame.
287 Protocol(&'static str),
288 /// A frame larger than the limit this node announced (its length).
289 TooLarge(u32),
290 /// Nothing from the peer for `node_down_after_ms`, or a handshake that
291 /// took that long.
292 Timeout,
293 /// Closed in its handshake to make room for a newer connection: more
294 /// than [`MAX_UNAUTHENTICATED`] were in theirs.
295 Crowded,
296 /// Refused at its hello: this node keeps `max_peers` connections past
297 /// theirs, and the peer is neither a seed nor `connect`ed. Labelled by
298 /// its address (its hello is not accepted), so `node.rs` logs it as
299 /// sparingly as a connection that fails before its hello.
300 Full,
301 /// The peer ended the connection in order (TLS `close_notify`): its
302 /// program stopped, say.
303 PeerClosed,
304 /// The connection failed, or ended without `close_notify`.
305 Closed(String),
306 /// The peer refused this node: its reason's code and text.
307 Refused(u8, String),
308 /// A new incarnation of the node connected.
309 Replaced,
310 /// This transport stops.
311 Stopped,
312}
313
314impl Reason {
315 /// The code a refusal frame carries (`docs/wire-format.md`,
316 /// *Handshake*), for a reason this node tells its peer.
317 fn code(&self) -> Option<u8> {
318 Some(match self {
319 Reason::Version(_) => 1,
320 Reason::Cluster(_) => 2,
321 Reason::Schema(_) => 3,
322 Reason::Name(_) => 4,
323 Reason::Duplicate => 5,
324 Reason::Protocol(_) | Reason::TooLarge(_) | Reason::Alpn => 6,
325 Reason::Replaced => 7,
326 Reason::Full => 8,
327 _ => return None,
328 })
329 }
330
331 /// Whether this is how the protocol normally goes, not worth a log:
332 /// a peer that stops closes its connections in order. `Crowded` is
333 /// not, but a log line for each connection of a flood would be another
334 /// flood.
335 pub(crate) fn routine(&self) -> bool {
336 matches!(
337 self,
338 Reason::Duplicate
339 | Reason::Refused(5, _)
340 | Reason::Stopped
341 | Reason::Crowded
342 | Reason::PeerClosed
343 )
344 }
345}
346
347impl std::fmt::Display for Reason {
348 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349 match self {
350 Reason::Tls(e) => write!(f, "TLS: {e}"),
351 Reason::Alpn => write!(f, "not the louise-dist protocol (ALPN)"),
352 Reason::Version(v) => write!(f, "protocol version {v}, not {}", frame::VERSION),
353 Reason::Cluster(c) => write!(f, "cluster {:?}", c.escape_debug().to_string()),
354 Reason::Schema(h) => write!(f, "schema {h:016x}: built from other types"),
355 Reason::Name(n) => write!(f, "node name {:?} refused", n.escape_debug().to_string()),
356 Reason::Duplicate => write!(f, "already connected"),
357 Reason::Protocol(what) => write!(f, "protocol error: {what}"),
358 Reason::TooLarge(n) => write!(f, "frame of {n} bytes over the limit"),
359 Reason::Timeout => write!(f, "timed out (no heartbeat, or a slow handshake)"),
360 Reason::Crowded => write!(f, "too many connections in their handshake"),
361 Reason::Full => write!(f, "too many peers ([cluster] max_peers)"),
362 Reason::PeerClosed => write!(f, "connection closed: the peer closed it"),
363 Reason::Closed(why) => write!(f, "connection closed: {why}"),
364 Reason::Refused(code, text) => {
365 write!(f, "refused by the peer ({code}): {}", text.escape_debug())
366 }
367 Reason::Replaced => write!(f, "replaced by a new incarnation"),
368 Reason::Stopped => write!(f, "stopped"),
369 }
370 }
371}
372
373/// What arrives from peers, called on the `louise-dist-in` thread in the
374/// order it arrived (per peer: the order it was sent), [`Inbound::drained`]
375/// excepted: on the `louise-dist` thread, at once. The real handler decodes
376/// and calls `dist::inbound`; it must not wait for the transport (a send is
377/// fine, stopping it is not).
378pub(crate) trait Inbound: Send + Sync {
379 /// The handshake with `peer` completed: frames flow both ways.
380 fn node_up(&self, peer: &Node);
381 /// `peer`, which was up, is lost (`dist::inbound::node_down`'s
382 /// fan-out): no more frames come from it, and frames still queued for
383 /// it are dropped.
384 fn node_down(&self, peer: &Node);
385 /// A message frame from `from` for this node's incarnation, its header
386 /// checked (`docs/wire-format.md`, *Frames*); `payload` is its
387 /// `payload_len` bytes.
388 fn message(&self, from: &Node, header: &MessageHeader, payload: &[u8]);
389 /// A signal frame: a lookup or its answer, a link, monitor or exit
390 /// signal (`docs/wire-format.md`, *Lookups* and *Signals*).
391 fn signal(&self, from: &Node, body: &[u8]);
392 /// Senders that found `peer`'s queue full may try again: the thread
393 /// took the queue to write it, or the node is down (their next try
394 /// is then refused). Each was registered once, by a refused
395 /// [`Transport::queue`].
396 fn drained(&self, peer: &Node, waiters: &[Waiter]);
397 /// A connection to `peer` (its name, or its address before the
398 /// handshake) was refused or closed for `reason`. `hearsay`: it was a
399 /// dial, never past its hello, to an address that only peers' lists
400 /// gave (a discovered node that never confirmed it): the peers chose
401 /// the name, and how often it fails. Logged by default.
402 fn closed(&self, peer: &str, reason: &Reason, hearsay: bool) {
403 let _ = hearsay;
404 if !reason.routine() {
405 eprintln!("louise: dist: {peer}: {reason}");
406 }
407 }
408}
409
410/// A frame for a peer, already encoded.
411pub(crate) enum Outbound {
412 /// A message frame: its 36-byte header, then its payload.
413 Message(Vec<u8>),
414 /// A signal frame that carries a payload, a spawn request: counted
415 /// against the queue's cap as a message is.
416 Request(Vec<u8>),
417 /// A signal frame of a fixed small size, exempt from the queue's cap
418 /// (not from its order).
419 Signal(Vec<u8>),
420}
421
422#[derive(Clone, Copy, Debug, PartialEq, Eq)]
423pub(crate) enum SendError {
424 /// That incarnation of the node is not up: the frame is dropped.
425 NotConnected,
426 /// Over the peer's frame limit.
427 TooLarge,
428 /// The peer's queue holds `max_queue` bytes of messages: the frame is
429 /// given back ([`Transport::queue`]).
430 Full,
431 /// A message frame whose header is malformed, does not match its
432 /// length or names another incarnation: a bug in the encoder.
433 Malformed,
434 /// A signal frame of an op the peer's hello did not say it takes
435 /// ([`frame::needs`]): the frame is dropped.
436 Unsupported,
437}
438
439/// Where senders queue frames for the thread: per peer that is up, in
440/// send order. Senders hold the lock for one push; the thread takes a
441/// peer's whole queue once its connection has written the previous batch
442/// (the low-water mark: the queue is then empty, and its parked senders
443/// are woken), so a peer holds at most twice `max_queue` bytes of
444/// messages, one larger message aside.
445pub(super) struct Outbox {
446 routes: Mutex<HashMap<String, Route>>,
447 /// Per node name, from the first time it is known: a seed, a
448 /// connection, a message for it. Bounded: see [`PeerStats`].
449 stats: Mutex<PeerStats>,
450 commands: Mutex<Vec<Command>>,
451 waker: mio::Waker,
452 /// A wake is pending: senders skip theirs.
453 woken: AtomicBool,
454 max_queue: usize,
455 /// Connections open, up or not.
456 open: AtomicUsize,
457 /// Frames received for another incarnation of this node.
458 dropped: AtomicU64,
459}
460
461/// A peer that is up, as senders see it.
462struct Route {
463 incarnation: u64,
464 /// The largest frame it accepts.
465 max_frame: u32,
466 /// The capability flags of its hello.
467 flags: u64,
468 queue: VecDeque<Entry>,
469 /// Message bytes in `queue`.
470 queued: usize,
471 /// Senders the full queue refused, to wake when it drains.
472 parked: Vec<Waiter>,
473 stats: Arc<Stats>,
474}
475
476/// What `std/dist.peers` reports of a node, for the whole run: counts
477/// across its connections, its round-trip time on the current one.
478pub(super) struct Stats {
479 /// The incarnation it was last up as; 0 before.
480 incarnation: AtomicU64,
481 /// Microseconds from a heartbeat to its echo, the latest measured on
482 /// the current connection; `u64::MAX` before.
483 rtt_us: AtomicU64,
484 /// Message frames handed to TLS for it.
485 sent: AtomicU64,
486 /// Message frames from it for this node's incarnation (some of which
487 /// the handler may drop: `dropped`).
488 received: AtomicU64,
489 /// Messages for it not sent: it was not up, or its connection was lost
490 /// with them queued, or their sender exited while parked.
491 unsent: AtomicU64,
492 /// Senders its full queue made wait (registered waiters).
493 parked: AtomicU64,
494 /// Frames from it dropped: for another incarnation of this node, or
495 /// refused by the handler (undecodable, of an unknown type...).
496 dropped: AtomicU64,
497}
498
499impl Stats {
500 fn new() -> Stats {
501 Stats {
502 incarnation: AtomicU64::new(0),
503 rtt_us: AtomicU64::new(u64::MAX),
504 sent: AtomicU64::new(0),
505 received: AtomicU64::new(0),
506 unsent: AtomicU64::new(0),
507 parked: AtomicU64::new(0),
508 dropped: AtomicU64::new(0),
509 }
510 }
511
512 pub(super) fn count(counter: &AtomicU64, n: u64) {
513 counter.fetch_add(n, Ordering::Relaxed);
514 }
515}
516
517/// Every node name this node knows, and its statistics: for the whole run
518/// while it is up, a seed or `connect`ed; otherwise while it is among the
519/// `max_down` most recently seen (`max_peers`). Names come from peers
520/// (a pid of a node this one never connected to, a peer that connects
521/// once), so a name past those forgets the least recently seen, its
522/// counts with it.
523pub(super) struct PeerStats {
524 by_name: HashMap<String, Seen>,
525 /// Ticks at each touch: what "recently" means.
526 clock: u64,
527 max_down: usize,
528}
529
530struct Seen {
531 stats: Arc<Stats>,
532 /// When it was last touched, on [`PeerStats::clock`].
533 at: u64,
534 /// A connection past its hello is up with it (the thread says so).
535 up: bool,
536 /// A seed or `connect`ed: never forgotten.
537 kept: bool,
538}
539
540impl PeerStats {
541 pub(super) fn new(max_down: usize) -> PeerStats {
542 PeerStats {
543 by_name: HashMap::new(),
544 clock: 0,
545 max_down,
546 }
547 }
548
549 /// `name`'s statistics, seen now.
550 pub(super) fn stats(&mut self, name: &str) -> Arc<Stats> {
551 let new = !self.by_name.contains_key(name);
552 let stats = self.seen(name).stats.clone();
553 if new {
554 self.forget();
555 }
556 stats
557 }
558
559 /// `name` is a seed or `connect`ed: kept from now on.
560 fn keep(&mut self, name: &str) {
561 self.seen(name).kept = true;
562 }
563
564 /// `name` is up: kept until it is down. Its statistics.
565 pub(super) fn up(&mut self, name: &str) -> Arc<Stats> {
566 let seen = self.seen(name);
567 seen.up = true;
568 seen.stats.clone()
569 }
570
571 /// `name` is down: seen now, the most recent of the down nodes.
572 pub(super) fn down(&mut self, name: &str) {
573 self.seen(name).up = false;
574 self.forget();
575 }
576
577 fn seen(&mut self, name: &str) -> &mut Seen {
578 self.clock += 1;
579 let seen = self.by_name.entry(name.to_owned()).or_insert_with(|| Seen {
580 stats: Arc::new(Stats::new()),
581 at: 0,
582 up: false,
583 kept: false,
584 });
585 seen.at = self.clock;
586 seen
587 }
588
589 /// Forget the least recently seen of the names neither up nor kept
590 /// while there are more than `max_down`. A scan of every name, only
591 /// for a new name or a node down, not for each message counted.
592 fn forget(&mut self) {
593 loop {
594 let mut down = 0;
595 let mut oldest: Option<(u64, &String)> = None;
596 for (name, seen) in &self.by_name {
597 if seen.up || seen.kept {
598 continue;
599 }
600 down += 1;
601 if oldest.is_none_or(|(at, _)| seen.at < at) {
602 oldest = Some((seen.at, name));
603 }
604 }
605 match oldest {
606 Some((_, name)) if down > self.max_down => {
607 let name = name.clone();
608 self.by_name.remove(&name);
609 }
610 _ => return,
611 }
612 }
613 }
614
615 /// Every name known, and its statistics.
616 fn iter(&self) -> impl Iterator<Item = (&String, &Arc<Stats>)> {
617 self.by_name.iter().map(|(name, seen)| (name, &seen.stats))
618 }
619}
620
621/// A node as [`Transport::report`] sees it.
622#[derive(Clone, Debug, PartialEq)]
623pub(crate) struct Report {
624 pub(crate) node: String,
625 /// The incarnation it is (or was last) up as; `None` if never.
626 pub(crate) incarnation: Option<u64>,
627 pub(crate) up: bool,
628 /// Round-trip time in microseconds, while up and once measured.
629 pub(crate) rtt_us: Option<u64>,
630 /// Message bytes queued for it, not yet taken by the thread.
631 pub(crate) queued: usize,
632 pub(crate) sent: u64,
633 pub(crate) received: u64,
634 pub(crate) unsent: u64,
635 pub(crate) parked: u64,
636 pub(crate) dropped: u64,
637}
638
639/// What the handle asks of the thread.
640pub(super) enum Command {
641 Connect(String, SocketAddr),
642 Stop,
643}
644
645impl Outbox {
646 fn routes(&self) -> MutexGuard<'_, HashMap<String, Route>> {
647 self.routes.lock().unwrap_or_else(PoisonError::into_inner)
648 }
649
650 /// Every node name known, and its statistics.
651 pub(super) fn peer_stats(&self) -> MutexGuard<'_, PeerStats> {
652 self.stats.lock().unwrap_or_else(PoisonError::into_inner)
653 }
654
655 /// `name`'s statistics, seen now ([`PeerStats`]).
656 pub(super) fn stats(&self, name: &str) -> Arc<Stats> {
657 self.peer_stats().stats(name)
658 }
659
660 fn command(&self, command: Command) {
661 self.commands
662 .lock()
663 .unwrap_or_else(PoisonError::into_inner)
664 .push(command);
665 self.wake();
666 }
667
668 /// Wake the thread, unless a wake is pending.
669 pub(super) fn wake(&self) {
670 if !self.woken.swap(true, Ordering::AcqRel) && self.waker.wake().is_err() {
671 // The frames wait for the next event or heartbeat; the next
672 // sender tries again.
673 self.woken.store(false, Ordering::Release);
674 }
675 }
676}
677
678/// A running transport: its thread, and the queues senders use.
679pub(crate) struct Transport {
680 outbox: Arc<Outbox>,
681 thread: Option<JoinHandle<()>>,
682 relay: Arc<relay::Relay>,
683 /// The relay's thread, joined after the transport's.
684 relayed: Option<JoinHandle<()>>,
685 me: Node,
686 local_addr: SocketAddr,
687}
688
689impl Transport {
690 /// Check `config`, load its certificates, listen, and start the
691 /// `louise-dist` thread, which dials the seeds. This node's
692 /// incarnation is drawn at random. Touches no global state (see
693 /// [`start_program`]).
694 pub(crate) fn start(config: Config, inbound: Arc<dyn Inbound>) -> Result<Transport, String> {
695 config.check()?;
696 let mut incarnation = [0u8; 8];
697 rustls::crypto::ring::default_provider()
698 .secure_random
699 .fill(&mut incarnation)
700 .map_err(|_| "no random incarnation".to_string())?;
701 let me = Node {
702 name: config.node.clone(),
703 incarnation: u64::from_le_bytes(incarnation),
704 };
705 let seeds: Vec<String> = config.seeds.iter().map(|(n, _)| n.clone()).collect();
706 let relay = Arc::new(relay::Relay::new(inbound));
707 let thread = thread::Thread::new(config, me.clone(), relay.clone())?;
708 let outbox = thread.outbox();
709 relay.wakes(outbox.clone());
710 for seed in &seeds {
711 outbox.peer_stats().keep(seed);
712 }
713 let local_addr = thread.local_addr();
714 let relayed = {
715 let relay = relay.clone();
716 std::thread::Builder::new()
717 .name("louise-dist-in".into())
718 .spawn(move || relay.run())
719 .map_err(|e| format!("cannot start the louise-dist-in thread: {e}"))?
720 };
721 let mut transport = Transport {
722 outbox,
723 thread: None,
724 relay,
725 relayed: Some(relayed),
726 me,
727 local_addr,
728 };
729 // On an error, dropping the transport joins the relay.
730 transport.thread = Some(
731 std::thread::Builder::new()
732 .name("louise-dist".into())
733 .spawn(move || thread.run())
734 .map_err(|e| format!("cannot start the louise-dist thread: {e}"))?,
735 );
736 Ok(transport)
737 }
738
739 /// This node: its name and incarnation.
740 pub(crate) fn me(&self) -> &Node {
741 &self.me
742 }
743
744 /// The address it listens on (the port the OS chose, for port 0).
745 pub(crate) fn local_addr(&self) -> SocketAddr {
746 self.local_addr
747 }
748
749 /// Connect to `name` at `addr` (unless connected), and again whenever
750 /// the connection is lost, as a seed: a discovered node becomes one.
751 pub(crate) fn connect(&self, name: &str, addr: SocketAddr) {
752 self.outbox.peer_stats().keep(name);
753 self.outbox.command(Command::Connect(name.to_owned(), addr));
754 }
755
756 /// Queue `frame` for `to`, behind every frame sent to it before, or
757 /// give it back with why not. It is written by the thread; it may
758 /// still be lost with the connection. A signal frame whose op needs a
759 /// capability flag `to`'s hello did not set is refused
760 /// ([`SendError::Unsupported`]), checked under the queue's lock. A message the full queue refuses
761 /// registers `waiter`, if any, under the queue's lock, so the drain it
762 /// waits for cannot pass unseen ([`Inbound::drained`]). From any
763 /// thread; never waits but for the queue's lock.
764 pub(crate) fn queue(
765 &self,
766 to: &Node,
767 frame: Outbound,
768 waiter: Option<Waiter>,
769 ) -> Result<(), (SendError, Outbound)> {
770 let counted = match &frame {
771 Outbound::Message(body) => {
772 let header = body
773 .first_chunk::<HEADER_LEN>()
774 .and_then(|h| MessageHeader::decode(h).ok());
775 let fits = header.is_some_and(|h| {
776 h.incarnation == to.incarnation
777 && body.len() - HEADER_LEN == h.payload_len as usize
778 });
779 if !fits {
780 return Err((SendError::Malformed, frame));
781 }
782 true
783 }
784 Outbound::Request(_) => true,
785 Outbound::Signal(_) => false,
786 };
787 let (size, needs) = match &frame {
788 Outbound::Message(body) => (body.len(), 0),
789 Outbound::Request(body) | Outbound::Signal(body) => {
790 (body.len(), body.first().map_or(0, |op| frame::needs(*op)))
791 }
792 };
793 {
794 let mut routes = self.outbox.routes();
795 let Some(route) = routes
796 .get_mut(&to.name)
797 .filter(|r| r.incarnation == to.incarnation)
798 else {
799 return Err((SendError::NotConnected, frame));
800 };
801 if route.flags & needs != needs {
802 return Err((SendError::Unsupported, frame));
803 }
804 if 1 + size as u64 > u64::from(route.max_frame) {
805 return Err((SendError::TooLarge, frame));
806 }
807 if counted {
808 // An empty queue takes any message: a queue smaller than
809 // the peer's frame limit must not refuse one forever.
810 if route.queued > 0 && route.queued.saturating_add(size) > self.outbox.max_queue {
811 if let Some(waiter) = waiter {
812 route.parked.push(waiter);
813 Stats::count(&route.stats.parked, 1);
814 }
815 return Err((SendError::Full, frame));
816 }
817 route.queued += size;
818 }
819 route.queue.push_back(match frame {
820 Outbound::Message(body) => Entry::new(frame::MESSAGE, body),
821 Outbound::Request(body) | Outbound::Signal(body) => Entry::new(frame::SIGNAL, body),
822 });
823 }
824 self.outbox.wake();
825 Ok(())
826 }
827
828 /// Whether `to`, up as that incarnation, did not set the capability
829 /// flag a signal frame of `op` needs ([`frame::needs`]): a frame of
830 /// it would be refused ([`SendError::Unsupported`]). False for a node
831 /// that is not up.
832 pub(crate) fn lacks(&self, to: &Node, op: u8) -> bool {
833 let needs = frame::needs(op);
834 self.outbox
835 .routes()
836 .get(&to.name)
837 .filter(|r| r.incarnation == to.incarnation)
838 .is_some_and(|r| r.flags & needs != needs)
839 }
840
841 /// [`Transport::queue`], a refused frame dropped.
842 pub(crate) fn send(&self, to: &Node, frame: Outbound) -> Result<(), SendError> {
843 self.queue(to, frame, None).map_err(|(e, _)| e)
844 }
845
846 /// Forget `waiter`, registered for `to`'s queue, if the thread has not
847 /// woken it: something else did (its actor exited).
848 pub(crate) fn unwait(&self, to: &Node, waiter: Waiter) {
849 if let Some(route) = self
850 .outbox
851 .routes()
852 .get_mut(&to.name)
853 .filter(|r| r.incarnation == to.incarnation)
854 {
855 route.parked.retain(|w| *w != waiter);
856 }
857 }
858
859 /// A message for `name` was not sent (see [`Stats`]'s `unsent`).
860 pub(crate) fn count_unsent(&self, name: &str) {
861 Stats::count(&self.outbox.stats(name).unsent, 1);
862 }
863
864 /// A frame from `name` was dropped by the handler.
865 pub(crate) fn count_dropped(&self, name: &str) {
866 Stats::count(&self.outbox.stats(name).dropped, 1);
867 }
868
869 /// Every node known, by name: up or not, its statistics. A snapshot,
870 /// each figure read on its own. Of the nodes neither up nor seeds, the
871 /// `max_peers` most recently seen ([`PeerStats`]).
872 pub(crate) fn report(&self) -> Vec<Report> {
873 let stats: Vec<(String, Arc<Stats>)> = self
874 .outbox
875 .peer_stats()
876 .iter()
877 .map(|(name, s)| (name.clone(), s.clone()))
878 .collect();
879 let routes = self.outbox.routes();
880 let mut report: Vec<Report> = stats
881 .into_iter()
882 .map(|(node, s)| {
883 let route = routes.get(&node);
884 let load = |c: &AtomicU64| c.load(Ordering::Relaxed);
885 let incarnation = load(&s.incarnation);
886 Report {
887 incarnation: route
888 .map(|r| r.incarnation)
889 .or((incarnation != 0).then_some(incarnation)),
890 up: route.is_some(),
891 rtt_us: route.map(|_| load(&s.rtt_us)).filter(|t| *t != u64::MAX),
892 queued: route.map_or(0, |r| r.queued),
893 sent: load(&s.sent),
894 received: load(&s.received),
895 unsent: load(&s.unsent),
896 parked: load(&s.parked),
897 dropped: load(&s.dropped),
898 node,
899 }
900 })
901 .collect();
902 drop(routes);
903 report.sort_by(|a, b| a.node.cmp(&b.node));
904 report
905 }
906
907 /// The peers that are up, by name.
908 pub(crate) fn peers(&self) -> Vec<Node> {
909 let mut peers: Vec<Node> = self
910 .outbox
911 .routes()
912 .iter()
913 .map(|(name, r)| Node {
914 name: name.clone(),
915 incarnation: r.incarnation,
916 })
917 .collect();
918 peers.sort_by(|a, b| a.name.cmp(&b.name));
919 peers
920 }
921
922 /// Connections open, up or still in their handshake.
923 #[cfg(test)]
924 pub(crate) fn connections(&self) -> usize {
925 self.outbox.open.load(Ordering::Acquire)
926 }
927
928 /// Frames received for another incarnation of this node, dropped.
929 #[cfg(test)]
930 pub(crate) fn dropped(&self) -> u64 {
931 self.outbox.dropped.load(Ordering::Relaxed)
932 }
933
934 /// Close every connection (each peer that was up is down) and join
935 /// the thread.
936 pub(crate) fn stop(mut self) {
937 self.join();
938 }
939
940 /// Stop the transport's thread, then the relay's once it has handed
941 /// over what the stop queued.
942 fn join(&mut self) {
943 if let Some(thread) = self.thread.take() {
944 self.outbox.command(Command::Stop);
945 if thread.join().is_err() {
946 eprintln!("louise: dist: the transport thread panicked");
947 }
948 }
949 if let Some(relayed) = self.relayed.take() {
950 self.relay.stop();
951 if relayed.join().is_err() {
952 eprintln!("louise: dist: the inbound thread panicked");
953 }
954 }
955 }
956}
957
958impl Drop for Transport {
959 fn drop(&mut self) {
960 self.join();
961 }
962}
963
964// ---- the program's transport -----------------------------------------------------
965
966/// The transport the program runs, between [`start_program`] and
967/// [`stop_program`]. The hooks (`dist::Hooks`) reach it here.
968static PROGRAM: RwLock<Option<Transport>> = RwLock::new(None);
969
970/// Start distribution for the program running on `sched`
971/// (`tl_dist_start`). The clock switches to real time, the scheduler's
972/// deadlock check counts the transport as something that can still wake
973/// an actor, and the scheduler stops it (joining its thread) before its
974/// shared state is dropped. Once per program.
975pub(crate) fn start_program(
976 sched: &Shared,
977 config: Config,
978 inbound: Arc<dyn Inbound>,
979) -> Result<(), String> {
980 let mut program = PROGRAM.write().unwrap_or_else(PoisonError::into_inner);
981 if program.is_some() {
982 return Err("distribution is already started".into());
983 }
984 *program = Some(Transport::start(config, inbound)?);
985 sched.switch_to_real_time();
986 crate::dist::transport_started(stop_program);
987 Ok(())
988}
989
990/// The program's transport, while it runs.
991pub(crate) fn with_program<R>(f: impl FnOnce(&Transport) -> R) -> Option<R> {
992 PROGRAM
993 .read()
994 .unwrap_or_else(PoisonError::into_inner)
995 .as_ref()
996 .map(f)
997}
998
999/// Stop the program's transport and join its thread: remote operations act
1000/// as on dead pids again. Outside the lock, so the handler may still reach
1001/// [`with_program`] while the thread stops.
1002fn stop_program() {
1003 crate::dist::uninstall();
1004 let transport = PROGRAM
1005 .write()
1006 .unwrap_or_else(PoisonError::into_inner)
1007 .take();
1008 if let Some(transport) = transport {
1009 transport.stop();
1010 }
1011 crate::dist::transport_stopped();
1012}