Skip to content

Commit

Permalink
feat(http-server): add health check and version endpoints (#33)
Browse files Browse the repository at this point in the history
Description
---
We need to have a health check and version endpoint for easier
deployments.
New endpoints:
- `http://127.0.0.1:19000/health`
- `http://127.0.0.1:19000/version`

Motivation and Context
---

How Has This Been Tested?
---

What process can a PR reviewer use to test or verify this change?
---

<!-- Checklist -->
<!-- 1. Is the title of your PR in the form that would make nice release
notes? The title, excluding the conventional commit
tag, will be included exactly as is in the CHANGELOG, so please think
about it carefully. -->


Breaking Changes
---

- [x] None
- [ ] Requires data directory on base node to be deleted
- [ ] Requires hard fork
- [ ] Other - Please specify

<!-- Does this include a breaking change? If so, include this line as a
footer -->
<!-- BREAKING CHANGE: Description what the user should do, e.g. delete a
database, resync the chain -->
  • Loading branch information
ksrichard authored Aug 22, 2024
1 parent 92d2bb9 commit 7b57c1b
Show file tree
Hide file tree
Showing 15 changed files with 58 additions and 37 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sha_p2pool"
version = "0.1.3"
version = "0.1.4-pre.0"
edition = "2021"

[dependencies]
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@ How to use
Please note that `18145` is the port where `base node's gRPC` is running, so if it is different from the default
one (`18145`)
just use the right port.
- Start sha p2pool by running the binary simple `$ ./sha_p2pool` or using `Cargo` (if installed and want to build from
- Start sha p2pool by running the binary simple `$ ./sha_p2pool start` or using `Cargo` (if installed and want to build
from
source):
`$ cargo build --release && ./target/release/sha_p2pool`
`$ cargo build --release && ./target/release/sha_p2pool start`

**Note:** For more information about usage of p2pool, just run `$ sha_p2pool --help`!

8 changes: 4 additions & 4 deletions src/cli/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ pub struct StartArgs {
#[arg(long, value_name = "mdns-disabled", default_value_t = false)]
pub mdns_disabled: bool,

/// Stats server disabled
/// HTTP server disabled
///
/// If set, local stats HTTP server is disabled.
#[arg(long, value_name = "stats-server-disabled", default_value_t = false)]
pub stats_server_disabled: bool,
/// If set, local HTTP server (stats, health-check, status etc...) is disabled.
#[arg(long, value_name = "http-server-disabled", default_value_t = false)]
pub http_server_disabled: bool,
}

#[derive(Subcommand, Clone, Debug)]
Expand Down
2 changes: 1 addition & 1 deletion src/cli/commands/list_tribes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub async fn handle_list_tribes(
let cli_ref = cli.clone();
let mut args_clone = args.clone();
args_clone.mining_disabled = true;
args_clone.stats_server_disabled = true;
args_clone.http_server_disabled = true;
let mut shutdown = Shutdown::new();
let shutdown_signal = shutdown.to_signal();
let (peer_store_channel_tx, peer_store_channel_rx) = oneshot::channel::<Arc<PeerStore>>();
Expand Down
2 changes: 1 addition & 1 deletion src/cli/commands/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub async fn server(

config_builder.with_mining_enabled(!args.mining_disabled);
config_builder.with_mdns_enabled(!args.mdns_disabled);
config_builder.with_stats_server_enabled(!args.stats_server_disabled);
config_builder.with_http_server_enabled(!args.http_server_disabled);
if let Some(stats_server_port) = args.stats_server_port {
config_builder.with_stats_server_port(stats_server_port);
}
Expand Down
13 changes: 6 additions & 7 deletions src/server/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ use std::{path::PathBuf, time::Duration};

use libp2p::identity::Keypair;

use crate::server::http::stats;
use crate::server::p2p::Tribe;
use crate::server::{p2p, p2p::peer_store::PeerStoreConfig};
use crate::server::{http, p2p, p2p::peer_store::PeerStoreConfig};

/// Config is the server configuration struct.
#[derive(Clone)]
Expand All @@ -19,7 +18,7 @@ pub struct Config {
pub peer_store: PeerStoreConfig,
pub p2p_service: p2p::Config,
pub mining_enabled: bool,
pub stats_server: stats::server::Config,
pub http_server: http::server::Config,
}

impl Default for Config {
Expand All @@ -32,7 +31,7 @@ impl Default for Config {
peer_store: PeerStoreConfig::default(),
p2p_service: p2p::Config::default(),
mining_enabled: true,
stats_server: stats::server::Config::default(),
http_server: http::server::Config::default(),
}
}
}
Expand Down Expand Up @@ -111,13 +110,13 @@ impl ConfigBuilder {
self
}

pub fn with_stats_server_enabled(&mut self, config: bool) -> &mut Self {
self.config.stats_server.enabled = config;
pub fn with_http_server_enabled(&mut self, config: bool) -> &mut Self {
self.config.http_server.enabled = config;
self
}

pub fn with_stats_server_port(&mut self, config: u16) -> &mut Self {
self.config.stats_server.port = config;
self.config.http_server.port = config;
self
}

Expand Down
20 changes: 9 additions & 11 deletions src/server/grpc/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use minotari_app_grpc::tari_rpc::base_node_client::BaseNodeClient;
use minotari_node_grpc_client::BaseNodeGrpcClient;
use tari_shutdown::ShutdownSignal;
use tokio::select;
use tokio::time::sleep;
use tonic::transport::Channel;

use crate::server::grpc::error::{Error, TonicError};
Expand All @@ -26,22 +25,21 @@ pub async fn connect_base_node(
Err(error) => {
error!("[Retry] Failed to connect to Tari base node: {:?}", error.to_string());
let mut client = None;
let mut retry_interval = tokio::time::interval(Duration::from_secs(5));
tokio::pin!(shutdown_signal);
while client.is_none() {
sleep(Duration::from_secs(5)).await;
match BaseNodeGrpcClient::connect(base_node_address.clone())
.await
.map_err(|e| Error::Tonic(TonicError::Transport(e)))
{
Ok(curr_client) => client = Some(curr_client),
Err(error) => error!("[Retry] Failed to connect to Tari base node: {:?}", error.to_string()),
}
select! {
() = &mut shutdown_signal => {
return Err(Error::Shutdown);
}
else => {
continue;
_ = retry_interval.tick() => {
match BaseNodeGrpcClient::connect(base_node_address.clone())
.await
.map_err(|e| Error::Tonic(TonicError::Transport(e)))
{
Ok(curr_client) => client = Some(curr_client),
Err(error) => error!("[Retry] Failed to connect to Tari base node: {:?}", error.to_string()),
}
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions src/server/http/health.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright 2024 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

use axum::http::StatusCode;

pub async fn handle_health() -> Result<StatusCode, StatusCode> {
Ok(StatusCode::OK)
}
3 changes: 3 additions & 0 deletions src/server/http/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// Copyright 2024 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

mod health;
pub mod server;
pub mod stats;
mod version;
7 changes: 5 additions & 2 deletions src/server/http/stats/server.rs → src/server/http/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use thiserror::Error;
use tokio::io;

use crate::server::http::stats::handlers;
use crate::server::http::{health, version};
use crate::server::p2p::peer_store::PeerStore;
use crate::server::p2p::Tribe;
use crate::server::stats_store::StatsStore;
Expand Down Expand Up @@ -39,7 +40,7 @@ pub enum Error {
IO(#[from] io::Error),
}

pub struct StatsServer<S>
pub struct HttpServer<S>
where
S: ShareChain,
{
Expand All @@ -59,7 +60,7 @@ pub struct AppState {
pub tribe: Tribe,
}

impl<S> StatsServer<S>
impl<S> HttpServer<S>
where
S: ShareChain,
{
Expand All @@ -85,6 +86,8 @@ where
pub fn routes(&self) -> Router {
Router::new()
.route("/stats", get(handlers::handle_get_stats))
.route("/health", get(health::handle_health))
.route("/version", get(version::handle_version))
.with_state(AppState {
share_chain: self.share_chain.clone(),
peer_store: self.peer_store.clone(),
Expand Down
2 changes: 1 addition & 1 deletion src/server/http/stats/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ use tari_core::consensus::ConsensusManager;
use tari_core::transactions::tari_amount::MicroMinotari;
use tari_utilities::epoch_time::EpochTime;

use crate::server::http::server::AppState;
use crate::server::http::stats::models::{BlockStats, EstimatedEarnings, Stats, TribeDetails};
use crate::server::http::stats::server::AppState;
use crate::server::http::stats::{
MINER_STAT_ACCEPTED_BLOCKS_COUNT, MINER_STAT_REJECTED_BLOCKS_COUNT, P2POOL_STAT_ACCEPTED_BLOCKS_COUNT,
P2POOL_STAT_REJECTED_BLOCKS_COUNT,
Expand Down
1 change: 0 additions & 1 deletion src/server/http/stats/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,3 @@ pub const P2POOL_STAT_REJECTED_BLOCKS_COUNT: &str = "p2pool_rejected_blocks_coun

pub mod handlers;
pub mod models;
pub mod server;
10 changes: 10 additions & 0 deletions src/server/http/version.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright 2024 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause

use axum::http::StatusCode;

const VERSION: &str = env!("CARGO_PKG_VERSION");

pub async fn handle_version() -> Result<String, StatusCode> {
Ok(VERSION.to_string())
}
10 changes: 5 additions & 5 deletions src/server/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use minotari_app_grpc::tari_rpc::{base_node_server::BaseNodeServer, sha_p2_pool_
use tari_shutdown::ShutdownSignal;
use thiserror::Error;

use crate::server::http::stats::server::StatsServer;
use crate::server::http::server::HttpServer;
use crate::server::p2p::peer_store::PeerStore;
use crate::server::stats_store::StatsStore;
use crate::{
Expand Down Expand Up @@ -46,7 +46,7 @@ where
p2p_service: p2p::Service<S>,
base_node_grpc_service: Option<BaseNodeServer<TariBaseNodeGrpc>>,
p2pool_grpc_service: Option<ShaP2PoolServer<ShaP2PoolGrpc<S>>>,
stats_server: Option<Arc<StatsServer<S>>>,
stats_server: Option<Arc<HttpServer<S>>>,
shutdown_signal: ShutdownSignal,
}

Expand Down Expand Up @@ -93,12 +93,12 @@ where
p2pool_server = Some(ShaP2PoolServer::new(p2pool_grpc_service));
}

let stats_server = if config.stats_server.enabled {
Some(Arc::new(StatsServer::new(
let stats_server = if config.http_server.enabled {
Some(Arc::new(HttpServer::new(
share_chain.clone(),
tribe_peer_store.clone(),
stats_store.clone(),
config.stats_server.port,
config.http_server.port,
config.p2p_service.tribe.clone(),
shutdown_signal.clone(),
)))
Expand Down

0 comments on commit 7b57c1b

Please sign in to comment.