Expand description

This crate provides an interface to the Prometheus HTTP API and leverage Rust’s type system in the process where applicable.

The Client uses as reqwest::Client as HTTP client internally as you will see in the usage section. Thus its features and limitations also apply to this library.

Usage

The following code contains just a few examples. See Client for the complete set of query functions.

Initialize a client

The Client can be constructed in various ways depending on your need to add customizations.

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

// In the most general case the default implementation is used to create the client.
// Requests will be sent to "http://127.0.0.1:9090 (the default listen address and port of the Prometheus server).
let client = Client::default();

// Provide an alternative URL if you need to. The URL will be checked for correctness.
use std::convert::TryFrom;
let client = Client::try_from("https://prometheus.example.com").unwrap();

// The greatest flexibility is offered by initializing a reqwest::Client first with
// all needed customizations and passing it along.
let client = {
    let c = reqwest::Client::builder().no_proxy().build().unwrap();
    Client::from(c, "https://prometheus.example.com").unwrap();
};

Execute PromQL queries

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

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

    let q = "topk by (code) (5, prometheus_http_requests_total)";
    let response = client.query(q, None, None).await?;
    assert!(response.as_instant().is_some());

    let q = r#"sum(prometheus_http_requests_total{code="200"})"#;
    let response = client.query(q, None, None).await?;
    let result = response.as_instant();

    if matches!(result, Some(x) if x.first().is_some()) {
        let first = result.unwrap().first().unwrap();
        println!("Received a total of {} HTTP requests", first.sample().value());
    }

    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, Error, Selector};

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

    let s1 = Selector::new()
        .eq("handler", "/api/v1/query");

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

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

    assert!(response.is_ok());

    Ok(())
}

Rules & Alerts

Retrieve recording/alerting rules and active alerts.

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

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

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

    assert!(response.is_ok());

    // Only request alerting rules instead:
    let response = client.rules(Some(RuleType::Alert)).await;

    assert!(response.is_ok());

    // Request active alerts:
    let response = client.alerts().await;

    assert!(response.is_ok());

    Ok(())
}

Convenience functions for one-off requests

use prometheus_http_query::{Error, query, runtime_information};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Error> {
    let q = "topk by (code) (5, prometheus_http_requests_total)";
    let response = query("http://localhost:9090", q, None, None).await?;

    assert!(response.as_instant().is_some());

    let response = runtime_information("http://localhost:9090").await;

    assert!(response.is_ok());

    Ok(())
}

Compatibility

See the README for details on this matter.

Supported operations

  • Execute instant and range queries and properly parse the results (vector/matrix/scalar)
  • Execute series metadata queries
  • Execute label metadata queries (names/values)
  • Retrieve target discovery status
  • Retrieve alerting + recording rules
  • Retrieve active alerts
  • Retrieve configured flags & values
  • Query target metadata
  • Query metric metadata
  • Query alertmanager service discovery status
  • Prometheus server flags
  • Prometheus server build information
  • Prometheus server runtime information
  • Prometheus server config

Notes

On parsing an error handling

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 as returned by the HTTP API.

Limitations

  • Some Client methods may not work with older versions of the Prometheus server
  • The String result type is not supported
  • Warnings contained in a API response will be ignored

Modules

All types that may be returned from crate::Client methods.

Structs

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

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

Enums

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

A helper type to filter rules by type.

A helper type to filter targets by state.

Functions

Query the current state of alertmanager discovery.

Retrieve a list of active alerts.

Retrieve Prometheus server build information.

Retrieve a list of flags that Prometheus was configured with.

Retrieve all label names (or use Selectors to select time series to read label names from).

Retrieve all label values for a label name (or use Selectors to select the time series to read label values from)

Retrieve metadata about metrics that are currently scraped from targets.

Execute an instant query.

Execute a range query.

Retrieve a list of rule groups of recording and alerting rules.

Retrieve Prometheus server runtime information.

Find time series that match certain label sets (Selectors).

Retrieve metadata about metrics that are currently scraped from targets, along with target information.

Query the current state of target discovery.