Rust监控与指标采集库substrate-prometheus-endpoint的使用,集成Prometheus端点实现Substrate区块链性能监控
Rust监控与指标采集库substrate-prometheus-endpoint的使用,集成Prometheus端点实现Substrate区块链性能监控
介绍
Prometheus是云原生计算基金会支持的最广泛使用的高可用服务监控工具之一。通过在Substrate中提供Prometheus指标,节点操作者可以轻松采用广泛使用的显示/告警工具如Grafana和Alertmanager。这种监控工具的便捷访问将使平行链开发者/操作者和验证者能够获得更高可用性的服务。
默认情况下,指标将在TCP端口9615的/metrics
路径下提供。
快速开始
- 从仓库根目录启动Substrate
cargo run --release
- 在另一个终端运行
curl localhost:9615/metrics
获取指标
要了解如何配置Prometheus,请参阅Prometheus的入门指南。
安装
在项目目录中运行以下Cargo命令:
cargo add substrate-prometheus-endpoint
或者在Cargo.toml中添加以下行:
substrate-prometheus-endpoint = "0.17.4"
完整示例代码
以下是一个完整的示例,展示如何在Substrate节点中集成Prometheus指标端点:
use sc_service::{
config::PrometheusConfig,
TFullBackend, TFullClient, TaskManager
};
use substrate_prometheus_endpoint::init_prometheus;
// 在服务构建过程中初始化Prometheus
fn init_prometheus_metrics(
task_manager: &mut TaskManager,
prometheus_config: &Option<PrometheusConfig>,
registry: &prometheus::Registry,
) -> Result<(), sc_service::Error> {
if let Some(cfg) = prometheus_config {
// 初始化Prometheus端点
let prometheus_handle = init_prometheus(
cfg.listen_addr,
registry.clone(),
task_manager.spawn_handle(),
)?;
// 将Prometheus服务器添加到任务管理器
task_manager.add_child(prometheus_handle);
}
Ok(())
}
// 完整的服务构建示例
fn build_service() -> Result<(), sc_service::Error> {
// ... 其他服务配置
// 创建Prometheus配置
let prometheus_config = PrometheusConfig::new(
"127.0.0.1:9615".parse().unwrap(), // 监听地址
None, // 端点路径,默认为/metrics
);
// 创建指标注册表
let prometheus_registry = prometheus::Registry::new();
// 创建任务管理器
let mut task_manager = TaskManager::new(...);
// 初始化Prometheus
init_prometheus_metrics(
&mut task_manager,
&Some(prometheus_config),
&prometheus_registry,
)?;
// ... 其他服务初始化代码
Ok(())
}
自定义指标示例
以下是如何添加自定义指标的示例:
use prometheus::{Counter, Opts, Registry};
// 定义自定义指标
struct CustomMetrics {
blocks_processed: Counter,
transactions_processed: Counter,
}
impl CustomMetrics {
// 创建新的指标实例
fn new(registry: &Registry) -> Result<Self, prometheus::Error> {
let blocks = Counter::with_opts(Opts::new(
"substrate_blocks_processed_total",
"Total number of blocks processed",
))?;
let transactions = Counter::with_opts(Opts::new(
"substrate_transactions_processed_total",
"Total number of transactions processed",
))?;
registry.register(Box::new(blocks.clone()))?;
registry.register(Box::new(transactions.clone()))?;
Ok(Self {
blocks_processed: blocks,
transactions_processed: transactions,
})
}
}
// 在应用中使用的示例
fn process_block(metrics: &CustomMetrics) {
// ... 处理区块的逻辑
// 增加指标计数
metrics.blocks_processed.inc();
// 假设处理了10笔交易
metrics.transactions_processed.inc_by(10);
}
注意事项
- 默认情况下,Prometheus端点监听在9615端口上的
/metrics
路径 - 确保在生产环境中正确配置防火墙规则,以允许访问监控端口
- 对于高安全性环境,考虑添加基本认证或其他安全措施来保护指标端点
通过这种方式,你可以轻松地将Prometheus监控集成到Substrate区块链节点中,并利用丰富的Prometheus生态系统来监控你的区块链应用程序。
Rust监控与指标采集库substrate-prometheus-endpoint使用指南
介绍
substrate-prometheus-endpoint
是一个用于Substrate区块链框架的Prometheus监控端点集成库,它允许开发者轻松地将Prometheus监控功能集成到Substrate区块链节点中,收集和暴露各种性能指标。
该库主要功能包括:
- 在Substrate节点中暴露Prometheus格式的指标端点
- 收集区块链节点的关键性能指标
- 支持自定义指标的添加
- 与标准的Prometheus监控系统无缝集成
安装
在项目的Cargo.toml
中添加依赖:
[dependencies]
substrate-prometheus-endpoint = "0.10.0"
基本使用方法
1. 初始化Prometheus端点
use substrate_prometheus_endpoint::{init, PrometheusConfig};
fn main() {
let prometheus_config = PrometheusConfig::new()
.with_listening_port(9615) // 默认端口9615
.with_prefix("substrate") // 指标前缀
.with_endpoint("/metrics"); // 端点路径
let _prometheus_handle = init(prometheus_config).expect("Failed to init Prometheus");
}
2. 添加默认指标
Substrate框架会自动收集一些默认指标,如:
- 区块导入数量
- 交易处理数量
- 内存使用情况
- CPU使用率
- 网络活动
3. 自定义指标
use substrate_prometheus_endpoint::{register, Gauge, Registry};
// 创建自定义指标
let custom_registry = Registry::new();
let custom_gauge = Gauge::new(
"custom_metric",
"A custom metric for demonstration"
).expect("Metric can't be created");
// 注册指标
register(Box::new(custom_gauge.clone()), &custom_registry)
.expect("Failed to register metric");
// 更新指标值
custom_gauge.set(42.0);
高级用法
集成到Substrate节点
use sc_service::Configuration;
use substrate_prometheus_endpoint::init_prometheus;
pub fn new_full(config: Configuration) -> Result<Service, Error> {
// ...其他初始化代码...
let prometheus_registry = init_prometheus(config.prometheus_config.clone())?;
// 将registry传递给需要收集指标的组件
let service = Service::new(
// ...其他参数...
prometheus_registry,
)?;
Ok(service)
}
自定义指标收集器
use prometheus_endpoint::{Registry, CounterVec, Opts};
struct CustomMetrics {
transactions: CounterVec,
}
impl CustomMetrics {
pub fn new(registry: &Registry) -> Self {
let transactions = CounterVec::new(
Opts::new("transactions_total", "Total number of transactions"),
&["type"]
).unwrap();
registry.register(Box::new(transactions.clone())).unwrap();
Self { transactions }
}
pub fn record_transaction(&self, tx_type: &str) {
self.transactions.with_label_values(&[tx_type]).inc();
}
}
配置选项
PrometheusConfig
提供多种配置选项:
let config = PrometheusConfig::new()
.with_listening_port(9615) // 监听端口
.with_listening_address("0.0.0.0") // 监听地址
.with_prefix("substrate") // 指标前缀
.with_endpoint("/metrics") // 端点路径
.with_default_metrics(true) // 是否收集默认指标
.with_system_metrics(true); // 是否收集系统指标
查询指标
启动节点后,可以通过以下方式访问指标:
curl http://localhost:9615/metrics
示例输出:
# HELP substrate_block_height Current block height
# TYPE substrate_block_height gauge
substrate_block_height 12345
# HELP substrate_transactions_total Total number of transactions
# TYPE substrate_transactions_total counter
substrate_transactions_total 7890
与Prometheus集成
在Prometheus的配置文件中添加:
scrape_configs:
- job_name: 'substrate_node'
static_configs:
- targets: ['localhost:9615']
注意事项
- 在生产环境中,应考虑限制对指标端点的访问
- 收集过多指标可能会影响节点性能
- 指标名称应遵循Prometheus命名规范
- 默认端口9615可能会与其他服务冲突,可根据需要修改
完整示例代码
以下是一个完整的Substrate节点集成Prometheus监控的示例:
use sc_service::{Configuration, TFullBackend, TFullClient, TaskManager};
use substrate_prometheus_endpoint::{init_prometheus, PrometheusConfig, Registry};
use prometheus_endpoint::{CounterVec, Opts};
// 自定义指标结构体
struct NodeMetrics {
blocks_processed: CounterVec,
custom_gauge: Gauge,
}
impl NodeMetrics {
fn new(registry: &Registry) -> Self {
let blocks_processed = CounterVec::new(
Opts::new("blocks_processed", "Number of blocks processed"),
&["status"]
).unwrap();
let custom_gauge = Gauge::new(
"custom_value",
"A custom gauge metric"
).unwrap();
registry.register(Box::new(blocks_processed.clone())).unwrap();
registry.register(Box::new(custom_gauge.clone())).unwrap();
Self { blocks_processed, custom_gauge }
}
}
pub fn new_full(config: Configuration) -> Result<Service, Error> {
// 初始化Prometheus
let prometheus_config = PrometheusConfig::new()
.with_listening_port(9615)
.with_prefix("substrate_node")
.with_endpoint("/metrics");
let prometheus_registry = init_prometheus(prometheus_config)?;
// 创建自定义指标
let metrics = NodeMetrics::new(&prometheus_registry);
// 模拟指标更新
metrics.blocks_processed.with_label_values(&["imported"]).inc();
metrics.custom_gauge.set(100.0);
// 创建服务
let service = Service::new(
config,
prometheus_registry,
// 其他参数...
)?;
Ok(service)
}
fn main() {
let config = Configuration::default();
let _service = new_full(config).expect("Failed to create service");
}
这个完整示例展示了:
- 如何初始化Prometheus监控
- 如何定义自定义指标结构体
- 如何在Substrate节点中集成监控功能
- 如何更新指标值
开发者可以根据实际需求扩展这个基础示例,添加更多自定义指标和监控逻辑。