1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::sync::Arc;

use axum::{
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use parking_lot::RwLock;

use crate::{
    chain_sync::SyncState, db::SettingsStore, libp2p::PeerManager, networks::ChainConfig, Config,
};

mod endpoints;

/// Default listening port for the healthcheck server.
pub const DEFAULT_HEALTHCHECK_PORT: u16 = 2346;

/// State shared between the healthcheck server and the main application.
pub(crate) struct ForestState {
    pub config: Config,
    pub chain_config: Arc<ChainConfig>,
    pub genesis_timestamp: u64,
    pub sync_state: Arc<RwLock<SyncState>>,
    pub peer_manager: Arc<PeerManager>,
    pub settings_store: Arc<dyn SettingsStore + Sync + Send>,
}

/// Initializes the healthcheck server. The server listens on the address specified in the
/// configuration (passed via state) and responds to the following endpoints:
/// - `[endpoints::healthz]`
/// - `[endpoints::readyz]`
/// - `[endpoints::livez]`
///
/// All endpoints accept an optional `verbose` query parameter. If present, the response will include detailed information about the checks performed.
pub(crate) async fn init_healthcheck_server(
    forest_state: ForestState,
    tcp_listener: tokio::net::TcpListener,
) -> anyhow::Result<()> {
    let healthcheck_service = Router::new()
        .route("/healthz", get(endpoints::healthz))
        .route("/readyz", get(endpoints::readyz))
        .route("/livez", get(endpoints::livez))
        .with_state(forest_state.into());

    axum::serve(tcp_listener, healthcheck_service).await?;
    Ok(())
}

/// Simple error wrapper for the healthcheck server
struct AppError(anyhow::Error);

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        (http::StatusCode::SERVICE_UNAVAILABLE, self.0.to_string()).into_response()
    }
}

#[cfg(test)]
mod test {
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};

    use crate::db::SettingsExt;
    use crate::{
        blocks::{CachingBlockHeader, Tipset},
        chain_sync::SyncStage,
        Client,
    };

    use itertools::Either;
    use reqwest::StatusCode;

    use super::*;

    #[tokio::test]
    async fn test_check_readyz() {
        let healthcheck_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
        let rpc_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();

        let sync_state = Arc::new(RwLock::new(SyncState::default()));

        let db = Arc::new(crate::db::MemoryDB::default());

        let forest_state = ForestState {
            config: Config {
                client: Client {
                    healthcheck_address,
                    rpc_address: rpc_listener.local_addr().unwrap(),
                    ..Default::default()
                },
                ..Default::default()
            },
            chain_config: Arc::new(ChainConfig::default()),
            genesis_timestamp: 0,
            sync_state: sync_state.clone(),
            peer_manager: Arc::new(PeerManager::default()),
            settings_store: db.clone(),
        };

        let listener =
            tokio::net::TcpListener::bind(forest_state.config.client.healthcheck_address)
                .await
                .unwrap();
        let healthcheck_port = listener.local_addr().unwrap().port();

        tokio::spawn(async move {
            init_healthcheck_server(forest_state, listener)
                .await
                .unwrap();
        });

        let call_healthcheck = |verbose| {
            reqwest::get(format!(
                "http://localhost:{}/readyz{}",
                healthcheck_port,
                if verbose { "?verbose" } else { "" }
            ))
        };

        // instrument the state so that the ready requirements are met
        sync_state.write().set_epoch(i64::MAX);
        sync_state.write().set_stage(SyncStage::Complete);

        db.set_eth_mapping_up_to_date().unwrap();

        assert_eq!(
            call_healthcheck(false).await.unwrap().status(),
            StatusCode::OK
        );
        let response = call_healthcheck(true).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let text = response.text().await.unwrap();
        assert!(text.contains("[+] sync complete"));
        assert!(text.contains("[+] epoch up to date"));
        assert!(text.contains("[+] rpc server running"));
        assert!(text.contains("[+] eth mapping up to date"));

        // instrument the state so that the ready requirements are not met
        drop(rpc_listener);
        sync_state.write().set_stage(SyncStage::Error);
        sync_state.write().set_epoch(0);

        assert_eq!(
            call_healthcheck(false).await.unwrap().status(),
            StatusCode::SERVICE_UNAVAILABLE
        );
        let response = call_healthcheck(true).await.unwrap();
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);

        let text = response.text().await.unwrap();
        assert!(text.contains("[!] sync incomplete"));
        assert!(text.contains("[!] epoch outdated"));
        assert!(text.contains("[!] rpc server not running"));
        assert!(text.contains("[+] eth mapping up to date"));
    }

    #[tokio::test]
    async fn test_check_livez() {
        let healthcheck_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);

        let sync_state = Arc::new(RwLock::new(SyncState::default()));
        let peer_manager = Arc::new(PeerManager::default());
        let db = Arc::new(crate::db::MemoryDB::default());
        let forest_state = ForestState {
            config: Config {
                client: Client {
                    healthcheck_address,
                    ..Default::default()
                },
                ..Default::default()
            },
            chain_config: Arc::new(ChainConfig::default()),
            genesis_timestamp: 0,
            sync_state: sync_state.clone(),
            peer_manager: peer_manager.clone(),
            settings_store: db,
        };

        let listener =
            tokio::net::TcpListener::bind(forest_state.config.client.healthcheck_address)
                .await
                .unwrap();
        let healthcheck_port = listener.local_addr().unwrap().port();

        tokio::spawn(async move {
            init_healthcheck_server(forest_state, listener)
                .await
                .unwrap();
        });

        let call_healthcheck = |verbose| {
            reqwest::get(format!(
                "http://localhost:{}/livez{}",
                healthcheck_port,
                if verbose { "?verbose" } else { "" }
            ))
        };

        // instrument the state so that the live requirements are met
        sync_state.write().set_stage(SyncStage::Headers);
        let peer = libp2p::PeerId::random();
        peer_manager.update_peer_head(
            peer,
            Either::Right(Arc::new(
                Tipset::new(vec![CachingBlockHeader::default()]).unwrap(),
            )),
        );

        assert_eq!(
            call_healthcheck(false).await.unwrap().status(),
            StatusCode::OK
        );

        let response = call_healthcheck(true).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let text = response.text().await.unwrap();
        assert!(text.contains("[+] sync ok"));
        assert!(text.contains("[+] peers connected"));

        // instrument the state so that the live requirements are not met
        sync_state.write().set_stage(SyncStage::Error);
        peer_manager.remove_peer(&peer);

        assert_eq!(
            call_healthcheck(false).await.unwrap().status(),
            StatusCode::SERVICE_UNAVAILABLE
        );

        let response = call_healthcheck(true).await.unwrap();
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let text = response.text().await.unwrap();
        assert!(text.contains("[!] sync error"));
        assert!(text.contains("[!] no peers connected"));
    }

    #[tokio::test]
    async fn test_check_healthz() {
        let healthcheck_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
        let rpc_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let peer_manager = Arc::new(PeerManager::default());
        let db = Arc::new(crate::db::MemoryDB::default());

        let sync_state = Arc::new(RwLock::new(SyncState::default()));
        let forest_state = ForestState {
            config: Config {
                client: Client {
                    healthcheck_address,
                    rpc_address: rpc_listener.local_addr().unwrap(),
                    ..Default::default()
                },
                ..Default::default()
            },
            chain_config: Arc::new(ChainConfig::default()),
            genesis_timestamp: 0,
            sync_state: sync_state.clone(),
            peer_manager: peer_manager.clone(),
            settings_store: db,
        };

        let listener =
            tokio::net::TcpListener::bind(forest_state.config.client.healthcheck_address)
                .await
                .unwrap();
        let healthcheck_port = listener.local_addr().unwrap().port();

        tokio::spawn(async move {
            init_healthcheck_server(forest_state, listener)
                .await
                .unwrap();
        });

        let call_healthcheck = |verbose| {
            reqwest::get(format!(
                "http://localhost:{}/healthz{}",
                healthcheck_port,
                if verbose { "?verbose" } else { "" }
            ))
        };

        // instrument the state so that the health requirements are met
        sync_state.write().set_epoch(i64::MAX);
        sync_state.write().set_stage(SyncStage::Headers);
        let peer = libp2p::PeerId::random();
        peer_manager.update_peer_head(
            peer,
            Either::Right(Arc::new(
                Tipset::new(vec![CachingBlockHeader::default()]).unwrap(),
            )),
        );

        assert_eq!(
            call_healthcheck(false).await.unwrap().status(),
            StatusCode::OK
        );
        let response = call_healthcheck(true).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let text = response.text().await.unwrap();
        assert!(text.contains("[+] sync ok"));
        assert!(text.contains("[+] epoch up to date"));
        assert!(text.contains("[+] rpc server running"));
        assert!(text.contains("[+] peers connected"));

        // instrument the state so that the health requirements are not met
        drop(rpc_listener);
        sync_state.write().set_stage(SyncStage::Error);
        sync_state.write().set_epoch(0);
        peer_manager.remove_peer(&peer);

        assert_eq!(
            call_healthcheck(false).await.unwrap().status(),
            StatusCode::SERVICE_UNAVAILABLE
        );
        let response = call_healthcheck(true).await.unwrap();
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);

        let text = response.text().await.unwrap();
        assert!(text.contains("[!] sync error"));
        assert!(text.contains("[!] epoch outdated"));
        assert!(text.contains("[!] rpc server not running"));
        assert!(text.contains("[!] no peers connected"));
    }

    #[tokio::test]
    async fn test_check_unknown_healthcheck_endpoint() {
        let healthcheck_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
        let forest_state = ForestState {
            config: Config {
                client: Client {
                    healthcheck_address,
                    ..Default::default()
                },
                ..Default::default()
            },
            chain_config: Arc::default(),
            genesis_timestamp: 0,
            sync_state: Arc::default(),
            peer_manager: Arc::default(),
            settings_store: Arc::new(crate::db::MemoryDB::default()),
        };
        let listener =
            tokio::net::TcpListener::bind(forest_state.config.client.healthcheck_address)
                .await
                .unwrap();
        let healthcheck_port = listener.local_addr().unwrap().port();

        tokio::spawn(async move {
            init_healthcheck_server(forest_state, listener)
                .await
                .unwrap();
        });

        let response = reqwest::get(format!(
            "http://localhost:{}/phngluimglwnafhcthulhurlyehwgahnaglfhtagn",
            healthcheck_port
        ))
        .await
        .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }
}