Skip to main content

icinga2_api/api/action/
schedule_downtime.rs

1//! API Action schedule-downtime
2//!
3//! [Official Documentation](https://icinga.com/docs/icinga-2/latest/doc/12-icinga2-api/#schedule-downtime)
4
5use serde::{Deserialize, Serialize};
6
7use crate::serde::{
8    deserialize_icinga_timestamp, deserialize_optional_seconds_as_duration,
9    serialize_icinga_timestamp, serialize_optional_duration_as_seconds,
10};
11use crate::types::action::StatusResponse;
12use crate::types::enums::downtime_child_options::IcingaDowntimeChildOptions;
13use crate::types::enums::object_type::IcingaObjectType;
14use crate::types::filter::IcingaFilter;
15use crate::types::names::IcingaDowntimeName;
16use crate::types::query::ResultsWrapper;
17use crate::types::rest::{RestApiEndpoint, RestApiResponse};
18
19/// REST API Endpoint for the schedule-downtime call
20#[derive(Debug, Clone, derive_builder::Builder, Serialize, Deserialize)]
21#[builder(
22    build_fn(error = "crate::error::Error", validate = "Self::validate"),
23    derive(Debug)
24)]
25pub struct ScheduleDowntime {
26    /// the author of the downtime
27    author: String,
28    /// the body of the downtime comment
29    comment: String,
30    /// beginning of the downtime
31    #[serde(
32        serialize_with = "serialize_icinga_timestamp",
33        deserialize_with = "deserialize_icinga_timestamp"
34    )]
35    start_time: time::OffsetDateTime,
36    /// end of the downtime
37    #[serde(
38        serialize_with = "serialize_icinga_timestamp",
39        deserialize_with = "deserialize_icinga_timestamp"
40    )]
41    end_time: time::OffsetDateTime,
42    /// Defaults to true. If true, the downtime is fixed otherwise flexible.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    fixed: Option<bool>,
45    /// the duration of the downtime
46    #[serde(
47        serialize_with = "serialize_optional_duration_as_seconds",
48        deserialize_with = "deserialize_optional_seconds_as_duration"
49    )]
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    duration: Option<time::Duration>,
52    /// Sets downtime for all services for the matched host objects. If child_options are set, all child hosts and their services will schedule a downtime too. Defaults to false.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    all_services: Option<bool>,
55    /// Sets the trigger for a triggered downtime.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    trigger_name: Option<IcingaDowntimeName>,
58    /// Schedule child downtimes.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    child_options: Option<IcingaDowntimeChildOptions>,
61    /// filter to target which host and/or service to schedule a downtime for
62    #[builder(default, setter(strip_option, into))]
63    #[serde(flatten)]
64    filter: Option<IcingaFilter>,
65}
66
67impl ScheduleDowntime {
68    /// create a new builder for this endpoint
69    ///
70    /// this is usually the first step to calling this REST API endpoint
71    #[must_use]
72    pub fn builder() -> ScheduleDowntimeBuilder {
73        ScheduleDowntimeBuilder::default()
74    }
75}
76
77impl ScheduleDowntimeBuilder {
78    /// makes sure the filter object type is valid for this call (either Host or Service)
79    ///
80    /// validates all_services is only used on host downtimes
81    ///
82    /// validates duration is specified if fixed is set to false
83    ///
84    /// # Errors
85    ///
86    /// this returns an error if the filter field object type is not Host or Service
87    pub fn validate(&self) -> Result<(), crate::error::Error> {
88        if matches!(&self.fixed, Some(Some(false))) && matches!(&self.duration, None | Some(None)) {
89            return Err(crate::error::Error::DurationRequiredOnFlexibleDowntime);
90        }
91        if let Some(Some(filter)) = &self.filter {
92            if filter.object_type != IcingaObjectType::Host
93                && filter.object_type != IcingaObjectType::Service
94            {
95                return Err(crate::error::Error::FilterObjectTypeMismatch(
96                    vec![IcingaObjectType::Host, IcingaObjectType::Service],
97                    filter.object_type.to_owned(),
98                ));
99            }
100            if filter.object_type == IcingaObjectType::Service
101                && matches!(&self.all_services, Some(Some(true)))
102            {
103                return Err(crate::error::Error::AllServicesInvalidOnServiceDowntime);
104            }
105        }
106        Ok(())
107    }
108}
109
110impl RestApiEndpoint for ScheduleDowntime {
111    type RequestBody = Self;
112
113    fn method(&self) -> Result<reqwest::Method, crate::error::Error> {
114        Ok(reqwest::Method::POST)
115    }
116
117    fn url(&self, base_url: &url::Url) -> Result<url::Url, crate::error::Error> {
118        base_url
119            .join("v1/actions/schedule-downtime")
120            .map_err(crate::error::Error::CouldNotParseUrlFragment)
121    }
122
123    fn request_body(
124        &self,
125    ) -> Result<Option<std::borrow::Cow<'_, Self::RequestBody>>, crate::error::Error>
126    where
127        Self::RequestBody: Clone + serde::Serialize + std::fmt::Debug,
128    {
129        Ok(Some(std::borrow::Cow::Borrowed(self)))
130    }
131}
132
133impl RestApiResponse<ScheduleDowntime> for ResultsWrapper<StatusResponse> {}
134
135#[cfg(test)]
136mod test {
137    use super::ScheduleDowntime;
138    use crate::types::enums::object_type::IcingaObjectType;
139    use crate::types::filter::IcingaFilter;
140    use pretty_assertions::assert_eq;
141
142    /// a filter for one object of `object_type`
143    fn filter(object_type: IcingaObjectType) -> IcingaFilter {
144        IcingaFilter {
145            object_type,
146            filter: "match(\"example\", host.name)".to_owned(),
147            filter_vars: std::collections::BTreeMap::new(),
148        }
149    }
150
151    /// a builder with every required field set
152    fn builder(object_type: IcingaObjectType) -> super::ScheduleDowntimeBuilder {
153        let start = time::OffsetDateTime::UNIX_EPOCH;
154        let mut builder = ScheduleDowntime::builder();
155        builder
156            .author("test".to_owned())
157            .comment("test".to_owned())
158            .start_time(start)
159            .end_time(start.saturating_add(time::Duration::hours(1)))
160            .fixed(Some(true))
161            .duration(None)
162            .all_services(None)
163            .trigger_name(None)
164            .child_options(None)
165            .filter(filter(object_type));
166        builder
167    }
168
169    #[test]
170    fn service_downtimes_are_valid() -> Result<(), crate::error::Error> {
171        builder(IcingaObjectType::Service).build()?;
172        Ok(())
173    }
174
175    #[test]
176    fn all_services_is_invalid_on_service_downtimes() -> Result<(), crate::error::Error> {
177        assert!(matches!(
178            builder(IcingaObjectType::Service)
179                .all_services(Some(true))
180                .build(),
181            Err(crate::error::Error::AllServicesInvalidOnServiceDowntime)
182        ));
183        builder(IcingaObjectType::Host)
184            .all_services(Some(true))
185            .build()?;
186        Ok(())
187    }
188
189    #[test]
190    fn flexible_downtimes_need_a_duration() -> Result<(), crate::error::Error> {
191        assert!(matches!(
192            builder(IcingaObjectType::Host).fixed(Some(false)).build(),
193            Err(crate::error::Error::DurationRequiredOnFlexibleDowntime)
194        ));
195        builder(IcingaObjectType::Host)
196            .fixed(Some(false))
197            .duration(Some(time::Duration::minutes(30)))
198            .build()?;
199        Ok(())
200    }
201
202    #[test]
203    fn unset_options_are_not_sent() -> Result<(), Box<dyn std::error::Error>> {
204        // Icinga rejects e.g. `"child_options": null` with a 400
205        let body = serde_json::to_value(builder(IcingaObjectType::Host).build()?)?;
206        for key in ["duration", "all_services", "trigger_name", "child_options"] {
207            assert!(body.get(key).is_none(), "{key} must not be sent when unset");
208        }
209        assert_eq!(body.get("fixed"), Some(&serde_json::Value::Bool(true)));
210        Ok(())
211    }
212}