mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-11-28 21:39:56 +00:00
Squashed 'bridges/' content from commit 062554430
git-subtree-dir: bridges git-subtree-split: 0625544309ff299307f7e110f252f04eac383102
This commit is contained in:
commit
d2b7ee2575
357 files changed
+79920
No files matched your search
@@ -0,0 +1,147 @@
|
||||
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{
|
||||
error::{self, Error},
|
||||
metrics::{
|
||||
metric_name, register, F64SharedRef, Gauge, Metric, PrometheusError, Registry,
|
||||
StandaloneMetric, F64,
|
||||
},
|
||||
};
|
||||
|
||||
use async_std::sync::{Arc, RwLock};
|
||||
use async_trait::async_trait;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Value update interval.
|
||||
const UPDATE_INTERVAL: Duration = Duration::from_secs(300);
|
||||
|
||||
/// Metric that represents float value received from HTTP service as float gauge.
|
||||
///
|
||||
/// The float value returned by the service is assumed to be normal (`f64::is_normal`
|
||||
/// should return `true`) and strictly positive.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FloatJsonValueMetric {
|
||||
url: String,
|
||||
json_path: String,
|
||||
metric: Gauge<F64>,
|
||||
shared_value_ref: F64SharedRef,
|
||||
}
|
||||
|
||||
impl FloatJsonValueMetric {
|
||||
/// Create new metric instance with given name and help.
|
||||
pub fn new(
|
||||
url: String,
|
||||
json_path: String,
|
||||
name: String,
|
||||
help: String,
|
||||
) -> Result<Self, PrometheusError> {
|
||||
let shared_value_ref = Arc::new(RwLock::new(None));
|
||||
Ok(FloatJsonValueMetric {
|
||||
url,
|
||||
json_path,
|
||||
metric: Gauge::new(metric_name(None, &name), help)?,
|
||||
shared_value_ref,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get shared reference to metric value.
|
||||
pub fn shared_value_ref(&self) -> F64SharedRef {
|
||||
self.shared_value_ref.clone()
|
||||
}
|
||||
|
||||
/// Request value from HTTP service.
|
||||
async fn request_value(&self) -> anyhow::Result<String> {
|
||||
use isahc::{AsyncReadResponseExt, HttpClient, Request};
|
||||
|
||||
let request = Request::get(&self.url).header("Accept", "application/json").body(())?;
|
||||
let raw_response = HttpClient::new()?.send_async(request).await?.text().await?;
|
||||
Ok(raw_response)
|
||||
}
|
||||
|
||||
/// Read value from HTTP service.
|
||||
async fn read_value(&self) -> error::Result<f64> {
|
||||
let raw_response = self.request_value().await.map_err(Error::FetchTokenPrice)?;
|
||||
parse_service_response(&self.json_path, &raw_response)
|
||||
}
|
||||
}
|
||||
|
||||
impl Metric for FloatJsonValueMetric {
|
||||
fn register(&self, registry: &Registry) -> Result<(), PrometheusError> {
|
||||
register(self.metric.clone(), registry).map(drop)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl StandaloneMetric for FloatJsonValueMetric {
|
||||
fn update_interval(&self) -> Duration {
|
||||
UPDATE_INTERVAL
|
||||
}
|
||||
|
||||
async fn update(&self) {
|
||||
let value = self.read_value().await;
|
||||
let maybe_ok = value.as_ref().ok().copied();
|
||||
crate::metrics::set_gauge_value(&self.metric, value.map(Some));
|
||||
*self.shared_value_ref.write().await = maybe_ok;
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse HTTP service response.
|
||||
fn parse_service_response(json_path: &str, response: &str) -> error::Result<f64> {
|
||||
let json =
|
||||
serde_json::from_str(response).map_err(|err| Error::ParseHttp(err, response.to_owned()))?;
|
||||
|
||||
let mut selector = jsonpath_lib::selector(&json);
|
||||
let maybe_selected_value =
|
||||
selector(json_path).map_err(|err| Error::SelectResponseValue(err, response.to_owned()))?;
|
||||
let selected_value = maybe_selected_value
|
||||
.first()
|
||||
.and_then(|v| v.as_f64())
|
||||
.ok_or_else(|| Error::MissingResponseValue(response.to_owned()))?;
|
||||
if !selected_value.is_normal() || selected_value < 0.0 {
|
||||
return Err(Error::ParseFloat(selected_value))
|
||||
}
|
||||
|
||||
Ok(selected_value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_service_response_works() {
|
||||
assert_eq!(
|
||||
parse_service_response("$.kusama.usd", r#"{"kusama":{"usd":433.05}}"#).map_err(drop),
|
||||
Ok(433.05),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_service_response_rejects_negative_numbers() {
|
||||
assert!(parse_service_response("$.kusama.usd", r#"{"kusama":{"usd":-433.05}}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_service_response_rejects_zero_numbers() {
|
||||
assert!(parse_service_response("$.kusama.usd", r#"{"kusama":{"usd":0.0}}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_service_response_rejects_nan() {
|
||||
assert!(parse_service_response("$.kusama.usd", r#"{"kusama":{"usd":NaN}}"#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Parity Bridges Common is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Global system-wide Prometheus metrics exposed by relays.
|
||||
|
||||
use crate::metrics::{
|
||||
metric_name, register, Gauge, GaugeVec, Metric, Opts, PrometheusError, Registry,
|
||||
StandaloneMetric, F64, U64,
|
||||
};
|
||||
|
||||
use async_std::sync::{Arc, Mutex};
|
||||
use async_trait::async_trait;
|
||||
use std::time::Duration;
|
||||
use sysinfo::{ProcessExt, RefreshKind, System, SystemExt};
|
||||
|
||||
/// Global metrics update interval.
|
||||
const UPDATE_INTERVAL: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Global Prometheus metrics.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct GlobalMetrics {
|
||||
system: Arc<Mutex<System>>,
|
||||
system_average_load: GaugeVec<F64>,
|
||||
process_cpu_usage_percentage: Gauge<F64>,
|
||||
process_memory_usage_bytes: Gauge<U64>,
|
||||
}
|
||||
|
||||
impl GlobalMetrics {
|
||||
/// Create and register global metrics.
|
||||
pub fn new() -> Result<Self, PrometheusError> {
|
||||
Ok(GlobalMetrics {
|
||||
system: Arc::new(Mutex::new(System::new_with_specifics(RefreshKind::everything()))),
|
||||
system_average_load: GaugeVec::new(
|
||||
Opts::new(metric_name(None, "system_average_load"), "System load average"),
|
||||
&["over"],
|
||||
)?,
|
||||
process_cpu_usage_percentage: Gauge::new(
|
||||
metric_name(None, "process_cpu_usage_percentage"),
|
||||
"Process CPU usage",
|
||||
)?,
|
||||
process_memory_usage_bytes: Gauge::new(
|
||||
metric_name(None, "process_memory_usage_bytes"),
|
||||
"Process memory (resident set size) usage",
|
||||
)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Metric for GlobalMetrics {
|
||||
fn register(&self, registry: &Registry) -> Result<(), PrometheusError> {
|
||||
register(self.system_average_load.clone(), registry)?;
|
||||
register(self.process_cpu_usage_percentage.clone(), registry)?;
|
||||
register(self.process_memory_usage_bytes.clone(), registry)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl StandaloneMetric for GlobalMetrics {
|
||||
async fn update(&self) {
|
||||
// update system-wide metrics
|
||||
let mut system = self.system.lock().await;
|
||||
let load = system.get_load_average();
|
||||
self.system_average_load.with_label_values(&["1min"]).set(load.one);
|
||||
self.system_average_load.with_label_values(&["5min"]).set(load.five);
|
||||
self.system_average_load.with_label_values(&["15min"]).set(load.fifteen);
|
||||
|
||||
// update process-related metrics
|
||||
let pid = sysinfo::get_current_pid().expect(
|
||||
"only fails where pid is unavailable (os=unknown || arch=wasm32);\
|
||||
relay is not supposed to run in such MetricsParamss;\
|
||||
qed",
|
||||
);
|
||||
let is_process_refreshed = system.refresh_process(pid);
|
||||
match (is_process_refreshed, system.get_process(pid)) {
|
||||
(true, Some(process_info)) => {
|
||||
let cpu_usage = process_info.cpu_usage() as f64;
|
||||
let memory_usage = process_info.memory() * 1024;
|
||||
log::trace!(
|
||||
target: "bridge-metrics",
|
||||
"Refreshed process metrics: CPU={}, memory={}",
|
||||
cpu_usage,
|
||||
memory_usage,
|
||||
);
|
||||
|
||||
self.process_cpu_usage_percentage.set(if cpu_usage.is_finite() {
|
||||
cpu_usage
|
||||
} else {
|
||||
0f64
|
||||
});
|
||||
self.process_memory_usage_bytes.set(memory_usage);
|
||||
},
|
||||
_ => {
|
||||
log::warn!(
|
||||
target: "bridge-metrics",
|
||||
"Failed to refresh process information. Metrics may show obsolete values",
|
||||
);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn update_interval(&self) -> Duration {
|
||||
UPDATE_INTERVAL
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user