Crate prometheus_http_query
source ·Expand description
This crate provides an interface to the Prometheus HTTP API. The Client is used to interact with a Prometheus server. It is basically a wrapper around a reqwest::Client and implements additional methods to execute PromQL queries and fetch metadata.
Usage
The following code contains just a few examples. See Client for the complete set of available 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();
// Execute a query using HTTP GET.
let q = "topk by (code) (5, prometheus_http_requests_total)";
let response = client.query(q).get().await?;
assert!(response.data().as_vector().is_some());
let q = r#"sum(prometheus_http_requests_total{code="200"})"#;
let response = client.query(q).get().await?;
let result = response.data().as_vector().expect("Expected result of type vector");
if !result.is_empty() {
let first = result.first().unwrap();
println!("Received a total of {} HTTP requests", first.sample().value());
}
// HTTP POST is also supported.
let q = "topk by (code) (5, prometheus_http_requests_total)";
let response = client.query(q).post().await?;
let result = response.data().as_vector().is_some();
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)?.get().await?;
assert!(response.data().as_vector().is_some());
let response = runtime_information("http://localhost:9090").await;
assert!(response.is_ok());
Ok(())
}
Features
At this point all available feature flags pertain to the Clients TLS configuration. They enable feature flags of
the reqwest
crate by the same name.
See the reqwest documentation for details on
these feature flags.
Also make sure that default features of prometheus-http-query
are disabled if you choose a TLS library other than
the default:
prometheus-http-query = { version = "0.6", default-features = false, features = ["rustls-tls"] }
Compatibility
The crate is generally compatible with Prometheus server >=2.30. However individual Client methods might
only work with the latest Prometheus server version when the corresponding API endpoint has only recently
been introduced.
Also some features may only work when the Prometheus server is started with certain flags. An example
are query statistics that can be enabled via RangeQueryBuilder::stats. The response
will not contain per-step stats unless Prometheus is started with --enable-feature=promql-per-step-stats
.
Error handling
All client methods that interact with the Prometheus API return a Result
. Also each request to the API
may fail at different stages. In general the following approach is taken to return the most significant
error to the caller:
- When the server’s response contains the header
Content-Type: application/json
the JSON body is parsed to the target type, regardless of the HTTP status code, because the Prometheus API provides more details on errors within the JSON response. A JSON response having"status": "success"
is deserialized to the target type of this function and returned withinResult::Ok
. A response with"status": "error"
is instead deserialized to a error::ApiError and returned withinResult::Err
. - Any other server HTTP 4xx/5xx responses without the proper header indicating a JSON-encoded body are
returned as Error::Client within
Result::Err
.
Supported operations
- Execute instant and range queries (GET or POST) 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 health and readiness
- Prometheus server flags
- Prometheus server build information
- Prometheus server runtime information
- Prometheus server config
Limitations
Re-exports
pub use self::error::Error;
Modules
- All types that may be returned when querying the Prometheus API.
Structs
- A client used to execute queries. It uses a reqwest::Client internally that manages connections for us.
- A builder object used to set some query parameters in the context of an instant query before sending the query on its way.
- A builder object used to set some query parameters in the context of a range query before sending the query on its way.
- A time series selector that is gradually built from a metric name and/or a set of label matchers.
Enums
- 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.