Skip to main content

icinga2_api/api/
blocking.rs

1//! Main API object (blocking version)
2
3use 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/// the runtime object for an Icinga2 instance (blocking variant)
13#[derive(Debug, Clone)]
14pub struct Icinga2 {
15    /// the HTTP client to use
16    client: reqwest::blocking::Client,
17    /// the base URL for the Icinga API
18    pub url: url::Url,
19    /// username, empty when authenticating with a client certificate
20    pub username: String,
21    /// how to authenticate
22    auth: Icinga2Auth,
23}
24
25impl Icinga2 {
26    /// create a new Icinga2 instance from a config that was
27    /// either manually created or previously loaded via [Icinga2Instance::from_config_file]
28    ///
29    /// # Errors
30    /// this fails if the CA certificate file mentioned in the configuration
31    /// can not be found or parsed
32    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    /// create a new Icinga2 instance from its URL (without the v1 component),
44    /// an optional CA certificate to validate the server certificate with
45    /// and the authentication to use
46    ///
47    /// see also [crate::config::instance_file::Icinga2InstanceFile] which
48    /// resolves these parts from an instance config file
49    ///
50    /// # Errors
51    /// this fails if the CA certificate file can not be found or parsed,
52    /// the client certificate can not be parsed or the URL can not be parsed
53    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    /// adds the basic auth header to a request if we use basic auth
88    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    /// create a new Icinga2 instance from a TOML config file
99    ///
100    /// # Errors
101    /// this fails if the configuration file can not be found or parsed
102    /// or the CA certificate file mentioned in the configuration file
103    /// can not be found or parsed
104    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    /// common code for the REST API calls
110    ///
111    /// # Errors
112    ///
113    /// this returns an error if encoding, the actual request, or decoding of the response fail
114    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                                        // if we can not find the element serde_path_to_error references fall back to just returning the error
193                                        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                                        // if we can not find the element serde_path_to_error references fall back to just returning the error
204                                        return Err(e.into());
205                                    }
206                                }
207                                _ => {
208                                    // if we can not find the element serde_path_to_error references fall back to just returning the error
209                                    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}