1mod 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
63const 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
70const MAX_RECENT_REQUESTS: usize = 10_000;
73const RECENT_REQUEST_INTERVAL: Duration = Duration::from_secs(5);
74
75const MAX_CONNECTIONS: usize = 32;
78
79const 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#[derive(Debug, Clone, PartialEq, Eq, new)]
96pub struct ChainTipMetrics {
97 pub last_chain_tip_grow_time: Instant,
99 pub blocks_behind_at_tip_growth: Option<i64>,
101}
102
103impl ChainTipMetrics {
104 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
113pub 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 if let Some(metrics) = num_live_peers(&address_book).await {
157 let _ = num_live_peer_sender.send(metrics);
158 }
159
160 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 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 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
215async 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
229async 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 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
278async 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
291async 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 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
314fn 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 loop {
349 match listener.accept().await {
350 Ok((stream, _)) => {
351 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 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 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}