1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
use crate::error::{Error, MissingFieldError};
use crate::response::*;
use crate::selector::Selector;
use crate::util::{self, build_final_url, RuleType, TargetState, ToBaseUrl};
use reqwest::header::{HeaderMap, HeaderValue, IntoHeaderName, CONTENT_TYPE};
use reqwest::Method as HttpMethod;
use serde::Serialize;
use std::collections::HashMap;
use url::Url;
/// A builder object used to set some query parameters in the context
/// of an instant query before sending the query on its way.
#[derive(Clone)]
pub struct InstantQueryBuilder {
client: Client,
params: Vec<(&'static str, String)>,
headers: Option<HeaderMap<HeaderValue>>,
}
impl InstantQueryBuilder {
/// Set the evaluation timestamp (Unix timestamp in seconds, e.g. 1659182624).
/// If this is not set the evaluation timestamp will default to the current Prometheus
/// server time.
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries)
pub fn at(mut self, time: i64) -> Self {
self.params.push(("time", time.to_string()));
self
}
/// Set the evaluation timeout (milliseconds, e.g. 1000).
/// If this is not set the timeout will default to the value of the "-query.timeout" flag of the Prometheus server.
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries)
pub fn timeout(mut self, timeout: i64) -> Self {
self.params.push(("timeout", format!("{}ms", timeout)));
self
}
/// Instruct Prometheus to compile query statistics as part of the API response.
pub fn stats(mut self) -> Self {
self.params.push(("stats", String::from("all")));
self
}
/// Include an additional header to the request.
pub fn header<K: IntoHeaderName, T: Into<HeaderValue>>(mut self, name: K, value: T) -> Self {
self.headers
.get_or_insert_with(Default::default)
.append(name, value.into());
self
}
/// Execute the instant query (using HTTP GET) and return the parsed API response.
pub async fn get(self) -> Result<PromqlResult, Error> {
self.client
.send("api/v1/query", &self.params, HttpMethod::GET, self.headers)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Execute the instant query (using HTTP POST) and return the parsed API response.
/// Using a POST request is useful in the context of larger PromQL queries when
/// the size of the final URL may break Prometheus' or an intermediate proxies' URL
/// character limits.
pub async fn post(self) -> Result<PromqlResult, Error> {
self.client
.send("api/v1/query", &self.params, HttpMethod::POST, self.headers)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
}
/// A builder object used to set some query parameters in the context
/// of a range query before sending the query on its way.
#[derive(Clone)]
pub struct RangeQueryBuilder {
client: Client,
params: Vec<(&'static str, String)>,
headers: Option<HeaderMap<HeaderValue>>,
}
impl RangeQueryBuilder {
/// Set the evaluation timeout (milliseconds, e.g. 1000).
/// If this is not set the timeout will default to the value of the "-query.timeout" flag of the Prometheus server.
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries)
pub fn timeout(mut self, timeout: i64) -> Self {
self.params.push(("timeout", format!("{}ms", timeout)));
self
}
/// Instruct Prometheus to compile query statistics as part of the API response.
pub fn stats(mut self) -> Self {
self.params.push(("stats", String::from("all")));
self
}
/// Include an additional header to the request.
pub fn header<K: IntoHeaderName, T: Into<HeaderValue>>(mut self, name: K, value: T) -> Self {
self.headers
.get_or_insert_with(Default::default)
.append(name, value.into());
self
}
/// Execute the range query (using HTTP GET) and return the parsed API response.
pub async fn get(self) -> Result<PromqlResult, Error> {
self.client
.send(
"api/v1/query_range",
&self.params,
HttpMethod::GET,
self.headers,
)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Execute the instant query (using HTTP POST) and return the parsed API response.
/// Using a POST request is useful in the context of larger PromQL queries when
/// the size of the final URL may break Prometheus' or an intermediate proxies' URL
/// character limits.
pub async fn post(self) -> Result<PromqlResult, Error> {
self.client
.send(
"api/v1/query_range",
&self.params,
HttpMethod::POST,
self.headers,
)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
}
/// A client used to execute queries. It uses a [reqwest::Client] internally
/// that manages connections for us.
#[derive(Clone)]
pub struct Client {
pub(crate) client: reqwest::Client,
pub(crate) base_url: Url,
}
impl Default for Client {
/// Create a standard Client that sends requests to "http://127.0.0.1:9090/".
///
/// ```rust
/// use prometheus_http_query::Client;
///
/// let client = Client::default();
/// ```
fn default() -> Self {
Client {
client: reqwest::Client::new(),
base_url: Url::parse("http://127.0.0.1:9090/").unwrap(),
}
}
}
impl std::str::FromStr for Client {
type Err = crate::error::Error;
/// Create a Client from a custom base URL. Note that the API-specific
/// path segments (like `/api/v1/query`) are added automatically.
///
/// ```rust
/// use prometheus_http_query::Client;
/// use std::str::FromStr;
///
/// let client = Client::from_str("http://proxy.example.com/prometheus");
/// assert!(client.is_ok());
/// ```
fn from_str(url: &str) -> Result<Self, Self::Err> {
let client = Client {
base_url: url.to_base_url()?,
client: reqwest::Client::new(),
};
Ok(client)
}
}
impl std::convert::TryFrom<&str> for Client {
type Error = crate::error::Error;
/// Create a [Client] from a custom base URL. Note that the API-specific
/// path segments (like `/api/v1/query`) are added automatically.
///
/// ```rust
/// use prometheus_http_query::Client;
/// use std::convert::TryFrom;
///
/// let client = Client::try_from("http://proxy.example.com/prometheus");
/// assert!(client.is_ok());
/// ```
fn try_from(url: &str) -> Result<Self, Self::Error> {
let client = Client {
base_url: url.to_base_url()?,
client: reqwest::Client::new(),
};
Ok(client)
}
}
impl std::convert::TryFrom<String> for Client {
type Error = crate::error::Error;
/// Create a [Client] from a custom base URL. Note that the API-specific
/// path segments (like `/api/v1/query`) are added automatically.
///
/// ```rust
/// use prometheus_http_query::Client;
/// use std::convert::TryFrom;
///
/// let url = String::from("http://proxy.example.com/prometheus");
/// let client = Client::try_from(url);
/// assert!(client.is_ok());
/// ```
fn try_from(url: String) -> Result<Self, Self::Error> {
let client = Client {
base_url: url.to_base_url()?,
client: reqwest::Client::new(),
};
Ok(client)
}
}
impl Client {
/// Return a reference to the wrapped [reqwest::Client], i.e. to
/// use it for other requests unrelated to the Prometheus API.
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// // An amittedly bad example, but that is not the point.
/// let response = client
/// .inner()
/// .head("http://127.0.0.1:9090")
/// .send()
/// .await
/// .map_err(Error::Client)?;
///
/// // Prometheus does not allow HEAD requests.
/// assert_eq!(response.status(), reqwest::StatusCode::METHOD_NOT_ALLOWED);
/// Ok(())
/// }
/// ```
pub fn inner(&self) -> &reqwest::Client {
&self.client
}
/// Return a reference to the base URL that is used in requests to
/// the Prometheus API.
///
/// ```rust
/// use prometheus_http_query::Client;
/// use std::str::FromStr;
///
/// let client = Client::default();
///
/// assert_eq!(client.base_url().as_str(), "http://127.0.0.1:9090/");
///
/// let client = Client::from_str("https://proxy.example.com:8443/prometheus").unwrap();
///
/// assert_eq!(client.base_url().as_str(), "https://proxy.example.com:8443/prometheus");
/// ```
pub fn base_url(&self) -> &Url {
&self.base_url
}
/// Create a Client from a custom [reqwest::Client] and URL.
/// This way you can account for all extra parameters (e.g. x509 authentication)
/// that may be needed to connect to Prometheus or an intermediate proxy,
/// by building it into the [reqwest::Client].
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// fn main() -> Result<(), Error> {
/// let client = {
/// let c = reqwest::Client::builder()
/// .no_proxy()
/// .build()
/// .map_err(Error::Client)?;
/// Client::from(c, "https://prometheus.example.com")
/// };
///
/// assert!(client.is_ok());
/// Ok(())
/// }
/// ```
pub fn from(client: reqwest::Client, url: &str) -> Result<Self, Error> {
let base_url = url.to_base_url()?;
Ok(Client { base_url, client })
}
/// Build and send the final HTTP request. Parse the result as JSON if the
/// `Content-Type` header indicates that the payload is JSON. Otherwise it is
/// assumed that an intermediate proxy sends a plain text error.
async fn send<T: Serialize>(
&self,
path: &str,
params: &T,
method: HttpMethod,
headers: Option<HeaderMap<HeaderValue>>,
) -> Result<ApiResponse, Error> {
let url = build_final_url(self.base_url.clone(), path);
let mut request = match method {
HttpMethod::GET => self.client.get(url).query(params),
HttpMethod::POST => self.client.post(url).form(params),
_ => unreachable!(),
};
if let Some(headers) = headers {
request = request.headers(headers);
}
let response = request.send().await.map_err(Error::Client)?;
let header = CONTENT_TYPE;
if util::is_json(response.headers().get(header)) {
response.json().await.map_err(Error::Client)
} else {
Err(Error::Client(response.error_for_status().unwrap_err()))
}
}
/// Create an [InstantQueryBuilder] from a PromQL query allowing you to set some query parameters
/// (e.g. evaluation timeout) before finally sending the instant query to the server.
///
/// # Arguments
/// * `query` - PromQL query to exeute
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#instant-queries)
///
/// ```rust
/// use prometheus_http_query::{Error, Client};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let response = client.query("prometheus_http_request_total").get().await?;
///
/// assert!(response.data().as_vector().is_some());
///
/// // Or make a POST request.
/// let response = client.query("prometheus_http_request_total").post().await?;
///
/// assert!(response.data().as_vector().is_some());
///
/// Ok(())
/// }
/// ```
pub fn query(&self, query: impl std::string::ToString) -> InstantQueryBuilder {
InstantQueryBuilder {
client: self.clone(),
params: vec![("query", query.to_string())],
headers: Default::default(),
}
}
/// Create a [RangeQueryBuilder] from a PromQL query allowing you to set some query parameters
/// (e.g. evaluation timeout) before finally sending the range query to the server.
///
/// # Arguments
/// * `query` - PromQL query to exeute
/// * `start` - Start timestamp as Unix timestamp (seconds)
/// * `end` - End timestamp as Unix timestamp (seconds)
/// * `step` - Query resolution step width as float number of seconds
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let q = "prometheus_http_requests_total";
///
/// let response = client.query_range(q, 1648373100, 1648373300, 10.0).get().await?;
///
/// assert!(response.data().as_matrix().is_some());
///
/// // Or make a POST request.
/// let response = client.query_range(q, 1648373100, 1648373300, 10.0).post().await?;
///
/// assert!(response.data().as_matrix().is_some());
///
/// Ok(())
/// }
/// ```
pub fn query_range(
&self,
query: impl std::string::ToString,
start: i64,
end: i64,
step: f64,
) -> RangeQueryBuilder {
RangeQueryBuilder {
client: self.clone(),
params: vec![
("query", query.to_string()),
("start", start.to_string()),
("end", end.to_string()),
("step", step.to_string()),
],
headers: Default::default(),
}
}
/// Find time series that match certain label sets ([Selector]s).
///
/// # Arguments
/// * `selectors` - List of [Selector]s that select the series to return. Must not be empty.
/// * `start` - Start timestamp as Unix timestamp (seconds). Optional.
/// * `end` - End timestamp as Unix timestamp (seconds). Optional.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#finding-series-by-label-matchers)
///
/// ```rust
/// use prometheus_http_query::{Client, Selector, Error};
///
/// #[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(())
/// }
/// ```
pub async fn series(
&self,
selectors: &[Selector<'_>],
start: Option<i64>,
end: Option<i64>,
) -> Result<Vec<HashMap<String, String>>, Error> {
if selectors.is_empty() {
return Err(Error::EmptySeriesSelector);
}
let mut params = vec![];
if let Some(s) = start {
params.push(("start", s.to_string()));
}
if let Some(e) = end {
params.push(("end", e.to_string()));
}
let mut matchers: Vec<(&str, String)> = selectors
.iter()
.map(|s| ("match[]", s.to_string()))
.collect();
params.append(&mut matchers);
self.send("api/v1/series", ¶ms, HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Retrieve label names.
///
/// # Arguments
/// * `selectors` - List of [Selector]s to restrict the set of time series to read the label names from. Optional.
/// * `start` - Start timestamp as Unix timestamp (seconds). Optional.
/// * `end` - End timestamp as Unix timestamp (seconds). Optional.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#getting-label-names)
///
/// ```rust
/// use prometheus_http_query::{Client, Selector, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// // To retrieve a list of all labels:
/// let response = client.label_names(None, None, None).await;
///
/// assert!(response.is_ok());
///
/// // Use a selector to retrieve a list of labels that appear in specific time series:
/// let s1 = Selector::new()
/// .eq("handler", "/api/v1/query");
///
/// let s2 = Selector::new()
/// .eq("job", "node")
/// .regex_eq("mode", ".+");
///
/// let set = Some(vec![s1, s2]);
///
/// let response = client.label_names(set, None, None).await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn label_names(
&self,
selectors: Option<Vec<Selector<'_>>>,
start: Option<i64>,
end: Option<i64>,
) -> Result<Vec<String>, Error> {
let mut params = vec![];
if let Some(s) = &start {
params.push(("start", s.to_string()));
}
if let Some(e) = &end {
params.push(("end", e.to_string()));
}
if let Some(items) = selectors {
let mut matchers: Vec<(&str, String)> =
items.iter().map(|s| ("match[]", s.to_string())).collect();
params.append(&mut matchers);
}
self.send("api/v1/labels", ¶ms, HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Retrieve all label values for a specific label name.
///
/// # Arguments
/// * `label` - Name of the label to return all occuring label values for.
/// * `selectors` - List of [Selector]s to restrict the set of time series to read the label values from. Optional.
/// * `start` - Start timestamp as Unix timestamp (seconds). Optional.
/// * `end` - End timestamp as Unix timestamp (seconds). Optional.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-label-values)
///
/// ```rust
/// use prometheus_http_query::{Client, Selector, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// // To retrieve a list of all label values for a specific label name:
/// let response = client.label_values("job", None, None, None).await;
///
/// assert!(response.is_ok());
///
/// // To retrieve a list of label values of labels that appear in specific time series:
/// let s1 = Selector::new()
/// .regex_eq("instance", ".+");
///
/// let set = Some(vec![s1]);
///
/// let response = client.label_values("job", set, None, None).await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn label_values(
&self,
label: &str,
selectors: Option<Vec<Selector<'_>>>,
start: Option<i64>,
end: Option<i64>,
) -> Result<Vec<String>, Error> {
let mut params = vec![];
if let Some(s) = &start {
params.push(("start", s.to_string()));
}
if let Some(e) = &end {
params.push(("end", e.to_string()));
}
if let Some(items) = selectors {
let mut matchers: Vec<(&str, String)> =
items.iter().map(|s| ("match[]", s.to_string())).collect();
params.append(&mut matchers);
}
let path = format!("api/v1/label/{}/values", label);
self.send(&path, ¶ms, HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Query the current state of target discovery.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#targets)
///
/// ```rust
/// use prometheus_http_query::{Client, Error, TargetState};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let response = client.targets(None).await;
///
/// assert!(response.is_ok());
///
/// // Filter targets by type:
/// let response = client.targets(Some(TargetState::Active)).await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn targets(&self, state: Option<TargetState>) -> Result<Targets, Error> {
let mut params = vec![];
if let Some(s) = &state {
params.push(("state", s.to_string()))
}
self.send("api/v1/targets", ¶ms, HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Retrieve a list of rule groups of recording and alerting rules.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#rules)
///
/// ```rust
/// 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());
///
/// // Filter rules by type:
/// let response = client.rules(Some(RuleType::Alert)).await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn rules(&self, rule_type: Option<RuleType>) -> Result<Vec<RuleGroup>, Error> {
let mut params = vec![];
if let Some(s) = rule_type {
params.push(("type", s.to_string()))
}
self.send("api/v1/rules", ¶ms, HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| {
res.as_object()
.unwrap()
.get("groups")
.ok_or(Error::MissingField(MissingFieldError("groups")))
.and_then(|d| {
serde_json::from_value(d.to_owned()).map_err(Error::ResponseParse)
})
})
}
/// Retrieve a list of active alerts.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#alerts)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let response = client.alerts().await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn alerts(&self) -> Result<Vec<Alert>, Error> {
self.send("api/v1/alerts", &(), HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| {
res.as_object()
.unwrap()
.get("alerts")
.ok_or(Error::MissingField(MissingFieldError("alerts")))
.and_then(|d| {
serde_json::from_value(d.to_owned()).map_err(Error::ResponseParse)
})
})
}
/// Retrieve a list of flags that Prometheus was configured with.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#flags)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let response = client.flags().await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn flags(&self) -> Result<HashMap<String, String>, Error> {
self.send("api/v1/status/flags", &(), HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Retrieve Prometheus server build information.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#build-information)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let response = client.build_information().await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn build_information(&self) -> Result<BuildInformation, Error> {
self.send("api/v1/status/buildinfo", &(), HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Retrieve Prometheus server runtime information.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#runtime-information)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let response = client.runtime_information().await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn runtime_information(&self) -> Result<RuntimeInformation, Error> {
self.send("api/v1/status/runtimeinfo", &(), HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Retrieve Prometheus TSDB statistics.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#tsdb-stats)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let response = client.tsdb_statistics().await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn tsdb_statistics(&self) -> Result<TsdbStatistics, Error> {
self.send("api/v1/status/tsdb", &(), HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Retrieve WAL replay statistics.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#wal-replay-stats)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let response = client.wal_replay_statistics().await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn wal_replay_statistics(&self) -> Result<WalReplayStatistics, Error> {
self.send("api/v1/status/walreplay", &(), HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Query the current state of alertmanager discovery.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#alertmanagers)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// let response = client.alertmanagers().await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn alertmanagers(&self) -> Result<Alertmanagers, Error> {
self.send("api/v1/alertmanagers", &(), HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Retrieve metadata about metrics that are currently scraped from targets, along with target information.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-target-metadata)
///
/// ```rust
/// use prometheus_http_query::{Client, Error, Selector};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// // Retrieve metadata for a specific metric from all targets.
/// let response = client.target_metadata(Some("go_routines"), None, None).await;
///
/// assert!(response.is_ok());
///
/// // Retrieve metric metadata from specific targets.
/// let s = Selector::new().eq("job", "prometheus");
///
/// let response = client.target_metadata(None, Some(&s), None).await;
///
/// assert!(response.is_ok());
///
/// // Retrieve metadata for a specific metric from targets that match a specific label set.
/// let s = Selector::new().eq("job", "node");
///
/// let response = client.target_metadata(Some("node_cpu_seconds_total"), Some(&s), None).await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn target_metadata(
&self,
metric: Option<&str>,
match_target: Option<&Selector<'_>>,
limit: Option<usize>,
) -> Result<Vec<TargetMetadata>, Error> {
let mut params = vec![];
if let Some(m) = metric {
params.push(("metric", m.to_string()))
}
if let Some(m) = match_target {
params.push(("match_target", m.to_string()))
}
if let Some(l) = &limit {
params.push(("limit", l.to_string()))
}
self.send("api/v1/targets/metadata", ¶ms, HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Retrieve metadata about metrics that are currently scraped from targets.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/querying/api/#querying-metric-metadata)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
///
/// // Retrieve metadata for a all metrics.
/// let response = client.metric_metadata(None, None).await;
///
/// assert!(response.is_ok());
///
/// // Limit the number of returned metrics
/// let response = client.metric_metadata(None, Some(10)).await;
///
/// assert!(response.is_ok());
///
/// // Retrieve metadata of a specific metric.
/// let response = client.metric_metadata(Some("go_routines"), None).await;
///
/// assert!(response.is_ok());
///
/// Ok(())
/// }
/// ```
pub async fn metric_metadata(
&self,
metric: Option<&str>,
limit: Option<usize>,
) -> Result<HashMap<String, Vec<MetricMetadata>>, Error> {
let mut params = vec![];
if let Some(m) = &metric {
params.push(("metric", m.to_string()))
}
if let Some(l) = &limit {
params.push(("limit", l.to_string()))
}
self.send("api/v1/metadata", ¶ms, HttpMethod::GET, None)
.await
.and_then(map_api_response)
.and_then(move |res| serde_json::from_value(res).map_err(Error::ResponseParse))
}
/// Check Prometheus server health.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/management_api/#health-check)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
/// assert!(client.is_server_healthy().await?);
/// Ok(())
/// }
/// ```
pub async fn is_server_healthy(&self) -> Result<bool, Error> {
let url = build_final_url(self.base_url.clone(), "-/healthy");
self.client
.get(url)
.send()
.await
.map_err(Error::Client)?
.error_for_status()
.map_err(Error::Client)
.map(|_| true)
}
/// Check Prometheus server readiness.
///
/// See also: [Prometheus API documentation](https://prometheus.io/docs/prometheus/latest/management_api/#readiness-check)
///
/// ```rust
/// use prometheus_http_query::{Client, Error};
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), Error> {
/// let client = Client::default();
/// assert!(client.is_server_ready().await?);
/// Ok(())
/// }
/// ```
pub async fn is_server_ready(&self) -> Result<bool, Error> {
let url = build_final_url(self.base_url.clone(), "-/ready");
self.client
.get(url)
.send()
.await
.map_err(Error::Client)?
.error_for_status()
.map_err(Error::Client)
.map(|_| true)
}
}
// Map the API response object to a Result:
// Data is returned as is, errors within the response body are converted to
// this crate's error type.
#[inline]
fn map_api_response(response: ApiResponse) -> Result<serde_json::Value, Error> {
match response {
ApiResponse::Success { data } => Ok(data),
ApiResponse::Error(e) => Err(Error::ApiError(e)),
}
}