stackpatrol 0.2.5

Single-binary Rust CLI that monitors a server and reports to the StackPatrol control plane.
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
use std::collections::HashMap;

use stackpatrol_core::event::Event;
use sysinfo::{Disks, System};

use crate::config::ResourceProbeConfig;

/// Drop in % below the entered threshold required to clear the in-memory state.
/// Without it, a value bouncing across the threshold each tick would re-emit
/// the same alert repeatedly. We only emit on rising edge.
const HYSTERESIS_MARGIN: u8 = 5;
/// Same idea for load (a float): must drop to 90% of the entered threshold
/// before the resource is considered out of that zone.
const LOAD_CLEAR_RATIO: f32 = 0.9;

/// How far below `*_high` to default the warning threshold when the user hasn't
/// set one explicitly. 10pp gives a meaningful "heads up" without being noisy.
const DEFAULT_WARNING_OFFSET: u8 = 10;
/// Floor for the auto-derived warning threshold — never warn below this.
/// Below 50% utilisation is "your server is doing fine," not "heads up."
const MIN_WARNING_PERCENT: u8 = 50;
/// Auto-derived load warning is 75% of the critical threshold.
const LOAD_WARNING_RATIO: f32 = 0.75;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Zone {
    Ok,
    Warning,
    Critical,
}

pub struct ResourceProbe {
    disk_warning: u8,
    disk_critical: u8,
    memory_warning: u8,
    memory_critical: u8,
    load_warning: f32,
    load_critical: f32,
    sys: System,
    disks: Disks,
    /// mount → last observed zone
    last_disk_zone: HashMap<String, Zone>,
    last_memory_zone: Zone,
    last_load_zone: Zone,
}

impl ResourceProbe {
    pub fn new(cfg: &ResourceProbeConfig) -> Self {
        let disk_critical = cfg.disk_high_percent;
        let disk_warning = resolve_warning_u8(cfg.disk_warning_percent, disk_critical);

        let memory_critical = cfg.memory_high_percent;
        let memory_warning = resolve_warning_u8(cfg.memory_warning_percent, memory_critical);

        let load_critical = if cfg.load_1m_high > 0.0 {
            cfg.load_1m_high
        } else {
            // 2× logical CPU count — saturated but stable. Single-core Pi gets 2.0,
            // an 8-core box gets 16.0. Conservative default: false-positives are
            // worse than missing a brief load spike.
            let cpu_count = std::thread::available_parallelism()
                .map(|n| n.get() as f32)
                .unwrap_or(1.0);
            2.0 * cpu_count
        };
        let load_warning = if cfg.load_1m_warning > 0.0 {
            cfg.load_1m_warning
        } else {
            load_critical * LOAD_WARNING_RATIO
        };

        Self {
            disk_warning,
            disk_critical,
            memory_warning,
            memory_critical,
            load_warning,
            load_critical,
            sys: System::new(),
            disks: Disks::new_with_refreshed_list(),
            last_disk_zone: HashMap::new(),
            last_memory_zone: Zone::Ok,
            last_load_zone: Zone::Ok,
        }
    }

    pub fn load_threshold(&self) -> f32 {
        self.load_critical
    }

    #[cfg(test)]
    pub fn load_warning_threshold(&self) -> f32 {
        self.load_warning
    }

    #[cfg(test)]
    pub fn disk_warning_threshold(&self) -> u8 {
        self.disk_warning
    }

    #[cfg(test)]
    pub fn memory_warning_threshold(&self) -> u8 {
        self.memory_warning
    }

    /// Rising-edge-only: emit on each upward zone transition (Ok→Warning,
    /// Ok→Critical, Warning→Critical), then stay silent until the value
    /// drops back. The control plane treats the most recent event as the
    /// active alert; recovery is handled server-side.
    pub fn tick(&mut self) -> Vec<Event> {
        let mut events = Vec::new();

        self.sys.refresh_memory();
        self.disks.refresh();

        // Disk — emit per-mount.
        for disk in &self.disks {
            let total = disk.total_space();
            if total == 0 {
                continue;
            }
            let mount = disk.mount_point().to_string_lossy().to_string();
            let used = total.saturating_sub(disk.available_space());
            let percent = ((used as f64 / total as f64) * 100.0).round().min(100.0) as u8;

            let prev = self.last_disk_zone.get(&mount).copied().unwrap_or(Zone::Ok);
            let next = next_zone_u8(prev, percent, self.disk_warning, self.disk_critical);
            if let Some(ev) = disk_transition_event(prev, next, &mount, percent) {
                events.push(ev);
            }
            self.last_disk_zone.insert(mount, next);
        }

        // Memory.
        let mem_total = self.sys.total_memory();
        if mem_total > 0 {
            let used = self.sys.used_memory();
            let percent = ((used as f64 / mem_total as f64) * 100.0)
                .round()
                .min(100.0) as u8;
            let next = next_zone_u8(
                self.last_memory_zone,
                percent,
                self.memory_warning,
                self.memory_critical,
            );
            if let Some(ev) = memory_transition_event(self.last_memory_zone, next, percent) {
                events.push(ev);
            }
            self.last_memory_zone = next;
        }

        // Load — 1-minute average.
        let load = System::load_average();
        let load_1m = load.one as f32;
        let next = next_zone_f32(
            self.last_load_zone,
            load_1m,
            self.load_warning,
            self.load_critical,
        );
        if let Some(ev) = load_transition_event(self.last_load_zone, next, load_1m) {
            events.push(ev);
        }
        self.last_load_zone = next;

        events
    }
}

fn resolve_warning_u8(configured: u8, critical: u8) -> u8 {
    if configured > 0 && configured < critical {
        configured
    } else {
        // Default: 10pp below critical, but never below MIN_WARNING_PERCENT.
        // If the user set warning >= critical (config error), fall through to default —
        // the warning is meaningless if critical fires first anyway.
        critical
            .saturating_sub(DEFAULT_WARNING_OFFSET)
            .max(MIN_WARNING_PERCENT)
    }
}

/// Zone state machine for u8-valued metrics (disk, memory percent).
fn next_zone_u8(current: Zone, value: u8, warn_t: u8, crit_t: u8) -> Zone {
    match current {
        Zone::Ok => {
            if value >= crit_t {
                Zone::Critical
            } else if value >= warn_t {
                Zone::Warning
            } else {
                Zone::Ok
            }
        }
        Zone::Warning => {
            if value >= crit_t {
                Zone::Critical
            } else if value < warn_t.saturating_sub(HYSTERESIS_MARGIN) {
                Zone::Ok
            } else {
                Zone::Warning
            }
        }
        Zone::Critical => {
            if value < crit_t.saturating_sub(HYSTERESIS_MARGIN) {
                if value >= warn_t {
                    Zone::Warning
                } else {
                    Zone::Ok
                }
            } else {
                Zone::Critical
            }
        }
    }
}

/// Zone state machine for f32-valued metrics (load).
fn next_zone_f32(current: Zone, value: f32, warn_t: f32, crit_t: f32) -> Zone {
    match current {
        Zone::Ok => {
            if value >= crit_t {
                Zone::Critical
            } else if value >= warn_t {
                Zone::Warning
            } else {
                Zone::Ok
            }
        }
        Zone::Warning => {
            if value >= crit_t {
                Zone::Critical
            } else if value < warn_t * LOAD_CLEAR_RATIO {
                Zone::Ok
            } else {
                Zone::Warning
            }
        }
        Zone::Critical => {
            if value < crit_t * LOAD_CLEAR_RATIO {
                if value >= warn_t {
                    Zone::Warning
                } else {
                    Zone::Ok
                }
            } else {
                Zone::Critical
            }
        }
    }
}

fn disk_transition_event(prev: Zone, next: Zone, mount: &str, percent: u8) -> Option<Event> {
    match (prev, next) {
        (Zone::Ok, Zone::Warning) => Some(Event::DiskWarning {
            mount: mount.to_string(),
            percent,
        }),
        (Zone::Ok, Zone::Critical) | (Zone::Warning, Zone::Critical) => Some(Event::DiskHigh {
            mount: mount.to_string(),
            percent,
        }),
        _ => None,
    }
}

fn memory_transition_event(prev: Zone, next: Zone, percent: u8) -> Option<Event> {
    match (prev, next) {
        (Zone::Ok, Zone::Warning) => Some(Event::MemoryWarning { percent }),
        (Zone::Ok, Zone::Critical) | (Zone::Warning, Zone::Critical) => {
            Some(Event::MemoryHigh { percent })
        }
        _ => None,
    }
}

fn load_transition_event(prev: Zone, next: Zone, load_1m: f32) -> Option<Event> {
    match (prev, next) {
        (Zone::Ok, Zone::Warning) => Some(Event::LoadWarning { load_1m }),
        (Zone::Ok, Zone::Critical) | (Zone::Warning, Zone::Critical) => {
            Some(Event::LoadHigh { load_1m })
        }
        _ => None,
    }
}

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

    fn cfg(disk: u8, mem: u8, load: f32) -> ResourceProbeConfig {
        ResourceProbeConfig {
            disk_high_percent: disk,
            disk_warning_percent: 0,
            memory_high_percent: mem,
            memory_warning_percent: 0,
            load_1m_high: load,
            load_1m_warning: 0.0,
        }
    }

    #[test]
    fn auto_load_threshold_when_unset() {
        let p = ResourceProbe::new(&cfg(90, 90, 0.0));
        assert!(p.load_threshold() > 0.0);
        // Warning threshold is 75% of critical.
        assert!(p.load_warning_threshold() < p.load_threshold());
        assert!(p.load_warning_threshold() > 0.0);
    }

    #[test]
    fn explicit_load_threshold_is_honored() {
        let p = ResourceProbe::new(&cfg(90, 90, 7.5));
        assert!((p.load_threshold() - 7.5).abs() < f32::EPSILON);
    }

    #[test]
    fn auto_disk_warning_is_10pp_below_critical() {
        let p = ResourceProbe::new(&cfg(90, 90, 0.0));
        assert_eq!(p.disk_warning_threshold(), 80);
        assert_eq!(p.memory_warning_threshold(), 80);
    }

    #[test]
    fn explicit_disk_warning_is_honored() {
        let mut c = cfg(90, 90, 0.0);
        c.disk_warning_percent = 75;
        c.memory_warning_percent = 70;
        let p = ResourceProbe::new(&c);
        assert_eq!(p.disk_warning_threshold(), 75);
        assert_eq!(p.memory_warning_threshold(), 70);
    }

    #[test]
    fn warning_floors_at_50_percent_for_low_critical() {
        // Critical at 55% would auto-derive warning at 45 — clamp to 50%.
        let mut c = cfg(55, 55, 0.0);
        let p = ResourceProbe::new(&c);
        assert_eq!(p.disk_warning_threshold(), 50);
        // And a critical of 30 would clamp to 50 even though that exceeds critical;
        // with warning >= critical the state machine just never emits a Warning event,
        // which is fine — Critical fires first.
        c.disk_high_percent = 30;
        let p = ResourceProbe::new(&c);
        assert_eq!(p.disk_warning_threshold(), 50);
    }

    #[test]
    fn invalid_explicit_warning_falls_back_to_default() {
        // warning >= critical is nonsensical; the resolver should fall back.
        let mut c = cfg(80, 80, 0.0);
        c.disk_warning_percent = 85; // higher than critical
        let p = ResourceProbe::new(&c);
        assert_eq!(p.disk_warning_threshold(), 70); // 80 - 10
    }

    #[test]
    fn high_threshold_disables_alerts_on_healthy_host() {
        let mut p = ResourceProbe::new(&cfg(100, 100, 1_000_000.0));
        let events = p.tick();
        for e in &events {
            assert!(
                !matches!(
                    e,
                    Event::DiskHigh { .. }
                        | Event::DiskWarning { .. }
                        | Event::MemoryHigh { .. }
                        | Event::MemoryWarning { .. }
                        | Event::LoadHigh { .. }
                        | Event::LoadWarning { .. }
                ),
                "unexpected alert at impossible thresholds: {e:?}"
            );
        }
    }

    // ── State machine tests (pure, no syscall noise) ──

    #[test]
    fn zone_ok_to_warning_to_critical() {
        // 80% warn, 90% crit
        assert_eq!(next_zone_u8(Zone::Ok, 75, 80, 90), Zone::Ok);
        assert_eq!(next_zone_u8(Zone::Ok, 80, 80, 90), Zone::Warning);
        assert_eq!(next_zone_u8(Zone::Warning, 85, 80, 90), Zone::Warning);
        assert_eq!(next_zone_u8(Zone::Warning, 90, 80, 90), Zone::Critical);
    }

    #[test]
    fn zone_ok_jumps_directly_to_critical_when_value_spikes() {
        // Value jumps Ok→Critical (skipping Warning) — Critical is the right zone.
        assert_eq!(next_zone_u8(Zone::Ok, 95, 80, 90), Zone::Critical);
    }

    #[test]
    fn zone_critical_clears_through_warning_with_hysteresis() {
        // Critical→Warning requires value < 90 - HYSTERESIS_MARGIN(5) = 85.
        assert_eq!(next_zone_u8(Zone::Critical, 88, 80, 90), Zone::Critical); // still in hysteresis
        assert_eq!(next_zone_u8(Zone::Critical, 84, 80, 90), Zone::Warning); // dropped enough
        assert_eq!(next_zone_u8(Zone::Critical, 70, 80, 90), Zone::Ok); // dropped well past warning too
    }

    #[test]
    fn zone_warning_clears_to_ok_with_hysteresis() {
        // Warning→Ok requires value < 80 - 5 = 75.
        assert_eq!(next_zone_u8(Zone::Warning, 76, 80, 90), Zone::Warning);
        assert_eq!(next_zone_u8(Zone::Warning, 74, 80, 90), Zone::Ok);
    }

    #[test]
    fn transition_events_match_expected_severity() {
        // Ok→Warning emits Warning
        assert!(matches!(
            disk_transition_event(Zone::Ok, Zone::Warning, "/", 82),
            Some(Event::DiskWarning { percent: 82, .. })
        ));
        // Ok→Critical emits High (skipping Warning event — value already critical)
        assert!(matches!(
            disk_transition_event(Zone::Ok, Zone::Critical, "/", 95),
            Some(Event::DiskHigh { percent: 95, .. })
        ));
        // Warning→Critical emits High (escalation)
        assert!(matches!(
            disk_transition_event(Zone::Warning, Zone::Critical, "/", 92),
            Some(Event::DiskHigh { percent: 92, .. })
        ));
        // Critical→Warning is a downgrade — no event (recovery handled server-side)
        assert!(disk_transition_event(Zone::Critical, Zone::Warning, "/", 85).is_none());
        // Warning→Ok is a recovery — no event
        assert!(disk_transition_event(Zone::Warning, Zone::Ok, "/", 50).is_none());
    }

    #[test]
    fn load_zone_uses_ratio_hysteresis() {
        // Critical→Warning when load drops below crit * 0.9 = 9.0
        assert_eq!(
            next_zone_f32(Zone::Critical, 9.5, 7.5, 10.0),
            Zone::Critical
        );
        assert_eq!(next_zone_f32(Zone::Critical, 8.5, 7.5, 10.0), Zone::Warning);
        // Warning→Ok when load drops below warn * 0.9 = 6.75
        assert_eq!(next_zone_f32(Zone::Warning, 7.0, 7.5, 10.0), Zone::Warning);
        assert_eq!(next_zone_f32(Zone::Warning, 6.5, 7.5, 10.0), Zone::Ok);
    }
}