Struct prometheus_http_query::Client
source · [−]pub struct Client { /* private fields */ }
Expand description
A client used to execute queries. It uses a reqwest::Client internally that manages connections for us.
Note that possible errors regarding domain name resolution or connection establishment will only be propagated from the underlying reqwest::Client when a query is executed.
Implementations
sourceimpl Client
impl Client
sourcepub fn inner(&self) -> &Client
pub fn inner(&self) -> &Client
Return a reference to the wrapped reqwest::Client, i.e. to use it for other requests unrelated to the Prometheus API.
use prometheus_http_query::{Client, Error};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
// An amittedly bad example, but that is not the point.
let response = client
.inner()
.head("http://127.0.0.1:9090")
.send()
.await
.map_err(Error::Reqwest)?;
// Prometheus does not allow HEAD requests.
assert_eq!(response.status(), reqwest::StatusCode::METHOD_NOT_ALLOWED);
Ok(())
}
sourcepub fn base_url(&self) -> &str
pub fn base_url(&self) -> &str
Return a reference to the base URL that is used in requests to the Prometheus API.
use prometheus_http_query::Client;
use std::str::FromStr;
let client = Client::default();
assert_eq!(client.base_url(), "http://127.0.0.1:9090/api/v1");
let client = Client::from_str("https://proxy.example.com:8443/prometheus").unwrap();
assert_eq!(client.base_url(), "https://proxy.example.com:8443/prometheus/api/v1");
sourcepub fn from(client: Client, url: &str) -> Result<Self, Error>
pub fn from(client: Client, url: &str) -> Result<Self, Error>
Create a Client from a custom reqwest::Client and URL. This way you can account for all extra parameters (e.g. x509 authentication) that may be needed to connect to Prometheus or an intermediate proxy, by building it into the reqwest::Client.
use prometheus_http_query::{Client, Error};
fn main() -> Result<(), Error> {
let client = {
let c = reqwest::Client::builder()
.no_proxy()
.build()
.map_err(Error::Reqwest)?;
Client::from(c, "https://prometheus.example.com")
};
assert!(client.is_ok());
Ok(())
}
sourcepub async fn query(
&self,
vector: impl Display,
time: Option<i64>,
timeout: Option<&str>
) -> Result<QueryResultType, Error>
pub async fn query(
&self,
vector: impl Display,
time: Option<i64>,
timeout: Option<&str>
) -> Result<QueryResultType, Error>
Perform an instant query using a crate::RangeVector or crate::InstantVector.
use prometheus_http_query::{Client, InstantVector, Selector, Aggregate, Error};
use prometheus_http_query::aggregations::sum;
use std::convert::TryInto;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
let v: InstantVector = Selector::new()
.metric("node_cpu_seconds_total")
.try_into()?;
let s = sum(v, Some(Aggregate::By(&["cpu"])));
let response = client.query(s, None, None).await?;
assert!(response.as_instant().is_some());
Ok(())
}
pub async fn query_range(
&self,
vector: impl Display,
start: i64,
end: i64,
step: &str,
timeout: Option<&str>
) -> Result<QueryResultType, Error>
sourcepub async fn series(
&self,
selectors: &[Selector<'_>],
start: Option<i64>,
end: Option<i64>
) -> Result<Vec<HashMap<String, String>>, Error>
pub async fn series(
&self,
selectors: &[Selector<'_>],
start: Option<i64>,
end: Option<i64>
) -> Result<Vec<HashMap<String, String>>, Error>
Find time series that match certain label sets (Selectors).
use prometheus_http_query::{Client, Selector, Error};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
let s1 = Selector::new()
.with("handler", "/api/v1/query");
let s2 = Selector::new()
.with("job", "node")
.regex_match("mode", ".+");
let set = vec![s1, s2];
let response = client.series(&set, None, None).await;
assert!(response.is_ok());
Ok(())
}
sourcepub async fn label_names(
&self,
selectors: Option<Vec<Selector<'_>>>,
start: Option<i64>,
end: Option<i64>
) -> Result<Vec<String>, Error>
pub async fn label_names(
&self,
selectors: Option<Vec<Selector<'_>>>,
start: Option<i64>,
end: Option<i64>
) -> Result<Vec<String>, Error>
Retrieve all label names (or use Selectors to select time series to read label names from).
use prometheus_http_query::{Client, Selector, Error};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
// To retrieve a list of all labels:
let response = client.label_names(None, None, None).await;
assert!(response.is_ok());
// To retrieve a list of labels that appear in specific time series, use Selectors:
let s1 = Selector::new()
.with("handler", "/api/v1/query");
let s2 = Selector::new()
.with("job", "node")
.regex_match("mode", ".+");
let set = Some(vec![s1, s2]);
let response = client.label_names(set, None, None).await;
assert!(response.is_ok());
Ok(())
}
sourcepub async fn label_values(
&self,
label: &str,
selectors: Option<Vec<Selector<'_>>>,
start: Option<i64>,
end: Option<i64>
) -> Result<Vec<String>, Error>
pub async fn label_values(
&self,
label: &str,
selectors: Option<Vec<Selector<'_>>>,
start: Option<i64>,
end: Option<i64>
) -> Result<Vec<String>, Error>
Retrieve all label values for a label name (or use Selectors to select the time series to read label values from)
use prometheus_http_query::{Client, Selector, Error};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
// To retrieve a list of all label values for a specific label name:
let response = client.label_values("job", None, None, None).await;
assert!(response.is_ok());
// To retrieve a list of label values of labels in specific time series instead:
let s1 = Selector::new()
.regex_match("instance", ".+");
let set = Some(vec![s1]);
let response = client.label_values("job", set, None, None).await;
assert!(response.is_ok());
Ok(())
}
sourcepub async fn targets(
&self,
state: Option<TargetState>
) -> Result<Targets, Error>
pub async fn targets(
&self,
state: Option<TargetState>
) -> Result<Targets, Error>
Query the current state of target discovery.
use prometheus_http_query::{Client, Error, TargetState};
use std::convert::TryInto;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
let response = client.targets(None).await;
assert!(response.is_ok());
// Filter targets by type:
let response = client.targets(Some(TargetState::Active)).await;
assert!(response.is_ok());
Ok(())
}
sourcepub async fn rules(
&self,
rule_type: Option<RuleType>
) -> Result<Vec<RuleGroup>, Error>
pub async fn rules(
&self,
rule_type: Option<RuleType>
) -> Result<Vec<RuleGroup>, Error>
Retrieve a list of rule groups of recording and alerting rules.
use prometheus_http_query::{Client, Error, RuleType};
use std::convert::TryInto;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
let response = client.rules(None).await;
assert!(response.is_ok());
// Filter rules by type:
let response = client.rules(Some(RuleType::Alert)).await;
assert!(response.is_ok());
Ok(())
}
sourcepub async fn alerts(&self) -> Result<Vec<Alert>, Error>
pub async fn alerts(&self) -> Result<Vec<Alert>, Error>
Retrieve a list of active alerts.
use prometheus_http_query::{Client, Error};
use std::convert::TryInto;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
let response = client.alerts().await;
assert!(response.is_ok());
Ok(())
}
sourcepub async fn flags(&self) -> Result<HashMap<String, String>, Error>
pub async fn flags(&self) -> Result<HashMap<String, String>, Error>
Retrieve a list of flags that Prometheus was configured with.
use prometheus_http_query::{Client, Error};
use std::convert::TryInto;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
let response = client.flags().await;
assert!(response.is_ok());
Ok(())
}
sourcepub async fn alertmanagers(&self) -> Result<Alertmanagers, Error>
pub async fn alertmanagers(&self) -> Result<Alertmanagers, Error>
Query the current state of alertmanager discovery.
use prometheus_http_query::{Client, Error, TargetState};
use std::convert::TryInto;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
let response = client.alertmanagers().await;
assert!(response.is_ok());
Ok(())
}
sourcepub async fn target_metadata(
&self,
metric: Option<&str>,
match_target: Option<&Selector<'_>>,
limit: Option<usize>
) -> Result<Vec<TargetMetadata>, Error>
pub async fn target_metadata(
&self,
metric: Option<&str>,
match_target: Option<&Selector<'_>>,
limit: Option<usize>
) -> Result<Vec<TargetMetadata>, Error>
Retrieve metadata about metrics that are currently scraped from targets, along with target information.
use prometheus_http_query::{Client, Error, Selector};
use std::convert::TryInto;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
// Retrieve metadata for a specific metric from all targets.
let response = client.target_metadata(Some("go_routines"), None, None).await;
assert!(response.is_ok());
// Retrieve metric metadata from specific targets.
let s = Selector::new().with("job", "prometheus");
let response = client.target_metadata(None, Some(&s), None).await;
assert!(response.is_ok());
// Retrieve metadata for a specific metric from targets that match a specific label set.
let s = Selector::new().with("job", "node");
let response = client.target_metadata(Some("node_cpu_seconds_total"), Some(&s), None).await;
assert!(response.is_ok());
Ok(())
}
sourcepub async fn metric_metadata(
&self,
metric: Option<&str>,
limit: Option<usize>
) -> Result<HashMap<String, Vec<MetricMetadata>>, Error>
pub async fn metric_metadata(
&self,
metric: Option<&str>,
limit: Option<usize>
) -> Result<HashMap<String, Vec<MetricMetadata>>, Error>
Retrieve metadata about metrics that are currently scraped from targets.
use prometheus_http_query::{Client, Error};
use std::convert::TryInto;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
let client = Client::default();
// Retrieve metadata for a all metrics.
let response = client.metric_metadata(None, None).await;
assert!(response.is_ok());
// Limit the number of returned metrics
let response = client.metric_metadata(None, Some(10)).await;
assert!(response.is_ok());
// Retrieve metadata of a specific metric.
let response = client.metric_metadata(Some("go_routines"), None).await;
assert!(response.is_ok());
Ok(())
}
Trait Implementations
sourceimpl FromStr for Client
impl FromStr for Client
sourcefn from_str(url: &str) -> Result<Self, Self::Err>
fn from_str(url: &str) -> Result<Self, Self::Err>
Create a Client from a custom base URL, which may be useful if requests are handled by i.e. a reverse proxy.
use prometheus_http_query::Client;
use std::str::FromStr;
let client = Client::from_str("http://proxy.example.com/prometheus");
assert!(client.is_ok());
sourceimpl TryFrom<&'_ str> for Client
impl TryFrom<&'_ str> for Client
sourcefn try_from(url: &str) -> Result<Self, Self::Error>
fn try_from(url: &str) -> Result<Self, Self::Error>
Create a Client from a custom base URL, which may be useful if requests are handled by i.e. a reverse proxy.
use prometheus_http_query::Client;
use std::convert::TryFrom;
let client = Client::try_from("http://proxy.example.com/prometheus");
assert!(client.is_ok());
sourceimpl TryFrom<String> for Client
impl TryFrom<String> for Client
sourcefn try_from(url: String) -> Result<Self, Self::Error>
fn try_from(url: String) -> Result<Self, Self::Error>
Create a Client from a custom base URL, which may be useful if requests are handled by i.e. a reverse proxy.
use prometheus_http_query::Client;
use std::convert::TryFrom;
let url = String::from("http://proxy.example.com/prometheus");
let client = Client::try_from(url);
assert!(client.is_ok());
Auto Trait Implementations
impl !RefUnwindSafe for Client
impl Send for Client
impl Sync for Client
impl Unpin for Client
impl !UnwindSafe for Client
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcefn clone_into(&self, target: &mut T)
fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more