forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

service_probe.rs135 lines, 5.5 KiBHistoryRawDownload
1//! The health probe worker (contracts.md 4): every minute it asks each listed service for `GET /healthz`
2//! and records the answer in that service's row of the `services` table.
3//!
4//! - A probe is a plain GET of `<origin>/healthz`. Redirects are not followed, so a `301` from a service is
5//! a failure. The answer is healthy only when its status is `200`. At most [`BODY_LIMIT`] bytes of the
6//! body are read, and they are discarded.
7//! - A probe has [`PROBE_TIMEOUT`] to finish, from connect to the end of the body. A service that does not
8//! answer in time is down.
9//! - Only `http` and `https` origins are probed. Any other origin is recorded as down.
10//! - im's own row (key `im`) is not probed: im is answering this very round, so it is recorded as healthy.
11//! - The rows are probed a few at a time ([`PROBE_CONCURRENCY`]), so one slow service does not hold up the
12//! others. Each row is recorded as soon as its own probe is done.
13//!
14//! The list is read again at every round, so a service the admin adds or removes is picked up within a minute.
15//! Nothing here fails the server: a store error or a failed probe is logged, and the next round tries again.
16
17use std::time::Duration;
18
19use futures_util::{StreamExt, stream};
20use im_core::model::Service;
21use im_core::store::Store;
22use im_core::time::now_stamp;
23use reqwest::{StatusCode, Url};
24use tokio::sync::watch;
25use tokio::task::JoinHandle;
26
27/// The key of im's own row. im is never probed over HTTP: its answer is known.
28const HOME_KEY: &str = "im";
29
30/// The time between two rounds (contracts.md 4: every 60 seconds).
31const EVERY: Duration = Duration::from_secs(60);
32
33/// How long a service has to answer one probe (contracts.md 4: 2 seconds).
34pub const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
35
36/// The most body bytes read from a probe answer. Only the status decides, so the body is read to drain it
37/// and then discarded.
38const BODY_LIMIT: usize = 256;
39
40/// How many probes run at once.
41const PROBE_CONCURRENCY: usize = 8;
42
43/// Starts the worker. It runs one round at boot and then every [`EVERY`], until `stop` is set.
44pub fn spawn(store: Store, mut stop: watch::Receiver<bool>) -> JoinHandle<()> {
45 tokio::spawn(async move {
46 let http = probe_client();
47 loop {
48 round(&store, &http).await;
49 tokio::select! {
50 () = tokio::time::sleep(EVERY) => {}
51 _ = stop.wait_for(|stopped| *stopped) => return,
52 }
53 }
54 })
55}
56
57/// The HTTP client of the probes: two-second timeouts and no redirects.
58fn probe_client() -> reqwest::Client {
59 reqwest::Client::builder()
60 .redirect(reqwest::redirect::Policy::none())
61 .timeout(PROBE_TIMEOUT)
62 .connect_timeout(PROBE_TIMEOUT)
63 .build()
64 .expect("the probe HTTP client can be built with fixed settings")
65}
66
67/// One round: im's own row is recorded as healthy, and every other row is probed and recorded.
68/// Failures are logged per row.
69pub async fn round(store: &Store, http: &reqwest::Client) {
70 let services = match store.list_services().await {
71 Ok(services) => services,
72 Err(error) => {
73 tracing::error!(error = %error, "service probes: cannot list the services");
74 return;
75 }
76 };
77 if let Err(error) = store.record_health(HOME_KEY, true, &now_stamp()).await {
78 tracing::error!(error = %error, "service probes: cannot record im's own health");
79 }
80 // The probes are built in a loop and polled `PROBE_CONCURRENCY` at a time, as the back-channel worker does.
81 let mut pending = Vec::with_capacity(services.len());
82 for service in &services {
83 if service.key != HOME_KEY {
84 pending.push(probe_and_record(store, http, service));
85 }
86 }
87 stream::iter(pending)
88 .buffer_unordered(PROBE_CONCURRENCY)
89 .collect::<Vec<()>>()
90 .await;
91}
92
93/// Probes one row and records the answer with the time it was recorded.
94async fn probe_and_record(store: &Store, http: &reqwest::Client, service: &Service) {
95 let healthy = probe(http, &service.key, &service.url).await;
96 if let Err(error) = store
97 .record_health(&service.key, healthy, &now_stamp())
98 .await
99 {
100 tracing::error!(service = %service.key, error = %error, "service probes: cannot record the answer");
101 }
102}
103
104/// True when `origin` is an http or https origin whose `/healthz` answers `200` within the timeout.
105async fn probe(http: &reqwest::Client, key: &str, origin: &str) -> bool {
106 let parsed = match Url::parse(origin) {
107 Ok(url) if matches!(url.scheme(), "http" | "https") => url,
108 _ => {
109 tracing::warn!(service = %key, "service probes: the origin is not an http or https address");
110 return false;
111 }
112 };
113 let target = format!("{}/healthz", parsed.as_str().trim_end_matches('/'));
114 let mut response = match http.get(&target).send().await {
115 Ok(response) => response,
116 Err(error) => {
117 tracing::warn!(service = %key, error = %error.without_url(), "service probe failed");
118 return false;
119 }
120 };
121 let healthy = response.status() == StatusCode::OK;
122 // Drain the body up to the limit so the connection can be reused. The last chunk may pass the limit;
123 // it is discarded either way.
124 let mut read = 0;
125 while read < BODY_LIMIT {
126 match response.chunk().await {
127 Ok(Some(chunk)) => read += chunk.len(),
128 _ => break,
129 }
130 }
131 if !healthy {
132 tracing::warn!(service = %key, status = %response.status(), "service probe answered unhealthy");
133 }
134 healthy
135}