Skip to main content

Client

Struct 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.

Implementations§

Source§

impl Client

Source

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};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::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?;

    // Prometheus does not allow HEAD requests.
    assert_eq!(response.status(), reqwest::StatusCode::METHOD_NOT_ALLOWED);
    Ok(())
}
Source

pub fn base_url(&self) -> &Url

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().as_str(), "http://127.0.0.1:9090/");

let client = Client::from_str("https://proxy.example.com:8443/prometheus").unwrap();

assert_eq!(client.base_url().as_str(), "https://proxy.example.com:8443/prometheus");
Source

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;

fn main() -> Result<(), anyhow::Error> {
    let client = {
        let c = reqwest::Client::builder()
            .no_proxy()
            .build()?;
        Client::from(c, "https://prometheus.example.com")
    };

    assert!(client.is_ok());
    Ok(())
}
Source

pub fn query(&self, query: impl Display) -> InstantQueryBuilder

Create an InstantQueryBuilder from a PromQL query allowing you to set some query parameters (e.g. evaluation timeout) before finally sending the instant query to the server.

§Arguments
  • query - PromQL query to exeute

See also: Prometheus API documentation

use prometheus_http_query::{Client, Duration};
use std::str::FromStr;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.query("prometheus_http_request_total")
        .time(time::macros::datetime!(1970-01-01 0:00 -1).unix_timestamp())
        .timeout(Duration::from_str("10s")?.into())
        .get()
        .await?;

    assert!(response.data().as_vector().is_some());

    // Or send a POST request without extra parameters. Also set
    // the lookback period to one hour.
    let response = client.query("prometheus_http_request_total")
        .lookback_delta(3600.into())
        .post()
        .await?;

    assert!(response.data().as_vector().is_some());

    Ok(())
}
Source

pub fn query_range( &self, query: impl Display, start: i64, end: i64, step: f64, ) -> RangeQueryBuilder

Create a RangeQueryBuilder from a PromQL query allowing you to set some query parameters (e.g. evaluation timeout) before finally sending the range query to the server.

§Arguments
  • query - PromQL query to exeute
  • start - Start timestamp as Unix timestamp (seconds)
  • end - End timestamp as Unix timestamp (seconds)
  • step - Query resolution step width as float number of seconds

See also: Prometheus API documentation

use prometheus_http_query::{Client, Duration};
use std::str::FromStr;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let q = "prometheus_http_requests_total";

    let response = client.query_range(q, 1648373100, 1648373300, 10.0)
        .timeout(10.into())
        .get()
        .await?;

    assert!(response.data().as_matrix().is_some());

    // Or make a POST request.
    // A Prometheus time duration can also be parsed from a string when
    // it is not available in its float representation.
    let duration = Duration::from_str("10s")?;
    let response = client.query_range(q, 1648373100, 1648373300, duration.into())
        .limit(10)
        .lookback_delta((6.5).into())
        .post()
        .await?;

    assert!(response.data().as_matrix().is_some());

    Ok(())
}
Source

pub fn series(&self) -> SeriesQueryBuilder

Create a SeriesQueryBuilder to apply filters to a series metadata query before sending it to Prometheus.
See also: Prometheus API documentation

use prometheus_http_query::{Client, Selector};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    // Use free-form series selectors to only return time series
    // matching a certain label set.
    {
        let response = client.series()
            .match_one("up")
            .match_one("{job=\"node\",instance=~\".+\"}")
            .limit(5)
            .get()
            .await;

        assert!(response.is_ok());
    }

    // Use strongly typed series selectors to only return time series
    // matching a certain label set.
    {
        let s1 = Selector::new()
            .eq("handler", "/api/v1/query");

        let s2 = Selector::new()
            .eq("job", "node")
            .regex_eq("mode", ".+");

        let response = client.series()
            .match_many(&[s1, s2])
            .get()
            .await;

        assert!(response.is_ok());
    }

    Ok(())
}
Source

pub fn label_names(&self) -> LabelNamesQueryBuilder

Create a LabelNamesQueryBuilder to apply filters to a query for the label names endpoint before sending it to Prometheus.

See also: Prometheus API documentation

use prometheus_http_query::{Client, Selector};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    // To retrieve a list of all labels:
    let response = client.label_names().get().await;

    assert!(response.is_ok());

    // Use free-form selectors to retrieve a list of labels
    // that appear in specific time series:
    {
        let response = client.label_names()
            .match_one("{handler=\"/api/v1/query\"}")
            .match_one("{job=\"node\",mode=~\".+\"}")
            .get()
            .await;

        assert!(response.is_ok());
    }

    // Use strongly typed selectors to retrieve a list of labels
    // that appear in specific time series:
    {
        let s1 = Selector::new()
            .eq("handler", "/api/v1/query");

        let s2 = Selector::new()
            .eq("job", "node")
            .regex_eq("mode", ".+");

        let response = client.label_names().match_many(&[s1, s2]).get().await;

        assert!(response.is_ok());
    }

    Ok(())
}
Source

pub fn label_values(&self, label: impl Display) -> LabelValuesQueryBuilder

Create a LabelValuesQueryBuilder to apply filters to a query for the label values endpoint before sending it to Prometheus.

§Arguments
  • label - Name of the label to return all occuring label values for.

See also: Prometheus API documentation

use prometheus_http_query::{Client, Selector};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    // To retrieve a list of all label values for a specific label name:
    let response = client.label_values("job").get().await;

    assert!(response.is_ok());

    // Using free-form series selectors to retrieve a list of label values
    // that appear in specific time series:
    {
        let response = client.label_values("job")
            .match_one("{instance=~\".+\"}")
            .get()
            .await;

        assert!(response.is_ok());
    }

    // Using strongly typed series selectors to retrieve a list of label
    // values that appear in specific time series:
    {
        let selector = Selector::new()
            .regex_eq("instance", ".+");

        let response = client.label_values("job")
            .match_one(&selector)
            .get()
            .await;

        assert!(response.is_ok());
    }

    Ok(())
}
Source

pub fn targets(&self) -> TargetsQueryBuilder

Query the current state of target discovery.

See also: Prometheus API documentation

use prometheus_http_query::{Client, TargetState};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.targets().get().await;

    assert!(response.is_ok());

    // Filter targets by state and scrape pool name.
    let response = client.targets()
        .state(TargetState::Active)
        .scrape_pool("node_exporter")
        .get().await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn rules(&self) -> RulesQueryBuilder

Create a RulesQueryBuilder to apply filters to the rules query before sending it to Prometheus.

See also: Prometheus API documentation

use prometheus_http_query::{Client, RuleKind};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.rules().get().await;

    assert!(response.is_ok());

    // Filter rules by type:
    let response = client.rules().kind(RuleKind::Alerting).get().await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn alerts(&self) -> AlertsQueryBuilder

Retrieve a list of active alerts.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.alerts().get().await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn flags(&self) -> FlagsQueryBuilder

Retrieve a list of flags that Prometheus was configured with.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.flags().get().await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn build_information(&self) -> BuildInformationQueryBuilder

Retrieve Prometheus server build information.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.build_information().get().await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn runtime_information(&self) -> RuntimeInformationQueryBuilder

Retrieve Prometheus server runtime information.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.runtime_information().get().await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn tsdb_statistics(&self) -> TsdbStatisticsQueryBuilder

Retrieve Prometheus TSDB statistics.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.tsdb_statistics().get().await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn wal_replay_statistics(&self) -> WalReplayStatisticsQueryBuilder

Retrieve WAL replay statistics.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.wal_replay_statistics().get().await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn alertmanagers(&self) -> AlertmanagersQueryBuilder

Query the current state of alertmanager discovery.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    let response = client.alertmanagers().get().await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn target_metadata(&self) -> TargetMetadataQueryBuilder

Create a TargetMetadataQueryBuilder to apply filters to a target metadata query before sending it to Prometheus.

See also: Prometheus API documentation

use prometheus_http_query::{Client, Selector};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    // Retrieve metadata for a specific metric from all targets.
    let response = client.target_metadata()
        .metric("go_goroutines")
        .get()
        .await;

    assert!(response.is_ok());

    // Retrieve metric metadata from specific targets.
    let response = client.target_metadata()
        .match_target("{job=\"prometheus\"}")
        .get()
        .await;

    assert!(response.is_ok());

    // Retrieve metadata for a specific metric from targets that match a specific label set.
    // Also use a stronger typed selector.
    let s = Selector::new().eq("job", "node");
    let response = client.target_metadata()
        .metric("node_cpu_seconds_total")
        .match_target(s)
        .get()
        .await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub fn metric_metadata(&self) -> MetricMetadataQueryBuilder

Create a MetricMetadataQueryBuilder to apply filters to a metric metadata query before sending it to Prometheus.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();

    // Retrieve metadata for a all metrics.
    let response = client.metric_metadata().get().await;

    assert!(response.is_ok());

    // Limit the number of returned metrics.
    let response = client.metric_metadata().limit(100).get().await;

    assert!(response.is_ok());

    // Retrieve metadata for a specific metric but with a per-metric
    // metadata limit.
    let response = client.metric_metadata()
        .metric("go_goroutines")
        .limit_per_metric(5)
        .get()
        .await;

    assert!(response.is_ok());

    Ok(())
}
Source

pub async fn is_server_healthy(&self) -> Result<bool, Error>

Check Prometheus server health.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();
    assert!(client.is_server_healthy().await?);
    Ok(())
}
Source

pub async fn is_server_ready(&self) -> Result<bool, Error>

Check Prometheus server readiness.

See also: Prometheus API documentation

use prometheus_http_query::Client;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
    let client = Client::default();
    assert!(client.is_server_ready().await?);
    Ok(())
}

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Client

Source§

fn default() -> Self

Create a standard Client that sends requests to “http://127.0.0.1:9090/”.

use prometheus_http_query::Client;

let client = Client::default();
Source§

impl FromStr for Client

Source§

fn from_str(url: &str) -> Result<Self, Self::Err>

Create a Client from a custom base URL. Note that the API-specific path segments (like /api/v1/query) are added automatically.

use prometheus_http_query::Client;
use std::str::FromStr;

let client = Client::from_str("http://proxy.example.com/prometheus");
assert!(client.is_ok());
Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

impl TryFrom<&str> for Client

Source§

fn try_from(url: &str) -> Result<Self, Self::Error>

Create a Client from a custom base URL. Note that the API-specific path segments (like /api/v1/query) are added automatically.

use prometheus_http_query::Client;
use std::convert::TryFrom;

let client = Client::try_from("http://proxy.example.com/prometheus");
assert!(client.is_ok());
Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

impl TryFrom<String> for Client

Source§

fn try_from(url: String) -> Result<Self, Self::Error>

Create a Client from a custom base URL. Note that the API-specific path segments (like /api/v1/query) are added automatically.

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());
Source§

type Error = Error

The type returned in the event of a conversion error.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Client

§

impl !UnwindSafe for Client

§

impl Forget for Client

§

impl Freeze for Client
where *const ArcInner<ClientRef> is !null: Freeze, PhantomData<ArcInner<ClientRef>>: Freeze, *const u8 is !null: Freeze, PhantomData<u8>: Freeze,

§

impl Move for Client

§

impl Send for Client
where Arc<ClientRef>: Send, RawVecInner: Send,

§

impl Sync for Client
where Arc<ClientRef>: Sync, RawVecInner: Sync,

§

impl Unpin for Client
where Arc<ClientRef>: Unpin, *const u8 is !null: Unpin,

§

impl UnsafeUnpin for Client
where *const ArcInner<ClientRef> is !null: UnsafeUnpin, PhantomData<ArcInner<ClientRef>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

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
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more