1use std::{path::Path, str::from_utf8};
4
5use futures::Stream;
6use futures::StreamExt as _;
7use futures::stream::TryStreamExt as _;
8use serde::{Serialize, de::DeserializeOwned};
9use tokio::io::AsyncBufReadExt as _;
10use tokio_stream::wrappers::LinesStream;
11use tokio_util::io::StreamReader;
12
13use crate::config::{Icinga2Auth, Icinga2Instance};
14use crate::types::{
15 enums::event_stream_type::IcingaEventStreamType,
16 event_stream::IcingaEvent,
17 filter::IcingaFilter,
18 rest::{RestApiEndpoint, RestApiResponse},
19};
20
21#[derive(Debug, Clone)]
23pub struct Icinga2Async {
24 client: reqwest::Client,
26 pub url: url::Url,
28 pub username: String,
30 auth: Icinga2Auth,
32}
33
34impl Icinga2Async {
35 pub fn from_instance_config(config: &Icinga2Instance) -> Result<Self, crate::error::Error> {
42 Self::from_parts(
43 &config.url,
44 config.ca_certificate.as_deref(),
45 Icinga2Auth::Basic {
46 username: config.username.clone(),
47 password: config.password.clone(),
48 },
49 )
50 }
51
52 pub fn from_parts(
63 url: &str,
64 ca_certificate: Option<&Path>,
65 auth: Icinga2Auth,
66 ) -> Result<Self, crate::error::Error> {
67 let parts = crate::config::client_parts(url, ca_certificate, &auth)?;
68 let client_builder = reqwest::ClientBuilder::new()
69 .user_agent(concat!(
70 env!("CARGO_PKG_NAME"),
71 "/",
72 env!("CARGO_PKG_VERSION")
73 ))
74 .default_headers(parts.headers);
75 let client_builder = if let Some(ca_cert) = parts.ca_certificate {
76 client_builder.tls_certs_only([ca_cert])
77 } else {
78 client_builder
79 };
80 let client_builder = if let Some(identity) = parts.identity {
81 client_builder.identity(identity)
82 } else {
83 client_builder
84 };
85 let client = client_builder
86 .build()
87 .map_err(crate::error::Error::CouldNotBuildReqwestClientFromSuppliedInformation)?;
88 Ok(Self {
89 client,
90 url: parts.url,
91 username: auth.username().to_owned(),
92 auth,
93 })
94 }
95
96 fn authenticate(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
98 match &self.auth {
99 Icinga2Auth::Basic { username, password } => req.basic_auth(username, Some(password)),
100 Icinga2Auth::ClientCertificate { .. } => req,
101 }
102 }
103
104 pub fn from_config_file(path: &Path) -> Result<Self, crate::error::Error> {
111 let icinga_instance = Icinga2Instance::from_config_file(path)?;
112 Self::from_instance_config(&icinga_instance)
113 }
114
115 #[expect(
121 clippy::future_not_send,
122 reason = "neither ApiEndpoint nor its RequestBody is required to be Send; callers that need a Send future can wrap with their own bounds"
123 )]
124 pub async fn rest<ApiEndpoint, Res>(
125 &self,
126 api_endpoint: ApiEndpoint,
127 ) -> Result<Res, crate::error::Error>
128 where
129 ApiEndpoint: RestApiEndpoint,
130 <ApiEndpoint as RestApiEndpoint>::RequestBody: Clone + Serialize + std::fmt::Debug,
131 Res: DeserializeOwned + std::fmt::Debug + RestApiResponse<ApiEndpoint>,
132 {
133 let method = api_endpoint.method()?;
134 let url = api_endpoint.url(&self.url)?;
135 let request_body: Option<std::borrow::Cow<<ApiEndpoint as RestApiEndpoint>::RequestBody>> =
136 api_endpoint.request_body()?;
137 let actual_method = if method == reqwest::Method::GET && request_body.is_some() {
138 reqwest::Method::POST
139 } else {
140 method.to_owned()
141 };
142 let mut req = self.client.request(actual_method, url.to_owned());
143 if method == reqwest::Method::GET && request_body.is_some() {
144 tracing::trace!("Sending GET request with body as POST via X-HTTP-Method-Override");
145 req = req.header(
146 "X-HTTP-Method-Override",
147 reqwest::header::HeaderValue::from_static("GET"),
148 );
149 }
150 req = self.authenticate(req);
151 if let Some(request_body) = request_body {
152 tracing::trace!("Request body:\n{:#?}", request_body);
153 req = req.json(&request_body);
154 }
155 let result = req.send().await;
156 if let Err(ref e) = result {
157 tracing::error!(%url, %method, "Icinga2 send error: {:?}", e);
158 }
159 let result = result?;
160 let status = result.status();
161 let response_body = result.bytes().await?;
162 match from_utf8(&response_body) {
163 Ok(response_body) => {
164 tracing::trace!("Response body:\n{}", &response_body);
165 }
166 Err(e) => {
167 tracing::trace!(
168 "Response body that could not be parsed as utf8 because of {}:\n{:?}",
169 &e,
170 &response_body
171 );
172 }
173 }
174 if status.is_client_error() {
175 tracing::error!(%url, %method, "Icinga2 status error (client error): {:?}", status);
176 } else if status.is_server_error() {
177 tracing::error!(%url, %method, "Icinga2 status error (server error): {:?}", status);
178 }
179 if response_body.is_empty() {
180 Err(crate::error::Error::EmptyResponseBody(status))
181 } else {
182 let jd = &mut serde_json::Deserializer::from_slice(&response_body);
183 match serde_path_to_error::deserialize(jd) {
184 Ok(response_body) => {
185 tracing::trace!("Parsed response body:\n{:#?}", response_body);
186 Ok(response_body)
187 }
188 Err(e) => {
189 let path = e.path();
190 tracing::error!("Parsing failed at path {}: {}", path.to_string(), e.inner());
191 if let Ok(response_body) = serde_json::from_slice(&response_body) {
192 let mut response_body: serde_json::Value = response_body;
193 for segment in path {
194 let next = match (&response_body, segment) {
195 (
196 serde_json::Value::Array(vs),
197 serde_path_to_error::Segment::Seq { index },
198 ) => {
199 if let Some(v) = vs.get(*index) {
200 v.clone()
201 } else {
202 return Err(e.into());
204 }
205 }
206 (
207 serde_json::Value::Object(m),
208 serde_path_to_error::Segment::Map { key },
209 ) => {
210 if let Some(v) = m.get(key) {
211 v.clone()
212 } else {
213 return Err(e.into());
215 }
216 }
217 _ => {
218 return Err(e.into());
220 }
221 };
222 response_body = next;
223 }
224 tracing::error!("Value in location path references is: {}", response_body);
225 }
226 Err(e.into())
227 }
228 }
229 }
230 }
231
232 pub async fn event_stream(
238 &self,
239 types: &[IcingaEventStreamType],
240 queue: &str,
241 filter: Option<IcingaFilter>,
242 ) -> Result<impl Stream<Item = Result<IcingaEvent, std::io::Error>>, crate::error::Error> {
243 let method = reqwest::Method::POST;
244 let mut url = self
245 .url
246 .join("v1/events")
247 .map_err(crate::error::Error::CouldNotParseUrlFragment)?;
248 for t in types {
249 url.query_pairs_mut().append_pair("types", &t.to_string());
250 }
251 url.query_pairs_mut().append_pair("queue", queue);
252 let request_body = filter;
253 let mut req = self.client.request(method.to_owned(), url.to_owned());
254 req = self.authenticate(req);
255 if let Some(request_body) = request_body {
256 tracing::trace!("Request body:\n{:#?}", request_body);
257 req = req.json(&request_body);
258 }
259 let result = req.send().await;
260 if let Err(ref e) = result {
261 tracing::error!(%url, %method, "Icinga2 send error: {:?}", e);
262 }
263 let result = result?;
264 let status = result.status();
265 if status.is_client_error() {
266 tracing::error!(%url, %method, "Icinga2 status error (client error): {:?}", status);
267 } else if status.is_server_error() {
268 tracing::error!(%url, %method, "Icinga2 status error (server error): {:?}", status);
269 }
270 let byte_chunk_stream = result.bytes_stream().map_err(std::io::Error::other);
271 let stream_reader = StreamReader::new(byte_chunk_stream);
272 let line_reader = LinesStream::new(stream_reader.lines());
273 let event_reader = line_reader.map(|l| match l {
274 Ok(l) => {
275 tracing::trace!("Icinga2 received raw event:\n{}", &l);
276 let jd = &mut serde_json::Deserializer::from_str(&l);
277 match serde_path_to_error::deserialize(jd) {
278 Ok(event) => {
279 tracing::trace!("Icinga2 received event:\n{:#?}", &event);
280 Ok(event)
281 }
282 Err(e) => Err(std::io::Error::other(e)),
283 }
284 }
285 Err(e) => Err(e),
286 });
287 Ok(event_reader)
288 }
289}
290
291#[cfg(test)]
292mod test {
293 use super::*;
294 use std::error::Error;
295 use tracing_test::traced_test;
296
297 #[traced_test]
298 #[tokio::test]
299 async fn test_event_stream_async() -> Result<(), Box<dyn Error>> {
300 dotenvy::dotenv()?;
301 let icinga2 = Icinga2Async::from_config_file(std::path::Path::new(&std::env::var(
302 "ICINGA_TEST_INSTANCE_CONFIG",
303 )?))?;
304 let mut stream = icinga2
305 .event_stream(
306 &[
307 IcingaEventStreamType::CheckResult,
308 IcingaEventStreamType::StateChange,
309 IcingaEventStreamType::Notification,
310 IcingaEventStreamType::AcknowledgementSet,
311 IcingaEventStreamType::AcknowledgementCleared,
312 IcingaEventStreamType::CommentAdded,
313 IcingaEventStreamType::CommentRemove,
314 IcingaEventStreamType::DowntimeAdded,
315 IcingaEventStreamType::DowntimeRemoved,
316 IcingaEventStreamType::DowntimeStarted,
317 IcingaEventStreamType::DowntimeTriggered,
318 IcingaEventStreamType::ObjectCreated,
319 IcingaEventStreamType::ObjectDeleted,
320 IcingaEventStreamType::ObjectModified,
321 IcingaEventStreamType::Flapping,
322 ],
323 "test",
324 None,
325 )
326 .await?;
327 for _ in 0..100 {
328 let event = stream.next().await;
329 tracing::trace!("Got event:\n{:#?}", event);
330 if let Some(event) = event {
331 event?;
332 }
333 }
334 Ok(())
335 }
336}