Skip to main content

zebrad/components/
health.rs

1//! HTTP health and readiness endpoints for `zebrad`.
2//!
3//! Overview
4//!
5//! - This module exposes two small HTTP/1.1 endpoints for basic liveness/readiness checks,
6//!   suitable for Kubernetes probes and load balancers.
7//! - Endpoints are opt-in, disabled by default. Enable by setting a `listen_addr` in the
8//!   `health` config section.
9//! - Plain-text responses and small responses keep the checks fast and safe.
10//!
11//! Endpoints
12//!
13//! - `GET /healthy` — returns `200 OK` if the process is up and the node has at least
14//!   `min_connected_peers` recently live peers (default: 1). Otherwise `503 Service Unavailable`.
15//! - `GET /ready` — returns `200 OK` if the node is near the chain tip, the estimated block lag is
16//!   within `ready_max_blocks_behind`, and the latest committed block is recent. On regtest/testnet,
17//!   readiness returns `200` unless `enforce_on_test_networks` is set.
18//!
19//! Security
20//!
21//! - Endpoints are unauthenticated by design. Bind to internal network interfaces,
22//!   and restrict exposure using network policy, firewall rules, and service configuration.
23//! - Each connection serves one request. The server drops connections past its connection and
24//!   request limits, and closes connections that don't send their request headers in time. A
25//!   client that can reach the endpoint can still use up those limits and make probes fail.
26//! - The server does not access or return private data. It only summarises coarse node state.
27//!
28//! Configuration and examples
29//!
30//! - See the Zebra Book for configuration details and Kubernetes probe examples:
31//!   <https://zebra.zfnd.org/user/health.html>
32
33mod config;
34#[cfg(test)]
35mod tests;
36
37pub use config::Config;
38use derive_new::new;
39
40use std::time::Instant;
41use std::{convert::Infallible, net::SocketAddr, sync::Arc, time::Duration};
42
43use bytes::Bytes;
44use chrono::Utc;
45use http_body_util::Full;
46use hyper::header::{CONTENT_LENGTH, CONTENT_TYPE};
47use hyper::server::conn::http1;
48use hyper::{
49    body::Incoming, http::response::Builder as ResponseBuilder, Method, Request, Response,
50    StatusCode,
51};
52use hyper_util::rt::{TokioIo, TokioTimer};
53use tokio::{
54    sync::{watch, Semaphore},
55    task::JoinHandle,
56    time::{self, MissedTickBehavior},
57};
58use tracing::{debug, info, warn};
59
60use zebra_chain::{chain_sync_status::ChainSyncStatus, parameters::Network};
61use zebra_network::AddressBookPeers;
62
63// Refresh peers on a short cadence so the cached snapshot tracks live network
64// conditions closely without hitting the address book mutex on every request.
65const PEER_METRICS_REFRESH_INTERVAL: Duration = Duration::from_secs(5);
66
67const METHOD_NOT_ALLOWED_MSG: &str = "method not allowed";
68const NOT_FOUND_MSG: &str = "not found";
69
70/// The maximum number of requests that will be handled in a given time interval before requests are
71/// dropped. Each connection serves one request, so this also limits new connections.
72const MAX_RECENT_REQUESTS: usize = 10_000;
73const RECENT_REQUEST_INTERVAL: Duration = Duration::from_secs(5);
74
75/// The maximum number of connections served at once. Connections past it are dropped, so the
76/// endpoint can't use up the file descriptors the node needs for peers and the database.
77const MAX_CONNECTIONS: usize = 32;
78
79/// How long a client has to send its request headers before the server closes the connection.
80const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(5);
81
82#[derive(Clone)]
83struct HealthCtx<SyncStatus>
84where
85    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
86{
87    config: Config,
88    network: Network,
89    chain_tip_metrics_receiver: watch::Receiver<ChainTipMetrics>,
90    sync_status: SyncStatus,
91    num_live_peer_receiver: watch::Receiver<usize>,
92}
93
94/// Chain tip measurements that `/ready` checks.
95#[derive(Debug, Clone, PartialEq, Eq, new)]
96pub struct ChainTipMetrics {
97    /// Last time the chain tip height increased.
98    pub last_chain_tip_grow_time: Instant,
99    /// Estimated blocks behind the network tip when Zebra started waiting for its latest block.
100    pub blocks_behind_at_tip_growth: Option<i64>,
101}
102
103impl ChainTipMetrics {
104    /// Creates a new watch channel for reporting [`ChainTipMetrics`].
105    pub fn channel() -> (watch::Sender<Self>, watch::Receiver<Self>) {
106        watch::channel(Self {
107            last_chain_tip_grow_time: Instant::now(),
108            blocks_behind_at_tip_growth: None,
109        })
110    }
111}
112
113/// Starts the health server if `listen_addr` is configured.
114///
115/// Returns a task handle and the bound socket address. When disabled, returns a
116/// pending task and `None` for the address.
117///
118/// The server accepts HTTP/1.1 requests on a dedicated TCP listener and serves
119/// two endpoints: `/healthy` and `/ready`.
120///
121/// # Panics
122///
123/// - If the configured `listen_addr` cannot be bound.
124pub async fn init<AddressBook, SyncStatus>(
125    config: Config,
126    network: Network,
127    chain_tip_metrics_receiver: watch::Receiver<ChainTipMetrics>,
128    sync_status: SyncStatus,
129    address_book: AddressBook,
130) -> (JoinHandle<()>, Option<SocketAddr>)
131where
132    AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
133    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
134{
135    let Some(listen_addr) = config.listen_addr else {
136        return (tokio::spawn(std::future::pending()), None);
137    };
138
139    info!("opening health endpoint at {listen_addr}...",);
140
141    let listener = tokio::net::TcpListener::bind(listen_addr)
142            .await
143            .unwrap_or_else(|e| panic!("Opening health endpoint listener {listen_addr:?} failed: {e:?}. Hint: Check if another zebrad is running, or change the health listen_addr in the config."));
144
145    let local = listener.local_addr().unwrap_or_else(|err| {
146        tracing::warn!(?err, "failed to read local addr from TcpListener");
147        listen_addr
148    });
149
150    info!("opened health endpoint at {}", local);
151
152    let (num_live_peer_sender, num_live_peer_receiver) = watch::channel(0);
153
154    // Seed the watch channel with the first snapshot so early requests see
155    // a consistent view even before the refresher loop has ticked.
156    if let Some(metrics) = num_live_peers(&address_book).await {
157        let _ = num_live_peer_sender.send(metrics);
158    }
159
160    // Refresh metrics in the background using a watch channel so request
161    // handlers can read the latest snapshot without taking locks.
162    let metrics_task = tokio::spawn(peer_metrics_refresh_task(
163        address_book.clone(),
164        num_live_peer_sender,
165    ));
166
167    let shared = Arc::new(HealthCtx {
168        config,
169        network,
170        chain_tip_metrics_receiver,
171        sync_status,
172        num_live_peer_receiver,
173    });
174
175    let server_task = tokio::spawn(run_health_server(listener, shared));
176
177    // Keep both async tasks tied to a single JoinHandle so shutdown and
178    // abort semantics mirror other components.
179    let task = tokio::spawn(async move {
180        tokio::select! {
181            _ = metrics_task => {},
182            _ = server_task => {},
183        }
184    });
185
186    (task, Some(local))
187}
188
189async fn handle_request<SyncStatus>(
190    req: Request<Incoming>,
191    ctx: Arc<HealthCtx<SyncStatus>>,
192) -> Result<Response<Full<Bytes>>, Infallible>
193where
194    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
195{
196    // Hyper is already lightweight, but we still fence non-GET methods to keep
197    // these endpoints deterministic for probes.
198    if req.method() != Method::GET {
199        return Ok(simple_response(
200            StatusCode::METHOD_NOT_ALLOWED,
201            METHOD_NOT_ALLOWED_MSG,
202        ));
203    }
204
205    let path = req.uri().path();
206    let response = match path {
207        "/healthy" => healthy(&ctx).await,
208        "/ready" => ready(&ctx).await,
209        _ => simple_response(StatusCode::NOT_FOUND, NOT_FOUND_MSG),
210    };
211
212    Ok(response)
213}
214
215// Liveness: ensure we still have the configured minimum of recently live peers,
216// matching historical behaviour but fed from the cached snapshot to avoid
217// mutex contention.
218async fn healthy<SyncStatus>(ctx: &HealthCtx<SyncStatus>) -> Response<Full<Bytes>>
219where
220    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
221{
222    if *ctx.num_live_peer_receiver.borrow() >= ctx.config.min_connected_peers {
223        simple_response(StatusCode::OK, "ok")
224    } else {
225        simple_response(StatusCode::SERVICE_UNAVAILABLE, "insufficient peers")
226    }
227}
228
229// Readiness: combine peer availability, sync progress, estimated lag, and tip
230// freshness to avoid the false positives called out in issue #4649 and the
231// implementation plan.
232async fn ready<SyncStatus>(ctx: &HealthCtx<SyncStatus>) -> Response<Full<Bytes>>
233where
234    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
235{
236    if !ctx.config.enforce_on_test_networks && ctx.network.is_a_test_network() {
237        return simple_response(StatusCode::OK, "ok");
238    }
239
240    if *ctx.num_live_peer_receiver.borrow() < ctx.config.min_connected_peers {
241        return simple_response(StatusCode::SERVICE_UNAVAILABLE, "insufficient peers");
242    }
243
244    // Keep the historical sync-gate but feed it with the richer readiness
245    // checks so we respect the plan's "ensure recent block commits" item.
246    if !ctx.sync_status.is_close_to_tip() {
247        return simple_response(StatusCode::SERVICE_UNAVAILABLE, "syncing");
248    }
249
250    let ChainTipMetrics {
251        last_chain_tip_grow_time,
252        blocks_behind_at_tip_growth,
253    } = ctx.chain_tip_metrics_receiver.borrow().clone();
254
255    let Some(blocks_behind) = blocks_behind_at_tip_growth else {
256        tracing::warn!("syncer is getting block hashes from peers, but state is empty");
257        return simple_response(StatusCode::SERVICE_UNAVAILABLE, "no tip");
258    };
259
260    let tip_age = last_chain_tip_grow_time.elapsed();
261    if tip_age > ctx.config.ready_max_tip_age {
262        return simple_response(
263            StatusCode::SERVICE_UNAVAILABLE,
264            &format!("tip_age={}s", tip_age.as_secs()),
265        );
266    }
267
268    if blocks_behind <= ctx.config.ready_max_blocks_behind {
269        simple_response(StatusCode::OK, "ok")
270    } else {
271        simple_response(
272            StatusCode::SERVICE_UNAVAILABLE,
273            &format!("lag={blocks_behind} blocks"),
274        )
275    }
276}
277
278// Measure peers on a blocking thread, mirroring the previous synchronous
279// implementation but without holding the mutex on the request path.
280async fn num_live_peers<A>(address_book: &A) -> Option<usize>
281where
282    A: AddressBookPeers + Clone + Send + Sync + 'static,
283{
284    let address_book = address_book.clone();
285    tokio::task::spawn_blocking(move || address_book.recently_live_peers(Utc::now()).len())
286        .await
287        .inspect_err(|err| warn!(?err, "failed to refresh peer metrics"))
288        .ok()
289}
290
291// Periodically update the cached peer metrics for all handlers that hold a
292// receiver. If receivers disappear we exit quietly so shutdown can proceed.
293async fn peer_metrics_refresh_task<A>(address_book: A, num_live_peer_sender: watch::Sender<usize>)
294where
295    A: AddressBookPeers + Clone + Send + Sync + 'static,
296{
297    let mut interval = time::interval(PEER_METRICS_REFRESH_INTERVAL);
298    interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
299
300    loop {
301        // Updates are best-effort: if the snapshot fails or all receivers are
302        // dropped we exit quietly, letting the caller terminate the health task.
303        if let Some(metrics) = num_live_peers(&address_book).await {
304            if let Err(err) = num_live_peer_sender.send(metrics) {
305                tracing::warn!(?err, "failed to send to peer metrics channel");
306                break;
307            }
308        }
309
310        interval.tick().await;
311    }
312}
313
314/// Checks the request limit, reading the clock only after the counter reaches the limit.
315fn allow_request(
316    num_recent_requests: &mut usize,
317    last_request_count_reset_time: &mut Instant,
318    now: impl FnOnce() -> Instant,
319) -> bool {
320    if *num_recent_requests < MAX_RECENT_REQUESTS {
321        *num_recent_requests += 1;
322        return true;
323    }
324
325    let now = now();
326    if now.duration_since(*last_request_count_reset_time) > RECENT_REQUEST_INTERVAL {
327        *num_recent_requests = 0;
328        *last_request_count_reset_time = now;
329        true
330    } else {
331        false
332    }
333}
334
335async fn run_health_server<SyncStatus>(
336    listener: tokio::net::TcpListener,
337    shared: Arc<HealthCtx<SyncStatus>>,
338) where
339    SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
340{
341    let mut num_recent_requests: usize = 0;
342    let mut last_request_count_reset_time = Instant::now();
343    let connections = Arc::new(Semaphore::new(MAX_CONNECTIONS));
344
345    // Dedicated accept loop to keep request handling small and predictable; we
346    // still spawn per-connection tasks but share the context clone.
347
348    loop {
349        match listener.accept().await {
350            Ok((stream, _)) => {
351                // Drop the connection if too many connections are open.
352                let Ok(permit) = connections.clone().try_acquire_owned() else {
353                    continue;
354                };
355
356                if !allow_request(
357                    &mut num_recent_requests,
358                    &mut last_request_count_reset_time,
359                    Instant::now,
360                ) {
361                    // Drop the request if there have been too many recent requests.
362                    continue;
363                }
364
365                let io = TokioIo::new(stream);
366                let svc_ctx = shared.clone();
367                let service =
368                    hyper::service::service_fn(move |req| handle_request(req, svc_ctx.clone()));
369
370                tokio::spawn(async move {
371                    // Serving one request per connection makes the request limit count requests.
372                    let result = http1::Builder::new()
373                        .keep_alive(false)
374                        .timer(TokioTimer::new())
375                        .header_read_timeout(HEADER_READ_TIMEOUT)
376                        .serve_connection(io, service)
377                        .await;
378                    drop(permit);
379
380                    if let Err(err) = result {
381                        debug!(?err, "health server connection closed with error");
382                    }
383                });
384            }
385            Err(err) => {
386                warn!(?err, "health server accept failed");
387            }
388        }
389    }
390}
391
392fn simple_response(status: StatusCode, body: &str) -> Response<Full<Bytes>> {
393    let bytes = Bytes::from(body.to_string());
394    let len = bytes.len();
395    ResponseBuilder::new()
396        .status(status)
397        .header(CONTENT_TYPE, "text/plain; charset=utf-8")
398        .header(CONTENT_LENGTH, len.to_string())
399        .body(Full::new(bytes))
400        .expect("valid response")
401}