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;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::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 time series Selectors
or providing selectors in their native string syntax, depending on what better suits your use case.
More metadata queries are available, e.g. methods to retrieve label names and values.
use prometheus_http_query::{Client, Selector};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::Error> {
let client = Client::default();
// Using `Selector`.
{
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());
}
// Using the free-form API.
{
let response = client.series()
.match_many(&["{handler=\"/api/v1/query\"}", "{job=\"node\", mode=\".+\"}"])
.get()
.await;
assert!(response.is_ok());
}
Ok(())
}§Rules & Alerts
Retrieve recording/alerting rules and active alerts.
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());
// Only request alerting rules instead:
let response = client.rules().kind(RuleKind::Alerting).get().await;
assert!(response.is_ok());
// Request active alerts:
let response = client.alerts().get().await;
assert!(response.is_ok());
Ok(())
}§Convenience functions for one-off requests
use prometheus_http_query::{query, runtime_information};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), anyhow::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")?.get().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.7", 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.
The minimum recommended Prometheus server version is v2.46.
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 header
Content-Type: application/json(or variants thereof) the JSON body is parsed to the target type, regardless of the HTTP status code, since Prometheus returns elaborate error messages within the HTTP body in any case. 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 aerror::PrometheusErrorand returned withinResult::Err. - Any other server HTTP 4xx/5xx responses without the proper header indicating a JSON-encoded body are
returned as
Error::ClientwithinResult::Err. For example, this may happen when an intermediate proxy server fails to handle a request and subsequently return a plain text error message and a non-2xx HTTP status code.
§Supported operations
-
Instant queries via
Client::query -
Range queries via
Client::query_range - Query cost estimation
- Formatting query expressions
- Parsing PromQL expression into an abstract syntax tree
-
Finding series by label matchers via
Client::series -
Getting label names via
Client::label_names -
Querying label values via
Client::label_values - Searching metric names, label names and label values
- Querying exemplars
- Scrape pools
-
Targets via
Client::targets - Relabel steps
-
Rules via
Client::rules -
Alerts via
Client::alerts -
Querying target metadata via
Client::target_metadata -
Querying metric metadata via
Client::metric_metadata -
Alertmanagers via
Client::alertmanagers - Prometheus server config
-
Prometheus server flags via
Client::flags -
Prometheus server runtime information via
Client::runtime_information -
Prometheus server build information via
Client::build_information -
Prometheus server TSDB stats via
Client::tsdb_statistics - Prometheus server TSDB blocks
-
WAL Replay Stats via
Client::wal_replay_statistics - Prometheus server self metrics
-
Prometheus server health via
Client::is_server_healthy -
Prometheus server readiness via
Client::is_server_ready
§Limitations
Re-exports§
Modules§
- error
- All error types that are returned by methods in this crate.
- response
- All types that are returned when querying the Prometheus API.
Structs§
- Alertmanagers
Query Builder - Provides a builder to choose how the response from Prometheus is returned to the caller.
- Alerts
Query Builder - Provides a builder to choose how the response from Prometheus is returned to the caller.
- Build
Information Query Builder - Provides a builder to choose how the response from Prometheus is returned to the caller.
- Client
- A client used to execute queries. It uses a
reqwest::Clientinternally that manages connections for us. - Duration
- A wrapper around
time::Durationthat is used to deserialize responses or verify time durations before sending them to Prometheus. - Flags
Query Builder - Provides a builder to choose how the response from Prometheus is returned to the caller.
- Instant
Query Builder - Provides a builder to set some query parameters in the context of an instant query before sending it to Prometheus.
- Label
Names Query Builder - Provides methods to build a query to retrieve label names from Prometheus.
- Label
Values Query Builder - Provides methods to build a query to retrieve label values for a specific label from Prometheus.
- Metric
Metadata Query Builder - Provides methods to build a query to the metric metadata endpoint and send it to Prometheus.
- Range
Query Builder - Provides a builder to set some query parameters in the context of a range query before sending it to Prometheus.
- Rules
Query Builder - Provides methods to build a query to the rules endpoint and send it to Prometheus.
- Runtime
Information Query Builder - Provides a builder to choose how the response from Prometheus is returned to the caller.
- Selector
- A time series selector that is gradually built from a metric name and/or a set of label matchers.
- Series
Query Builder - Provides methods to build a query to the series endpoint and send it to Prometheus.
- Target
Metadata Query Builder - Provides methods to build a query to the target metadata endpoint and send it to Prometheus.
- Targets
Query Builder - Provides methods to build a query to the targets endpoint and send it to Prometheus.
- Tsdb
Statistics Query Builder - Provides a builder to choose how the response from Prometheus is returned to the caller.
- WalReplay
Statistics Query Builder - Provides a builder to choose how the response from Prometheus is returned to the caller.
Enums§
- Alert
State - A helper type to represent possible rule health states.
- Rule
Health - A helper enum to represent possible rule health states.
- Rule
Kind - A helper enum to filter rules by type.
- Target
Health - A helper enum to represent possible target health states.
- Target
State - A helper enum to filter targets by state.
Functions§
- alertmanagers
- Query the current state of alertmanager discovery.
- alerts
- Retrieve a list of active alerts.
- build_
information - Retrieve Prometheus server build information.
- flags
- Retrieve a list of flags that Prometheus was configured with.
- is_
server_ healthy - Check Prometheus server health.
- is_
server_ ready - Check Prometheus server readiness.
- label_
names - Create a
LabelNamesQueryBuilderto apply filters to a query for the label names endpoint before sending it to Prometheus. - label_
values - Create a
LabelValuesQueryBuilderto apply filters to a query for the label values endpoint before sending it to Prometheus. - metric_
metadata - Create a
MetricMetadataQueryBuilderto apply filters to a metric metadata query before sending it to Prometheus. - query
- Execute an instant query.
- query_
range - Execute a range query.
- rules
- Create a
RulesQueryBuilderto apply filters to the rules query before sending it to Prometheus. - runtime_
information - Retrieve Prometheus server runtime information.
- series
- Create a
SeriesQueryBuilderto apply filters to a series metadata query before sending it to Prometheus. - target_
metadata - Create a
TargetMetadataQueryBuilderto apply filters to a target metadata query before sending it to Prometheus. - targets
- Query the current state of target discovery.
- tsdb_
statistics - Retrieve various cardinality statistics about the Prometheus TSDB.
- wal_
replay_ statistics - Retrieve information about the WAL replay.