regent-sdk 0.16.0

Multi-paradigm configuration management system as a library
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Storage monitoring attribute
//!
//! This module provides the `StorageExpectedState` type for monitoring filesystem
//! or mount point storage capacity against configurable thresholds. When the
//! threshold is breached (e.g. disk usage exceeds a percentage), optional cleanup
//! commands are triggered to free up space.
//!
//! **Compatible OS:** Linux (uses `df`)
//!
//! # Examples
//!
//! ## Rust API
//!
//! ```no_run
//! use regent_sdk::state::attribute::utilities::storage::{
//!     StorageExpectedState, Threshold,
//! };
//! use regent_sdk::{Attribute, ExpectedState, Privilege};
//!
//! // Watch root filesystem: trigger cleanup when usage exceeds 95%
//! let mut storage = StorageExpectedState::watch_filesystem("/", Threshold::Percent(95));
//! storage.with_cleanup(vec![
//!     "docker system prune -af".to_string(),
//!     "journalctl --vacuum-time=3d".to_string(),
//! ]);
//!
//! // Watch a mount point: trigger cleanup when less than 10GB remain
//! let mut storage_mnt = StorageExpectedState::watch_mountpoint(
//!     "/var/lib/docker",
//!     Threshold::AbsoluteRemaining(10_485_760), // 10 GB in 1K blocks
//! );
//! storage_mnt.with_cleanup(vec!["docker system prune -af".to_string()]);
//!
//! let expected_state = ExpectedState::new()
//!     .with_attribute(Attribute::storage(storage, Privilege::WithSudo, None))
//!     .build();
//! ```
//!
//! ## YAML API
//!
//! ```yaml
//! Attributes:
//!   - Name: Root filesystem has at least 5% free
//!     Privilege: !WithSudo
//!     Detail: !Storage
//!       Target: !FileSystem /
//!       Threshold: !Percent 95
//!       Cleanup:
//!         - docker system prune -af
//!         - journalctl --vacuum-time=3d
//! ```

use crate::error::RegentError;
use crate::hosts::managed_host::InternalApiCallOutcome;
use crate::hosts::managed_host::{AssessCompliance, ReachCompliance, Timeout};
use crate::hosts::properties::{HostProperties, OsKind};
use crate::secrets::SecretProvidersPool;
use crate::state::Check;
use crate::state::attribute::HostHandler;
use crate::state::attribute::Privilege;
use crate::state::attribute::Remediation;
use crate::state::attribute::RemediationsList;
use crate::state::compliance::AttributeComplianceAssessment;
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Threshold that triggers the storage watch when breached.
///
/// Values are compared against `df --output=pcent,used,avail` results.
/// `used` and `avail` are expressed in 1K blocks.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Threshold {
    /// Trigger when the used percentage (from `df --output=pcent`) is greater than or equal to this value.
    /// For example, `Percent(95)` triggers when 95% or more of the storage is used
    /// (i.e. less than 5% available).
    Percent(u8),
    /// Trigger when the used space (in 1K blocks, from `df --output=used`) is greater than or equal to this value.
    AbsoluteUsed(u64),
    /// Trigger when the remaining available space (in 1K blocks, from `df --output=avail`) is less than or equal to this value.
    AbsoluteRemaining(u64),
}

/// Target of the storage watch: either a filesystem path or a mount point.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum StorageTarget {
    /// A filesystem path (e.g. `/`, `/var`).
    FileSystem(String),
    /// A mount point path (e.g. `/mnt/data`).
    MountPoint(String),
}

impl StorageTarget {
    fn path(&self) -> &str {
        match self {
            StorageTarget::FileSystem(p) => p,
            StorageTarget::MountPoint(p) => p,
        }
    }
}

/// Expected state for storage monitoring on a filesystem or mount point.
///
/// When the storage usage breaches the configured [`Threshold`], the optional
/// cleanup commands are executed one by one to free up space.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct StorageExpectedState {
    target: StorageTarget,
    threshold: Threshold,
    cleanup: Option<Vec<String>>,
}

impl Timeout for StorageExpectedState {
    fn default_timeout(&self) -> Duration {
        Duration::from_secs(10)
    }
}

impl StorageExpectedState {
    /// Watch a filesystem path (e.g. `/`, `/var`) against a threshold.
    pub fn watch_filesystem(fs: &str, threshold: Threshold) -> StorageExpectedState {
        StorageExpectedState {
            target: StorageTarget::FileSystem(fs.to_string()),
            threshold,
            cleanup: None,
        }
    }

    /// Watch a mount point path (e.g. `/mnt/data`) against a threshold.
    pub fn watch_mountpoint(mountpoint: &str, threshold: Threshold) -> StorageExpectedState {
        StorageExpectedState {
            target: StorageTarget::MountPoint(mountpoint.to_string()),
            threshold,
            cleanup: None,
        }
    }

    /// Attach cleanup commands to run when the threshold is breached.
    pub fn with_cleanup(&mut self, cleanup: Vec<String>) {
        self.cleanup = Some(cleanup);
    }
}

impl Check for StorageExpectedState {
    fn check(&self) -> Result<(), RegentError> {
        Ok(())
    }

    fn check_host_compatibility(
        &self,
        host_properties: &HostProperties,
    ) -> Result<(), RegentError> {
        match host_properties.os_kind() {
            OsKind::Linux(_) => Ok(()),
            _ => Err(RegentError::IncompatibleHost(format!(
                "Storage management is only supported on Linux (df)",
            ))),
        }
    }
}

impl<Handler: HostHandler> AssessCompliance<Handler> for StorageExpectedState {
    async fn assess_compliance(
        &self,
        host_handler: &mut Handler,
        host_properties: &Option<HostProperties>,
        privilege: &Privilege,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<AttributeComplianceAssessment, RegentError> {
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }

        // Verify that `df` is available on the host
        let df_available = host_handler
            .is_this_command_available("df", privilege)
            .await
            .unwrap_or(false);

        if !df_available {
            return Err(RegentError::FailedDryRunEvaluation(
                "Storage management command (df) is not available on this host".to_string(),
            ));
        }

        let path = self.target.path();

        // Run df to get usage percentage, used (1K blocks), and available (1K blocks)
        let cmd = format!("df -P --output=pcent,used,avail {}", path);
        let result = host_handler.run_command(&cmd, privilege).await?;

        if result.return_code != 0 {
            return Err(RegentError::FailedTaskDryRun(format!(
                "Unable to check storage usage for {}: RC: {}, STDERR: {}",
                path, result.return_code, result.stderr
            )));
        }

        // Parse df output: header line then data line
        // Example:
        //   Use%  Used  Avail
        //    45% 12345 67890
        let lines: Vec<&str> = result.stdout.lines().collect();
        if lines.len() < 2 {
            return Err(RegentError::FailedTaskDryRun(format!(
                "Unexpected df output for {}: {}",
                path, result.stdout
            )));
        }

        let data_line = lines[1].trim();
        let fields: Vec<&str> = data_line.split_whitespace().collect();
        if fields.len() < 3 {
            return Err(RegentError::FailedTaskDryRun(format!(
                "Unable to parse df output for {}: {}",
                path, result.stdout
            )));
        }

        // Parse percentage (strip trailing '%')
        let pcent_str = fields[0].trim_end_matches('%');
        let pcent: u8 = pcent_str.parse().map_err(|_| {
            RegentError::FailedTaskDryRun(format!(
                "Unable to parse usage percentage from df output: {}",
                fields[0]
            ))
        })?;

        // Parse used and available (in 1K blocks)
        let used: u64 = fields[1].parse().map_err(|_| {
            RegentError::FailedTaskDryRun(format!(
                "Unable to parse used blocks from df output: {}",
                fields[1]
            ))
        })?;

        let avail: u64 = fields[2].parse().map_err(|_| {
            RegentError::FailedTaskDryRun(format!(
                "Unable to parse available blocks from df output: {}",
                fields[2]
            ))
        })?;

        // Check if the threshold is breached
        let breached = match &self.threshold {
            Threshold::Percent(limit) => pcent >= *limit,
            Threshold::AbsoluteUsed(limit) => used >= *limit,
            Threshold::AbsoluteRemaining(limit) => avail <= *limit,
        };

        if breached {
            if let Some(cleanup_cmds) = &self.cleanup {
                if !cleanup_cmds.is_empty() {
                    let remediation = Remediation::Storage(StorageApiCall::from(
                        StorageModuleInternalApiCall::from(cleanup_cmds.clone()),
                        privilege.clone(),
                    ));
                    return Ok(AttributeComplianceAssessment::NonCompliant(
                        RemediationsList::from(vec![remediation])?,
                    ));
                }
            }
            // Threshold breached but no cleanup commands: report as non-compliant fatal
            // since there is nothing actionable to remediate
            return Ok(AttributeComplianceAssessment::NonCompliantFatal(format!(
                "Storage threshold breached for {} (use%: {}%, used: {}K, avail: {}K) but no cleanup commands configured",
                path, pcent, used, avail
            )));
        }

        Ok(AttributeComplianceAssessment::Compliant)
    }
}

/// Internal API call representation for the storage module.
///
/// Holds the list of cleanup commands to execute when the storage threshold is breached.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct StorageModuleInternalApiCall {
    cleanup: Vec<String>,
}

impl std::fmt::Display for StorageModuleInternalApiCall {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Clean up with {:?}", self.cleanup)
    }
}

impl StorageModuleInternalApiCall {
    fn from(cleanup: Vec<String>) -> StorageModuleInternalApiCall {
        StorageModuleInternalApiCall { cleanup }
    }
}

impl Check for StorageModuleInternalApiCall {
    fn check(&self) -> Result<(), RegentError> {
        Ok(())
    }

    fn check_host_compatibility(
        &self,
        host_properties: &HostProperties,
    ) -> Result<(), RegentError> {
        match host_properties.os_kind() {
            OsKind::Linux(_) => Ok(()),
            _ => Err(RegentError::IncompatibleHost(format!(
                "Storage management is only supported on Linux (df)",
            ))),
        }
    }
}

/// API call for the storage module: executes cleanup commands one by one.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StorageApiCall {
    pub api_call: StorageModuleInternalApiCall,
    privilege: Privilege,
}

impl StorageApiCall {
    pub fn display(&self) -> String {
        format!("Run storage cleanup commands: {:?}", self.api_call.cleanup)
    }

    fn from(api_call: StorageModuleInternalApiCall, privilege: Privilege) -> StorageApiCall {
        StorageApiCall {
            api_call,
            privilege,
        }
    }
}

impl Check for StorageApiCall {
    fn check(&self) -> Result<(), RegentError> {
        Ok(())
    }

    fn check_host_compatibility(
        &self,
        host_properties: &HostProperties,
    ) -> Result<(), RegentError> {
        match host_properties.os_kind() {
            OsKind::Linux(_) => Ok(()),
            _ => Err(RegentError::IncompatibleHost(format!(
                "Storage management is only supported on Linux (df)",
            ))),
        }
    }
}

impl<Handler: HostHandler> ReachCompliance<Handler> for StorageApiCall {
    async fn call(
        &self,
        host_handler: &mut Handler,
        host_properties: &Option<HostProperties>,
        _optional_secret_provider: &Option<SecretProvidersPool>,
    ) -> Result<InternalApiCallOutcome, RegentError> {
        if let Some(props) = host_properties {
            self.check_host_compatibility(props)?;
        }

        // Run each cleanup command one by one
        for cmd in &self.api_call.cleanup {
            let result = host_handler.run_command(cmd, &self.privilege).await;

            match result {
                Ok(r) => {
                    if r.return_code != 0 {
                        return Ok(InternalApiCallOutcome::Failure(format!(
                            "Cleanup command '{}' failed - RC: {}, STDOUT: {}, STDERR: {}",
                            cmd, r.return_code, r.stdout, r.stderr
                        )));
                    }
                }
                Err(e) => {
                    return Ok(InternalApiCallOutcome::Failure(format!(
                        "Cleanup command '{}' execution failed: {:?}",
                        cmd, e
                    )));
                }
            }
        }

        Ok(InternalApiCallOutcome::Success(None))
    }
}

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

    #[test]
    fn parsing_storage_module_block_from_yaml_str() {
        let raw = "---
Target: !FileSystem /
Threshold: !Percent 95
Cleanup:
  - docker system prune -af
  - journalctl --vacuum-time=3d
";
        let storage: StorageExpectedState = yaml_serde::from_str(raw).unwrap();
        assert_eq!(storage.target, StorageTarget::FileSystem("/".to_string()));
        assert_eq!(storage.threshold, Threshold::Percent(95));
        assert_eq!(
            storage.cleanup,
            Some(vec![
                "docker system prune -af".to_string(),
                "journalctl --vacuum-time=3d".to_string(),
            ])
        );
    }

    #[test]
    fn parsing_storage_mountpoint_with_absolute_remaining() {
        let raw = "---
Target: !MountPoint /var/lib/docker
Threshold: !AbsoluteRemaining 10485760
";
        let storage: StorageExpectedState = yaml_serde::from_str(raw).unwrap();
        assert_eq!(
            storage.target,
            StorageTarget::MountPoint("/var/lib/docker".to_string())
        );
        assert_eq!(storage.threshold, Threshold::AbsoluteRemaining(10485760));
        assert_eq!(storage.cleanup, None);
    }

    #[test]
    fn parsing_storage_with_absolute_used() {
        let raw = "---
Target: !FileSystem /data
Threshold: !AbsoluteUsed 51200000
";
        let storage: StorageExpectedState = yaml_serde::from_str(raw).unwrap();
        assert_eq!(
            storage.target,
            StorageTarget::FileSystem("/data".to_string())
        );
        assert_eq!(storage.threshold, Threshold::AbsoluteUsed(51200000));
    }

    #[test]
    fn builder_watch_filesystem() {
        let storage = StorageExpectedState::watch_filesystem("/", Threshold::Percent(90));
        assert_eq!(storage.target, StorageTarget::FileSystem("/".to_string()));
        assert_eq!(storage.threshold, Threshold::Percent(90));
        assert!(storage.cleanup.is_none());
    }

    #[test]
    fn builder_watch_mountpoint_with_cleanup() {
        let mut storage =
            StorageExpectedState::watch_mountpoint("/mnt/data", Threshold::AbsoluteRemaining(1024));
        storage.with_cleanup(vec!["rm -rf /mnt/data/tmp/*".to_string()]);
        assert_eq!(
            storage.target,
            StorageTarget::MountPoint("/mnt/data".to_string())
        );
        assert_eq!(
            storage.cleanup,
            Some(vec!["rm -rf /mnt/data/tmp/*".to_string()])
        );
    }
}