Skip to content

Commit

Permalink
feat(metrics): add UTXO set size to base node metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
sdbondi committed Mar 21, 2022
1 parent 7145201 commit 82d1d80
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 21 deletions.
30 changes: 25 additions & 5 deletions base_layer/core/src/base_node/comms_interface/inbound_handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use std::{
convert::TryFrom,
convert::{TryFrom, TryInto},
sync::Arc,
time::{Duration, Instant},
};
Expand Down Expand Up @@ -708,7 +708,7 @@ where B: BlockchainBackend + 'static
BlockAddResult::ChainReorg { .. } => true,
};

self.update_block_result_metrics(&block_add_result);
self.update_block_result_metrics(&block_add_result).await?;
self.publish_block_event(BlockEvent::ValidBlockAdded(block.clone(), block_add_result));

if should_propagate {
Expand Down Expand Up @@ -762,21 +762,41 @@ where B: BlockchainBackend + 'static
}
}

fn update_block_result_metrics(&self, block_add_result: &BlockAddResult) {
async fn update_block_result_metrics(&self, block_add_result: &BlockAddResult) -> Result<(), CommsInterfaceError> {
fn update_target_difficulty(block: &ChainBlock) {
match block.header().pow_algo() {
PowAlgorithm::Sha3 => {
metrics::target_difficulty_sha(block.height())
.set(i64::try_from(block.accumulated_data().target_difficulty.as_u64()).unwrap_or(i64::MAX));
},
PowAlgorithm::Monero => {
metrics::target_difficulty_monero(block.height())
.set(i64::try_from(block.accumulated_data().target_difficulty.as_u64()).unwrap_or(i64::MAX));
},
}
}

match block_add_result {
BlockAddResult::Ok(ref block) => {
metrics::target_difficulty(block.height())
.set(i64::try_from(block.accumulated_data().target_difficulty.as_u64()).unwrap_or(i64::MAX));
update_target_difficulty(block);
let utxo_set_size = self.blockchain_db.utxo_count().await?;
metrics::utxo_set_size().set(utxo_set_size.try_into().unwrap_or(i64::MAX));
},
BlockAddResult::ChainReorg { added, removed } => {
let fork_height = added.last().map(|b| b.height() - 1).unwrap_or_default();
metrics::reorg(fork_height, added.len(), removed.len()).inc();
for block in added {
update_target_difficulty(block);
}
let utxo_set_size = self.blockchain_db.utxo_count().await?;
metrics::utxo_set_size().set(utxo_set_size.try_into().unwrap_or(i64::MAX));
},
BlockAddResult::OrphanBlock => {
metrics::orphaned_blocks().inc();
},
_ => {},
}
Ok(())
}

async fn get_target_difficulty_for_next_block(
Expand Down
31 changes: 28 additions & 3 deletions base_layer/core/src/base_node/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,24 @@ use once_cell::sync::Lazy;
use tari_metrics::{IntCounter, IntCounterVec, IntGauge, IntGaugeVec};
use tari_utilities::hex::to_hex;

pub fn target_difficulty(height: u64) -> IntGauge {
pub fn target_difficulty_sha(height: u64) -> IntGauge {
static METER: Lazy<IntGaugeVec> = Lazy::new(|| {
tari_metrics::register_int_gauge_vec(
"base_node::blockchain::target_difficulty",
"The current miner target difficulty",
"base_node::blockchain::target_difficulty_sha",
"The current miner target difficulty for the sha3 PoW algo",
&["height"],
)
.unwrap()
});

METER.with_label_values(&[&height.to_string()])
}

pub fn target_difficulty_monero(height: u64) -> IntGauge {
static METER: Lazy<IntGaugeVec> = Lazy::new(|| {
tari_metrics::register_int_gauge_vec(
"base_node::blockchain::target_difficulty_monero",
"The current miner target difficulty for the monero PoW algo",
&["height"],
)
.unwrap()
Expand Down Expand Up @@ -116,3 +129,15 @@ pub fn active_sync_peers() -> IntGauge {

METER.clone()
}

pub fn utxo_set_size() -> IntGauge {
static METER: Lazy<IntGauge> = Lazy::new(|| {
tari_metrics::register_int_gauge(
"base_node::blockchain::utxo_set_size",
"The number of UTXOs in the current UTXO set",
)
.unwrap()
});

METER.clone()
}
2 changes: 2 additions & 0 deletions base_layer/core/src/chain_storage/async_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,8 @@ impl<B: BlockchainBackend + 'static> AsyncBlockchainDb<B> {
parent_public_key: PublicKey,
range: Range<usize>) -> Vec<UtxoMinedInfo>, "fetch_all_unspent_by_parent_public_key");

make_async_fn!(utxo_count() -> usize, "utxo_count");

//---------------------------------- Kernel --------------------------------------------//
make_async_fn!(fetch_kernel_by_excess_sig(excess_sig: Signature) -> Option<(TransactionKernel, HashOutput)>, "fetch_kernel_by_excess_sig");

Expand Down
6 changes: 6 additions & 0 deletions base_layer/core/src/chain_storage/blockchain_database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,12 @@ where B: BlockchainBackend
db.fetch_utxos_in_block(&hash, deleted.as_deref())
}

/// Returns the number of UTXOs in the current unspent set
pub fn utxo_count(&self) -> Result<usize, ChainStorageError> {
let db = self.db_read_access()?;
db.utxo_count()
}

/// Returns the block header at the given block height.
pub fn fetch_header(&self, height: u64) -> Result<Option<BlockHeader>, ChainStorageError> {
let db = self.db_read_access()?;
Expand Down
2 changes: 1 addition & 1 deletion base_layer/core/src/chain_storage/lmdb_db/lmdb_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2105,7 +2105,7 @@ impl BlockchainBackend for LMDBDatabase {

fn utxo_count(&self) -> Result<usize, ChainStorageError> {
let txn = self.read_transaction()?;
lmdb_len(&txn, &self.utxos_db)
lmdb_len(&txn, &self.utxo_commitment_index)
}

fn kernel_count(&self) -> Result<usize, ChainStorageError> {
Expand Down
10 changes: 0 additions & 10 deletions base_layer/core/src/proof_of_work/proof_of_work.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,16 +77,6 @@ impl ProofOfWork {
}
}

impl Display for PowAlgorithm {
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error> {
let algo = match self {
PowAlgorithm::Monero => "Monero",
PowAlgorithm::Sha3 => "Sha3",
};
fmt.write_str(&algo.to_string())
}
}

impl Display for ProofOfWork {
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error> {
writeln!(fmt, "Mining algorithm: {}", self.pow_algo)?;
Expand Down
16 changes: 15 additions & 1 deletion base_layer/core/src/proof_of_work/proof_of_work_algorithm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::{convert::TryFrom, str::FromStr};
use std::{
convert::TryFrom,
fmt::{Display, Formatter},
str::FromStr,
};

use serde::{Deserialize, Serialize};
use thiserror::Error;
Expand Down Expand Up @@ -75,3 +79,13 @@ impl FromStr for PowAlgorithm {
}
}
}

impl Display for PowAlgorithm {
fn fmt(&self, fmt: &mut Formatter<'_>) -> std::fmt::Result {
let algo = match self {
PowAlgorithm::Monero => "Monero",
PowAlgorithm::Sha3 => "Sha3",
};
fmt.write_str(algo)
}
}
11 changes: 10 additions & 1 deletion comms/src/peer_manager/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ use multiaddr::Multiaddr;
use tari_storage::{lmdb_store::LMDBDatabase, IterationResult};
use tokio::sync::RwLock;

#[cfg(feature = "metrics")]
use crate::peer_manager::metrics;
use crate::{
peer_manager::{
migrations,
Expand Down Expand Up @@ -71,7 +73,14 @@ impl PeerManager {
/// Adds a peer to the routing table of the PeerManager if the peer does not already exist. When a peer already
/// exist, the stored version will be replaced with the newly provided peer.
pub async fn add_peer(&self, peer: Peer) -> Result<PeerId, PeerManagerError> {
self.peer_storage.write().await.add_peer(peer)
let mut lock = self.peer_storage.write().await;
let peer_id = lock.add_peer(peer)?;
#[cfg(feature = "metrics")]
{
let count = lock.count();
metrics::peer_list_size().set(count as i64);
}
Ok(peer_id)
}

/// The peer with the specified public_key will be removed from the PeerManager
Expand Down
3 changes: 3 additions & 0 deletions comms/src/peer_manager/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,6 @@ mod or_not_found;
pub use or_not_found::OrNotFound;

mod wrapper;

#[cfg(feature = "metrics")]
mod metrics;

0 comments on commit 82d1d80

Please sign in to comment.