Crate prometheus_http_query[][src]

Expand description

The goal of this crate is to provide a query interface to the Prometheus HTTP API and leverage Rust’s type system in the process. Thus mistakes while building a query can be caught at compile-time (or at least before actually sending the query to Prometheus).

Most of the features of PromQL are mirrored in this library. Queries are gradually built from time series selectors, aggregations and functions and then passed to an HTTP client to execute.

Behind the scenes this library uses the reqwest crate as a HTTP client. Thus its features and limitations also apply to this library.

Usage

Construct PromQL queries

Gradually build PromQL expressions using Selector, turn it into a RangeVector or InstantVector, apply additional aggregations or functions on them and evaluate the final expression at an instant (Client::query) or a range of time (Client::query_range).

use prometheus_http_query::{Client, Selector, RangeVector, Aggregate};
use prometheus_http_query::aggregations::sum;
use prometheus_http_query::functions::rate;
use std::convert::TryInto;

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

    let v: RangeVector = Selector::new()
        .metric("node_cpu_seconds_total")?
        .with("mode", "user")
        .range("5m")?
        .try_into()?;

    let q = sum(rate(v), Some(Aggregate::By(&["cpu"])));

    let response = client.query(q, None, None).await;

    assert!(response.is_ok());
    
    Ok(())
}

Custom non-validated PromQL queries

It is also possible to bypass every kind of validation by supplying a custom query directly to the InstantVector / RangeVector types.

use prometheus_http_query::{Client, RangeVector};

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

    let q = r#"sum by(cpu) (rate(node_cpu_seconds_total{mode="user"}[5m]))"#;

    let v = RangeVector(q.to_string());

    let response = client.query(v, None, None).await;

    assert!(response.is_ok());
    
    Ok(())
}

Metadata queries

Retrieve a list of time series that match a certain label set by providing one or more series Selectors.

use prometheus_http_query::{Client, Scheme, Selector, Error};

fn main() -> Result<(), Error> {
    let client = Client::new(Scheme::Http, "localhost", 9090);

    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 = tokio_test::block_on( async { client.series(&set, None, None).await });

    assert!(response.is_ok());

    Ok(())
}

Rules & Alerts

Retrieve recording/alerting rules and active alerts.

use prometheus_http_query::{Client, Scheme, Error, RuleType};

fn main() -> Result<(), Error> {
    let client = Client::new(Scheme::Http, "localhost", 9090);

    let response = tokio_test::block_on( async { client.rules(None).await });

    assert!(response.is_ok());

    // Only request alerting rules instead:
    let response = tokio_test::block_on( async { client.rules(Some(RuleType::Alert)).await });

    assert!(response.is_ok());

    // Request active alerts:
    let response = tokio_test::block_on( async { client.alerts().await });

    assert!(response.is_ok());

    Ok(())
}

This is just one example. See Client for examples of other types of metadata queries.

Supported operations

  • Building PromQL expressions using time series selectors, functions and operators (aggregation/binary/vector matching …)
  • Evaluating expressions as instant queries
  • Evaluating expressions as range queries
  • Executing series metadata queries
  • Executing label metadata queries (names/values)
  • Retrieving target discovery status
  • Retrieve alerting + recording rules
  • Retrieve active alerts
  • Target metadata
  • Metric metadata
  • Alertmanager service discovery status
  • Prometheus status (config, startup flags …)

Notes

If the JSON response from the Prometheus HTTP API indicates an error (field status == "error"), then the contents of both fields errorType and error are captured and then returned by the client as a variant of the Error enum, just as any HTTP errors (non-200) that may indicate a problem with the provided query string. Thus any syntax problems etc. that cannot be caught at compile time or before executing the query will at least be propagated in the same manner.

Limitations

  • Some query types (e.g. Prometheus status, metric & target metadata) are not supported (yet)
  • reqwest client configuration cannot be customized (yet)
  • Subqueries are not supported (only as custom query)
  • PromQL functions that do not take a range / instant vector as an argument are not supported (only as custom query)

Modules

aggregations

A set of aggregation operators like sum and avg

functions

A set of PromQL function equivalents e.g. abs and rate

response

Collection of response types, most importantly the Response enum

Structs

Client

A client used to execute queries. It uses a reqwest::Client internally that manages connections for us.

InstantVector

An instant vector expression that can be further operated on with functions/aggregations or passed to a crate::Client in order to evaluate.

RangeVector

An range vector expression that can be further operated on with functions/aggregations or passed to a Client in order to evaluate.

Selector

A time series selector that is gradually built from a metric name and/or a set of label matchers.

Enums

Aggregate

A helper type that provides label matching logic for e.g. aggregations like sum.

Error

A global error enum that encapsulates other more specific types of errors.

Group

A helper type that provides grouping logic for e.g. vector matching.

Match

A helper type that provides label matching logic for e.g. binary operations (between instant vectors).

RuleType

A helper type to filter rules by type.

Scheme

A helper enum that is passed to the Client::new function in order to avoid errors on unsupported connection schemes.

TargetState

A helper type to filter targets by state.