icinga2_api/api/
blocking.rs1use std::{path::Path, str::from_utf8};
4
5use serde::{Serialize, de::DeserializeOwned};
6
7use crate::{
8 config::{Icinga2Auth, Icinga2Instance},
9 types::rest::{RestApiEndpoint, RestApiResponse},
10};
11
12#[derive(Debug, Clone)]
14pub struct Icinga2 {
15 client: reqwest::blocking::Client,
17 pub url: url::Url,
19 pub username: String,
21 auth: Icinga2Auth,
23}
24
25impl Icinga2 {
26 pub fn from_instance_config(config: &Icinga2Instance) -> Result<Self, crate::error::Error> {
33 Self::from_parts(
34 &config.url,
35 config.ca_certificate.as_deref(),
36 Icinga2Auth::Basic {
37 username: config.username.clone(),
38 password: config.password.clone(),
39 },
40 )
41 }
42
43 pub fn from_parts(
54 url: &str,
55 ca_certificate: Option<&Path>,
56 auth: Icinga2Auth,
57 ) -> Result<Self, crate::error::Error> {
58 let parts = crate::config::client_parts(url, ca_certificate, &auth)?;
59 let client_builder = reqwest::blocking::ClientBuilder::new()
60 .user_agent(concat!(
61 env!("CARGO_PKG_NAME"),
62 "/",
63 env!("CARGO_PKG_VERSION")
64 ))
65 .default_headers(parts.headers);
66 let client_builder = if let Some(ca_cert) = parts.ca_certificate {
67 client_builder.tls_certs_only([ca_cert])
68 } else {
69 client_builder
70 };
71 let client_builder = if let Some(identity) = parts.identity {
72 client_builder.identity(identity)
73 } else {
74 client_builder
75 };
76 let client = client_builder
77 .build()
78 .map_err(crate::error::Error::CouldNotBuildReqwestClientFromSuppliedInformation)?;
79 Ok(Self {
80 client,
81 url: parts.url,
82 username: auth.username().to_owned(),
83 auth,
84 })
85 }
86
87 fn authenticate(
89 &self,
90 req: reqwest::blocking::RequestBuilder,
91 ) -> reqwest::blocking::RequestBuilder {
92 match &self.auth {
93 Icinga2Auth::Basic { username, password } => req.basic_auth(username, Some(password)),
94 Icinga2Auth::ClientCertificate { .. } => req,
95 }
96 }
97
98 pub fn from_config_file(path: &Path) -> Result<Self, crate::error::Error> {
105 let icinga_instance = Icinga2Instance::from_config_file(path)?;
106 Self::from_instance_config(&icinga_instance)
107 }
108
109 pub fn rest<ApiEndpoint, Res>(
115 &self,
116 api_endpoint: ApiEndpoint,
117 ) -> Result<Res, crate::error::Error>
118 where
119 ApiEndpoint: RestApiEndpoint,
120 <ApiEndpoint as RestApiEndpoint>::RequestBody: Clone + Serialize + std::fmt::Debug,
121 Res: DeserializeOwned + std::fmt::Debug + RestApiResponse<ApiEndpoint>,
122 {
123 let method = api_endpoint.method()?;
124 let url = api_endpoint.url(&self.url)?;
125 let request_body: Option<std::borrow::Cow<<ApiEndpoint as RestApiEndpoint>::RequestBody>> =
126 api_endpoint.request_body()?;
127 let actual_method = if method == reqwest::Method::GET && request_body.is_some() {
128 reqwest::Method::POST
129 } else {
130 method.to_owned()
131 };
132 let mut req = self.client.request(actual_method, url.to_owned());
133 if method == reqwest::Method::GET && request_body.is_some() {
134 tracing::trace!("Sending GET request with body as POST via X-HTTP-Method-Override");
135 req = req.header(
136 "X-HTTP-Method-Override",
137 reqwest::header::HeaderValue::from_static("GET"),
138 );
139 }
140 req = self.authenticate(req);
141 if let Some(request_body) = request_body {
142 tracing::trace!("Request body:\n{:#?}", request_body);
143 req = req.json(&request_body);
144 }
145 let result = req.send();
146 if let Err(ref e) = result {
147 tracing::error!(%url, %method, "Icinga2 send error: {:?}", e);
148 }
149 let result = result?;
150 let status = result.status();
151 let response_body = result.bytes()?;
152 match from_utf8(&response_body) {
153 Ok(response_body) => {
154 tracing::trace!("Response body:\n{}", &response_body);
155 }
156 Err(e) => {
157 tracing::trace!(
158 "Response body that could not be parsed as utf8 because of {}:\n{:?}",
159 &e,
160 &response_body
161 );
162 }
163 }
164 if status.is_client_error() {
165 tracing::error!(%url, %method, "Icinga2 status error (client error): {:?}", status);
166 } else if status.is_server_error() {
167 tracing::error!(%url, %method, "Icinga2 status error (server error): {:?}", status);
168 }
169 if response_body.is_empty() {
170 Err(crate::error::Error::EmptyResponseBody(status))
171 } else {
172 let jd = &mut serde_json::Deserializer::from_slice(&response_body);
173 match serde_path_to_error::deserialize(jd) {
174 Ok(response_body) => {
175 tracing::trace!("Parsed response body:\n{:#?}", response_body);
176 Ok(response_body)
177 }
178 Err(e) => {
179 let path = e.path();
180 tracing::error!("Parsing failed at path {}: {}", path.to_string(), e.inner());
181 if let Ok(response_body) = serde_json::from_slice(&response_body) {
182 let mut response_body: serde_json::Value = response_body;
183 for segment in path {
184 let next = match (&response_body, segment) {
185 (
186 serde_json::Value::Array(vs),
187 serde_path_to_error::Segment::Seq { index },
188 ) => {
189 if let Some(v) = vs.get(*index) {
190 v.clone()
191 } else {
192 return Err(e.into());
194 }
195 }
196 (
197 serde_json::Value::Object(m),
198 serde_path_to_error::Segment::Map { key },
199 ) => {
200 if let Some(v) = m.get(key) {
201 v.clone()
202 } else {
203 return Err(e.into());
205 }
206 }
207 _ => {
208 return Err(e.into());
210 }
211 };
212 response_body = next;
213 }
214 tracing::error!("Value in location path references is: {}", response_body);
215 }
216 Err(e.into())
217 }
218 }
219 }
220 }
221}