forest/metrics/
db.rs

1// Copyright 2019-2025 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use prometheus_client::{
5    collector::Collector,
6    encoding::{DescriptorEncoder, EncodeMetric},
7    metrics::gauge::Gauge,
8};
9use std::path::PathBuf;
10use tracing::error;
11
12#[derive(Debug)]
13pub struct DBCollector {
14    db_directory: PathBuf,
15    db_size: Gauge,
16}
17
18impl DBCollector {
19    pub fn new(db_directory: PathBuf) -> Self {
20        Self {
21            db_directory,
22            db_size: Gauge::default(),
23        }
24    }
25}
26
27impl Collector for DBCollector {
28    fn encode(&self, mut encoder: DescriptorEncoder) -> Result<(), std::fmt::Error> {
29        let db_size = match fs_extra::dir::get_size(self.db_directory.clone()) {
30            Ok(db_size) => db_size,
31            Err(e) => {
32                error!("Calculating DB size for metrics failed: {:?}", e);
33                0
34            }
35        };
36        self.db_size.set(db_size as _);
37        let metric_encoder = encoder.encode_descriptor(
38            "forest_db_size",
39            "Size of Forest database in bytes",
40            // Using Some(&Unit::Bytes) here changes the output to
41            // # HELP forest_db_size_bytes Size of Forest database in bytes
42            // # TYPE forest_db_size_bytes gauge
43            // # UNIT forest_db_size_bytes bytes
44            // forest_db_size_bytes 9281452850
45            None,
46            self.db_size.metric_type(),
47        )?;
48        self.db_size.encode(metric_encoder)?;
49        Ok(())
50    }
51}