opsview 0.1.12

A Rust Opsview API Client Library with batteries included
Documentation
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
use super::{Host, HostRef, ManagementURL, ServiceCheck, ServiceCheckHostRef};
use crate::{prelude::*, util::*};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Represents a [HostTemplate](https://docs.itrsgroup.com/docs/opsview/6.8.9/configuration/service-checks-and-host/host-templates/index.html#Heading-overview) in Opsview.
///
/// Host templates are used to define a set of shared [`ServiceCheck`]s and [`ManagementURL`]s that can be
/// applied to multiple [`Host`]s. This allows users to define a set of common checks and URLs that can
/// be applied to multiple hosts, rather than having to define them individually for each host.
///
/// This struct defines the structure for a host template entity as used in Opsview.
///
/// # Example
/// ```rust
/// use opsview::config::HostTemplate;
/// use opsview::prelude::*;
///
/// let host_template = HostTemplate::builder()
///    .name("My Host Template")
///    .build()
///    .unwrap();
///
/// assert_eq!(host_template.name, "My Host Template");
/// ```    
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct HostTemplate {
    // Required fields ---------------------------------------------------------------------------//
    /// The name of the `HostTemplate`.
    pub name: String,

    // Optional fields ---------------------------------------------------------------------------//
    /// Optional description of the `HostTemplate`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Unix Timestamp indicating when the icon was last updated, or 0 if there is no icon.
    #[serde(
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_string_or_number_to_u64",
        default
    )]
    pub has_icon: Option<u64>,

    /// [`ConfigRefMap`] of [`HostRef`] objects associated with this `HostTemplate`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hosts: Option<ConfigRefMap<HostRef>>,

    /// [`ConfigObjectMap`] of [`ManagementURL`]s associated with this `HostTemplate`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub managementurls: Option<ConfigObjectMap<ManagementURL>>,

    /// [`ConfigRefMap`] of [`ServiceCheckHostRef`] objects associated with this `HostTemplate`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub servicechecks: Option<ConfigRefMap<ServiceCheckHostRef>>,

    // Read-only fields --------------------------------------------------------------------------//
    /// The unique identifier of the `HostTemplate`.
    #[serde(
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_string_or_number_to_u64",
        default
    )]
    pub id: Option<u64>,

    /// A reference string unique to this template.
    #[serde(
        rename = "ref",
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_readonly",
        default
    )]
    pub ref_: Option<String>,

    /// A boolean indicating whether the `HostTemplate` is uncommitted.
    #[serde(
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_string_or_number_to_option_bool",
        serialize_with = "serialize_option_bool_as_string",
        default
    )]
    pub uncommitted: Option<bool>,
}

/// Enables the creation of a [`HostTemplate`] instance from a JSON representation.
/// Typically used when parsing JSON data from the Opsview API.
impl CreateFromJson for HostTemplate {}

impl ConfigObject for HostTemplate {
    type Builder = HostTemplateBuilder;

    /// Returns a builder for constructing a [`HostTemplate`] object.
    ///
    /// # Returns
    /// A [`HostTemplateBuilder`] object.
    fn builder() -> Self::Builder {
        HostTemplateBuilder::new()
    }

    /// Provides the configuration path for a [`HostTemplate`] object within the Opsview system.
    ///
    /// # Returns
    /// A string representing the API path where host templates are configured.
    fn config_path() -> Option<String> {
        Some("/config/hosttemplate".to_string())
    }

    /// Returns a minimal `HostTemplate` object with only the name set.
    ///
    /// # Arguments
    /// * `name` - Name of the [`HostTemplate`].
    ///
    /// # Returns
    /// A Result containing a minimal `HostTemplate` object with only the name set, and
    /// the rest of the fields in their default states.
    fn minimal(name: &str) -> Result<Self, OpsviewConfigError> {
        Ok(Self {
            name: validate_and_trim_hosttemplate_name(name)?,
            ..Default::default()
        })
    }

    /// Returns the unique name of the [`HostTemplate`] object.
    /// This name is used to identify the `HostTemplate` when building the `HashMap` for an
    /// [`ConfigObjectMap`].
    fn unique_name(&self) -> String {
        self.name.clone()
    }
}

impl Persistent for HostTemplate {
    /// Returns the unique identifier.
    fn id(&self) -> Option<u64> {
        self.id
    }

    /// Returns the reference string if it's not empty.
    fn ref_(&self) -> Option<String> {
        if self.ref_.as_ref().is_some_and(|x| !x.is_empty()) {
            self.ref_.clone()
        } else {
            None
        }
    }

    /// Returns the name if it's not empty.
    fn name(&self) -> Option<String> {
        if self.name.is_empty() {
            None
        } else {
            Some(self.name.clone())
        }
    }

    fn name_regex(&self) -> Option<String> {
        Some(HOSTTEMPLATE_NAME_REGEX_STR.to_string())
    }

    fn validated_name(&self, name: &str) -> Result<String, OpsviewConfigError> {
        validate_and_trim_hosttemplate_name(name)
    }

    fn set_name(&mut self, new_name: &str) -> Result<String, OpsviewConfigError> {
        self.name = self.validated_name(new_name)?;
        Ok(self.name.clone())
    }

    fn clear_readonly(&mut self) {
        self.id = None;
        self.ref_ = None;
        self.uncommitted = None;
    }
}

impl PersistentMap for ConfigObjectMap<HostTemplate> {
    fn config_path() -> Option<String> {
        Some("/config/hosttemplate".to_string())
    }
}

/// Builder for creating instances of [`HostTemplate`].
///
/// Provides a fluent interface for constructing a `HostTemplate` object with optional fields.
#[derive(Clone, Debug, Default)]
pub struct HostTemplateBuilder {
    name: Option<String>,
    description: Option<String>,
    has_icon: Option<u64>,
    hosts: Option<ConfigRefMap<HostRef>>,
    managementurls: Option<ConfigObjectMap<ManagementURL>>,
    servicechecks: Option<ConfigRefMap<ServiceCheckHostRef>>,
}

impl Builder for HostTemplateBuilder {
    type ConfigObject = HostTemplate;

    /// Creates a new instance of [`HostTemplateBuilder`] with default values. Initializes a new
    /// builder for creating a [`HostTemplate`] object with all fields in their default state.
    fn new() -> Self {
        HostTemplateBuilder::default()
    }

    /// Sets the name field.
    ///
    /// # Arguments
    /// * `name` - The name of the `HostTemplate`.
    fn name(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }

    /// Consumes the builder and returns a [`HostTemplate`] object.
    ///
    /// # Returns
    /// A `HostTemplate` object with the values specified by the builder.
    ///
    /// # Errors
    /// Returns an error if the name field is not set.
    fn build(self) -> Result<Self::ConfigObject, OpsviewConfigError> {
        let name = require_field(&self.name, "name")?;

        let validated_description =
            validate_opt_string(self.description, validate_and_trim_description)?;

        if self
            .has_icon
            .is_some_and(|ts| !is_valid_past_unix_timestamp(ts))
        {
            return Err(OpsviewConfigError::InvalidTimestamp(format!(
                "has_icon timestamp is in the future: {}",
                self.has_icon.unwrap()
            )));
        }

        Ok(HostTemplate {
            name: validate_and_trim_hosttemplate_name(&name)?,
            description: validated_description,
            has_icon: self.has_icon,
            hosts: self.hosts,
            managementurls: self.managementurls,
            servicechecks: self.servicechecks,
            id: None,
            ref_: None,
            uncommitted: None,
        })
    }
}

impl HostTemplateBuilder {
    /// Clears the description field.
    pub fn clear_description(mut self) -> Self {
        self.description = None;
        self
    }

    /// Clears the has_icon field.
    pub fn clear_has_icon(mut self) -> Self {
        self.has_icon = None;
        self
    }

    /// Clears the hosts field.
    pub fn clear_hosts(mut self) -> Self {
        self.hosts = None;
        self
    }

    /// Clears the managementurls field.
    pub fn clear_managementurls(mut self) -> Self {
        self.managementurls = None;
        self
    }

    /// Clears the name field.
    pub fn clear_name(mut self) -> Self {
        self.name = None;
        self
    }

    /// Clears the servicechecks field.
    pub fn clear_servicechecks(mut self) -> Self {
        self.servicechecks = None;
        self
    }

    /// Sets the description field.
    ///
    /// # Arguments
    /// * `description` - The description of the `HostTemplate`.
    pub fn description(mut self, description: &str) -> Self {
        self.description = Some(description.to_string());
        self
    }

    /// Sets the has_icon field.
    ///
    /// # Arguments
    /// * `has_icon` - A Unix timestamp `u64` indicating when the icon was set, or 0 for no icon.
    pub fn has_icon(mut self, has_icon: u64) -> Self {
        self.has_icon = Some(has_icon);
        self
    }

    /// Sets the hosts field.
    ///
    /// # Arguments
    /// * `hosts` - A reference to a [`ConfigObjectMap`] of [`Host`] objects associated with this `HostTemplate`.
    pub fn hosts(mut self, hosts: &ConfigObjectMap<Host>) -> Self {
        self.hosts = Some(hosts.into());
        self
    }

    /// Sets the managementurls field.
    ///
    /// # Arguments
    /// * `managementurls` - [`ConfigObjectMap`] of [`ManagementURL`]s associated with this `HostTemplate`.
    pub fn managementurls(mut self, managementurls: ConfigObjectMap<ManagementURL>) -> Self {
        self.managementurls = Some(managementurls);
        self
    }

    /// Sets the servicechecks field.
    ///
    /// # Arguments
    /// * `servicechecks` - A reference to a [`ConfigObjectMap`] of [`ServiceCheck`] objects associated with this `HostTemplate`.
    pub fn servicechecks(mut self, servicechecks: &ConfigObjectMap<ServiceCheck>) -> Self {
        self.servicechecks = Some(servicechecks.into());
        self
    }
}

/// A reference version of [`HostTemplate`] that is used when passing or retrieving a
/// [`HostTemplate`] object as part of another object.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
pub struct HostTemplateRef {
    name: String,
    #[serde(
        rename = "ref",
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_readonly",
        default
    )]
    ref_: Option<String>,
}

/// Enables the creation of a [`HostTemplateRef`] instance from a JSON representation.
/// Typically used when parsing JSON data from the Opsview API.
impl CreateFromJson for HostTemplateRef {}

impl ConfigRef for HostTemplateRef {
    type FullObject = HostTemplate;

    /// Returns the reference string of the [`HostTemplateRef`] object.
    fn ref_(&self) -> Option<String> {
        self.ref_.clone()
    }

    /// Returns the name of the [`HostTemplateRef`] object.
    fn name(&self) -> String {
        self.name.clone()
    }

    /// Returns the unique name of the [`HostTemplateRef`] object.
    /// This name is used to identify the `HostTemplateRef` when building the `HashMap` for a
    /// [`ConfigRefMap`].
    fn unique_name(&self) -> String {
        self.name.clone()
    }
}

impl From<HostTemplate> for HostTemplateRef {
    /// Creates a [`HostTemplateRef`] object from a full [`HostTemplate`] object.
    ///
    /// # Arguments
    /// * `host_template` - A full [`HostTemplate`] object.
    ///
    /// # Returns
    /// A [`HostTemplateRef`] object with the same name and reference string as the full
    /// [`HostTemplate`] object.
    fn from(host_template: HostTemplate) -> Self {
        Self {
            name: host_template.name.clone(),
            ref_: host_template.ref_.clone(),
        }
    }
}

impl From<Arc<HostTemplate>> for HostTemplateRef {
    fn from(item: Arc<HostTemplate>) -> Self {
        let cmd: HostTemplate = Arc::try_unwrap(item).unwrap_or_else(|arc| (*arc).clone());
        HostTemplateRef::from(cmd)
    }
}

impl From<&ConfigObjectMap<HostTemplate>> for ConfigRefMap<HostTemplateRef> {
    fn from(host_templates: &ConfigObjectMap<HostTemplate>) -> Self {
        ref_map_from(host_templates)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default() {
        let template = HostTemplate::default();

        assert!(template.name.is_empty());
    }

    #[test]
    fn test_minimal() {
        let template = HostTemplate::minimal("My Host Template");

        assert_eq!(template.unwrap().name, "My Host Template".to_string());
    }

    #[test]
    fn test_thin_from_full_host_template() {
        let obj = HostTemplate {
            name: "My Host Template".to_string(),
            description: Some("My Host Template Description".to_string()),
            has_icon: Some(0),
            hosts: None,
            managementurls: None,
            servicechecks: None,
            id: Some(1),
            ref_: Some("my-host-template-ref".to_string()),
            uncommitted: Some(false),
        };

        let obj_ref = HostTemplateRef::from(obj.clone());

        assert_eq!(obj_ref.name, obj.name);
        assert_eq!(obj_ref.ref_, obj.ref_);
    }
}