prometheus_http_query/lib.rs
1//! This crate provides an interface to the [Prometheus HTTP API](https://prometheus.io/docs/prometheus/latest/querying/api/).
2//! The [`Client`] is used to interact with a Prometheus server. It is basically a wrapper around a [`reqwest::Client`] and implements
3//! additional methods to execute PromQL queries and fetch metadata.
4//!
5//! # Usage
6//!
7//! The following code contains just a few examples. See [`Client`] for the complete set of available functions.
8//!
9//!
10//! ## Initialize a client
11//!
12//! The [`Client`] can be constructed in various ways depending on your need to add customizations.
13//!
14//! ```rust
15//! use prometheus_http_query::Client;
16//! use std::str::FromStr;
17//!
18//! // In the most general case the default implementation is used to create the client.
19//! // Requests will be sent to "http://127.0.0.1:9090 (the default listen address and port of the Prometheus server).
20//! let client = Client::default();
21//!
22//! // Provide an alternative URL if you need to. The URL will be checked for correctness.
23//! use std::convert::TryFrom;
24//! let client = Client::try_from("https://prometheus.example.com").unwrap();
25//!
26//! // The greatest flexibility is offered by initializing a reqwest::Client first with
27//! // all needed customizations and passing it along.
28//! let client = {
29//! let c = reqwest::Client::builder().no_proxy().build().unwrap();
30//! Client::from(c, "https://prometheus.example.com").unwrap();
31//! };
32//! ```
33//!
34//! ## Execute PromQL queries
35//!
36//! ```rust
37//! use prometheus_http_query::Client;
38//!
39//! #[tokio::main(flavor = "current_thread")]
40//! async fn main() -> Result<(), anyhow::Error> {
41//! let client = Client::default();
42//!
43//! // Execute a query using HTTP GET.
44//! let q = "topk by (code) (5, prometheus_http_requests_total)";
45//! let response = client.query(q).get().await?;
46//! assert!(response.data().as_vector().is_some());
47//!
48//! let q = r#"sum(prometheus_http_requests_total{code="200"})"#;
49//! let response = client.query(q).get().await?;
50//! let result = response.data().as_vector().expect("Expected result of type vector");
51//!
52//! if !result.is_empty() {
53//! let first = result.first().unwrap();
54//! println!("Received a total of {} HTTP requests", first.sample().value());
55//! }
56//!
57//! // HTTP POST is also supported.
58//! let q = "topk by (code) (5, prometheus_http_requests_total)";
59//! let response = client.query(q).post().await?;
60//! let result = response.data().as_vector().is_some();
61//!
62//! Ok(())
63//! }
64//! ```
65//!
66//! ## Metadata queries
67//!
68//! Retrieve a list of time series that match a certain label set by providing one or more time series [`Selector`]s
69//! or providing selectors in their native string syntax, depending on what better suits your use case.<br>
70//! More metadata queries are available, e.g. methods to retrieve label names and values.
71//!
72//! ```rust
73//! use prometheus_http_query::{Client, Selector};
74//!
75//! #[tokio::main(flavor = "current_thread")]
76//! async fn main() -> Result<(), anyhow::Error> {
77//! let client = Client::default();
78//!
79//! // Using `Selector`.
80//! {
81//! let s1 = Selector::new()
82//! .eq("handler", "/api/v1/query");
83//!
84//! let s2 = Selector::new()
85//! .eq("job", "node")
86//! .regex_eq("mode", ".+");
87//!
88//! let response = client.series().match_many(&[s1, s2]).get().await;
89//!
90//! assert!(response.is_ok());
91//! }
92//!
93//! // Using the free-form API.
94//! {
95//! let response = client.series()
96//! .match_many(&["{handler=\"/api/v1/query\"}", "{job=\"node\", mode=\".+\"}"])
97//! .get()
98//! .await;
99//!
100//! assert!(response.is_ok());
101//! }
102//!
103//! Ok(())
104//! }
105//! ```
106//!
107//! ## Rules & Alerts
108//!
109//! Retrieve recording/alerting rules and active alerts.
110//!
111//! ```rust
112//! use prometheus_http_query::{Client, RuleKind};
113//!
114//! #[tokio::main(flavor = "current_thread")]
115//! async fn main() -> Result<(), anyhow::Error> {
116//! let client = Client::default();
117//!
118//! let response = client.rules().get().await;
119//!
120//! assert!(response.is_ok());
121//!
122//! // Only request alerting rules instead:
123//! let response = client.rules().kind(RuleKind::Alerting).get().await;
124//!
125//! assert!(response.is_ok());
126//!
127//! // Request active alerts:
128//! let response = client.alerts().get().await;
129//!
130//! assert!(response.is_ok());
131//!
132//! Ok(())
133//! }
134//! ```
135//!
136//! ## Convenience functions for one-off requests
137//!
138//! ```rust
139//! use prometheus_http_query::{query, runtime_information};
140//!
141//! #[tokio::main(flavor = "current_thread")]
142//! async fn main() -> Result<(), anyhow::Error> {
143//! let q = "topk by (code) (5, prometheus_http_requests_total)";
144//! let response = query("http://localhost:9090", q)?.get().await?;
145//!
146//! assert!(response.data().as_vector().is_some());
147//!
148//! let response = runtime_information("http://localhost:9090")?.get().await;
149//!
150//! assert!(response.is_ok());
151//!
152//! Ok(())
153//! }
154//! ```
155//!
156//! # Features
157//!
158//! At this point all available feature flags pertain to the [`Client`]s TLS configuration. They enable feature flags of
159//! the `reqwest` crate by the same name.<br>
160//! See the [reqwest documentation](https://docs.rs/reqwest/0.11.14/reqwest/index.html#optional-features) for details on
161//! these feature flags.<br>
162//! Also make sure that default features of `prometheus-http-query` are disabled if you choose a TLS library other than
163//! the default:
164//!
165//! `prometheus-http-query = { version = "0.7", default-features = false, features = ["rustls-tls"] }`
166//!
167//! # Compatibility
168//!
169//! The crate is generally compatible with Prometheus server >=2.30. However individual [`Client`] methods might
170//! only work with the latest Prometheus server version when the corresponding API endpoint has only recently
171//! been introduced.<br>
172//! The minimum recommended Prometheus server version is v2.46.<br>
173//! Also some features may only work when the Prometheus server is started with certain flags. An example
174//! are query statistics that can be enabled via [`RangeQueryBuilder::stats`]. The response
175//! will not contain per-step stats unless Prometheus is started with `--enable-feature=promql-per-step-stats`.
176//!
177//! # Error handling
178//!
179//! All [`Client`] methods that interact with the Prometheus API return a `Result`. Also each request to the API
180//! may fail at different stages. In general the following approach is taken to return the most significant
181//! error to the caller:
182//! - When the server's response contains header `Content-Type: application/json` (or variants thereof) the
183//! JSON body is parsed to the target type, regardless of the HTTP status code, since Prometheus returns elaborate
184//! error messages within the HTTP body in any case.
185//! A JSON response having `"status": "success"` is deserialized to the target type of this function and returned
186//! within `Result::Ok`. A response with `"status": "error"` is instead deserialized to a [`error::PrometheusError`]
187//! and returned within `Result::Err`.
188//! - Any other server HTTP 4xx/5xx responses without the proper header indicating a JSON-encoded body are
189//! returned as [`Error::Client`] within `Result::Err`. For example, this may happen when an intermediate proxy server
190//! fails to handle a request and subsequently return a plain text error message and a non-2xx HTTP status code.
191//!
192//! # Supported operations
193//!
194//! - [x] [Instant queries](https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries) via [`Client::query`]
195//! - [x] [Range queries](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries) via [`Client::query_range`]
196//! - [ ] [Query cost estimation](https://prometheus.io/docs/prometheus/latest/querying/api/#query-cost)
197//! - [ ] [Formatting query expressions](https://prometheus.io/docs/prometheus/latest/querying/api/#formatting-query-expressions)
198//! - [ ] [Parsing PromQL expression into an abstract syntax tree](https://prometheus.io/docs/prometheus/latest/querying/api/#parsing-a-promql-expressions-into-a-abstract-syntax-tree-ast)
199//! - [x] [Finding series by label matchers](https://prometheus.io/docs/prometheus/latest/querying/api/#finding-series-by-label-matchers) via [`Client::series`]
200//! - [x] [Getting label names](https://prometheus.io/docs/prometheus/latest/querying/api/#getting-label-names) via [`Client::label_names`]
201//! - [x] [Querying label values](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-label-values) via [`Client::label_values`]
202//! - [ ] [Searching metric names, label names and label values](https://prometheus.io/docs/prometheus/latest/querying/api/#searching-metric-names-label-names-and-label-values)
203//! - [ ] [Querying exemplars](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-exemplars)
204//! - [ ] [Scrape pools](https://prometheus.io/docs/prometheus/latest/querying/api/#scrape-pools)
205//! - [x] [Targets](https://prometheus.io/docs/prometheus/latest/querying/api/#targets) via [`Client::targets`]
206//! - [ ] [Relabel steps](https://prometheus.io/docs/prometheus/latest/querying/api/#relabel-steps)
207//! - [x] [Rules](https://prometheus.io/docs/prometheus/latest/querying/api/#rules) via [`Client::rules`]
208//! - [x] [Alerts](https://prometheus.io/docs/prometheus/latest/querying/api/#alerts) via [`Client::alerts`]
209//! - [x] [Querying target metadata](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-target-metadata) via [`Client::target_metadata`]
210//! - [x] [Querying metric metadata](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-metric-metadata) via [`Client::metric_metadata`]
211//! - [x] [Alertmanagers](https://prometheus.io/docs/prometheus/latest/querying/api/#alertmanagers) via [`Client::alertmanagers`]
212//! - [ ] [Prometheus server config](https://prometheus.io/docs/prometheus/latest/querying/api/#config)
213//! - [x] [Prometheus server flags](https://prometheus.io/docs/prometheus/latest/querying/api/#flags) via [`Client::flags`]
214//! - [x] [Prometheus server runtime information](https://prometheus.io/docs/prometheus/latest/querying/api/#runtime-information) via [`Client::runtime_information`]
215//! - [x] [Prometheus server build information](https://prometheus.io/docs/prometheus/latest/querying/api/#build-information) via [`Client::build_information`]
216//! - [x] [Prometheus server TSDB stats](https://prometheus.io/docs/prometheus/latest/querying/api/#tsdb-stats) via [`Client::tsdb_statistics`]
217//! - [ ] [Prometheus server TSDB blocks](https://prometheus.io/docs/prometheus/latest/querying/api/#tsdb-blocks)
218//! - [x] [WAL Replay Stats](https://prometheus.io/docs/prometheus/latest/querying/api/#wal-replay-stats) via [`Client::wal_replay_statistics`]
219//! - [ ] [Prometheus server self metrics](https://prometheus.io/docs/prometheus/latest/querying/api/#self-metrics)
220//! - [x] [Prometheus server health](https://prometheus.io/docs/prometheus/latest/management_api/#health-check) via [`Client::is_server_healthy`]
221//! - [x] [Prometheus server readiness](https://prometheus.io/docs/prometheus/latest/management_api/#readiness-check) via [`Client::is_server_ready`]
222//!
223//! # Limitations
224//!
225//! * Some [`Client`] methods may not work with older versions of the Prometheus server.
226//! * The [String](https://prometheus.io/docs/prometheus/latest/querying/api/#strings) result type is not supported
227//! as it is currently not used by Prometheus.
228//! * Warnings contained in an API response will be ignored.
229mod client;
230mod direct;
231pub mod error;
232pub mod response;
233mod selector;
234mod util;
235pub use self::client::{
236 AlertmanagersQueryBuilder, AlertsQueryBuilder, BuildInformationQueryBuilder, Client,
237 FlagsQueryBuilder, InstantQueryBuilder, LabelNamesQueryBuilder, LabelValuesQueryBuilder,
238 MetricMetadataQueryBuilder, RangeQueryBuilder, RulesQueryBuilder,
239 RuntimeInformationQueryBuilder, SeriesQueryBuilder, TargetMetadataQueryBuilder,
240 TargetsQueryBuilder, TsdbStatisticsQueryBuilder, WalReplayStatisticsQueryBuilder,
241};
242pub use self::direct::*;
243pub use self::error::Error;
244pub use self::selector::Selector;
245pub use self::util::AlertState;
246pub use self::util::Duration;
247pub use self::util::RuleHealth;
248pub use self::util::RuleKind;
249pub use self::util::TargetHealth;
250pub use self::util::TargetState;
251
252// Re-exported for users' convenience.
253pub use reqwest;