asterust-junos 0.5.11

Typed Juniper JunOS config views (interfaces, protocols, routing instances and options, policy options, firewall filters, class of service, system, services) extracted from an asterust config tree.
Documentation
//! `monitor`
//! `system { monitor { memory { ... } } }`.
//!
//! # See also
//!
//! - [memory (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/memory-edit-system-monitor.html)
//! - [process (Memory)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/process-edit-system-monitor-memory.html)
//! - [minor-event (Process)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/minor-event-process-edit-system-monitor-memory.html)
//! - [major-event (Process)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/major-event-process-edit-system-monitor-memory.html)
//! - [critical-event (Process)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/critical-event-process-edit-system-monitor-memory.html)
//! - [minor-event (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/minor-event-system-edit-system-monitor-memory.html)
//! - [major-event (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/major-event-system-edit-system-monitor-memory.html)
//! - [critical-event (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/critical-event-system-edit-system-monitor-memory.html)

use crate::protocols::traceoptions::{parse_traceoptions, Traceoptions};
use crate::{arg_of, args_of, child_block, has_leaf, list_values, split_keyword, value_after};
use asterust::config::ConfigLine;

/// A `minor-event`, `major-event` or `critical-event` of the system-level memory monitor.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SystemMemoryEvent {
    /// Percentage, from `threshold swap-usage`.
    pub swap_usage_threshold: Option<String>,
    /// e.g. `snmp-trap`, `live-vmcore`, `RE-restart`, `RE-switchover`.
    pub actions: Vec<String>,
}

/// A `threshold <process> memory-limit <limit>` of a process-level event.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ProcessMemoryThreshold {
    pub process: String,
    /// MB.
    pub memory_limit: Option<String>,
}

/// A `minor-event`, `major-event` or `critical-event` of the process-level memory monitor.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ProcessMemoryEvent {
    pub thresholds: Vec<ProcessMemoryThreshold>,
    /// e.g. `snmp-trap`, `live-core`, `terminate-process`, `terminate-process-force`.
    pub actions: Vec<String>,
}

/// The `memory system` block.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SystemMemoryMonitor {
    pub alarm: bool,
    /// How often usage is checked, e.g. `minutes 5`.
    pub frequency: Option<String>,
    pub minor_event: Option<SystemMemoryEvent>,
    pub major_event: Option<SystemMemoryEvent>,
    pub critical_event: Option<SystemMemoryEvent>,
}

/// The `memory process` block.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ProcessMemoryMonitor {
    /// How often usage is checked, e.g. `minutes 5`.
    pub frequency: Option<String>,
    pub minor_event: Option<ProcessMemoryEvent>,
    pub major_event: Option<ProcessMemoryEvent>,
    pub critical_event: Option<ProcessMemoryEvent>,
}

/// The `memory` block of `system monitor`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct MemoryMonitor {
    pub system: Option<SystemMemoryMonitor>,
    pub process: Option<ProcessMemoryMonitor>,
}

/// The `system monitor` settings.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Monitor {
    pub memory: Option<MemoryMonitor>,
    pub traceoptions: Option<Traceoptions>,
}

fn actions(event: &ConfigLine) -> Vec<String> {
    args_of(event, "action").into_iter().flat_map(list_values).collect()
}

fn system_event(event: &ConfigLine) -> SystemMemoryEvent {
    SystemMemoryEvent {
        swap_usage_threshold: arg_of(event, "threshold").and_then(|threshold| {
            let words: Vec<&str> = threshold.split_whitespace().collect();
            value_after(&words, "swap-usage")
        }),
        actions: actions(event),
    }
}

fn process_event(event: &ConfigLine) -> ProcessMemoryEvent {
    ProcessMemoryEvent {
        thresholds: args_of(event, "threshold")
            .into_iter()
            .map(|threshold| {
                let (process, rest) = split_keyword(threshold);
                let words: Vec<&str> = rest.split_whitespace().collect();
                ProcessMemoryThreshold {
                    process: process.to_string(),
                    memory_limit: value_after(&words, "memory-limit"),
                }
            })
            .collect(),
        actions: actions(event),
    }
}

pub(super) fn parse_monitor(monitor: &ConfigLine) -> Monitor {
    Monitor {
        memory: child_block(monitor, "memory").map(|memory| MemoryMonitor {
            system: child_block(memory, "system").map(|system| SystemMemoryMonitor {
                alarm: has_leaf(system, "alarm"),
                frequency: arg_of(system, "frequency").map(str::to_string),
                minor_event: child_block(system, "minor-event").map(system_event),
                major_event: child_block(system, "major-event").map(system_event),
                critical_event: child_block(system, "critical-event").map(system_event),
            }),
            process: child_block(memory, "process").map(|process| ProcessMemoryMonitor {
                frequency: arg_of(process, "frequency").map(str::to_string),
                minor_event: child_block(process, "minor-event").map(process_event),
                major_event: child_block(process, "major-event").map(process_event),
                critical_event: child_block(process, "critical-event").map(process_event),
            }),
        }),
        traceoptions: parse_traceoptions(monitor),
    }
}

#[cfg(test)]
mod tests {
    use crate::system::system;
    use asterust::config::juniper;

    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
    #[test]
    fn extracts_the_memory_monitor() {
        let monitor = system(&juniper::parse_braces(
            r#"
system {
    monitor {
        memory {
            system {
                alarm;
                frequency minutes 5;
                minor-event {
                    threshold swap-usage 20;
                    action snmp-trap;
                }
                critical-event {
                    threshold swap-usage 80;
                    action [ snmp-trap live-vmcore RE-switchover ];
                }
            }
            process {
                frequency hours 1;
                major-event {
                    threshold rpd memory-limit 2048;
                    threshold mgd memory-limit 512;
                    action [ snmp-trap terminate-process ];
                }
            }
        }
        traceoptions {
            file monitor.log;
            flag all;
        }
    }
}
"#,
        ))
        .unwrap()
        .monitor
        .unwrap();
        let memory = monitor.memory.unwrap();
        let system = memory.system.unwrap();
        assert!(system.alarm);
        assert_eq!(system.frequency.as_deref(), Some("minutes 5"));
        let minor = system.minor_event.unwrap();
        assert_eq!(minor.swap_usage_threshold.as_deref(), Some("20"));
        assert_eq!(minor.actions, ["snmp-trap"]);
        assert!(system.major_event.is_none());
        let critical = system.critical_event.unwrap();
        assert_eq!(critical.swap_usage_threshold.as_deref(), Some("80"));
        assert_eq!(critical.actions, ["snmp-trap", "live-vmcore", "RE-switchover"]);

        let process = memory.process.unwrap();
        assert_eq!(process.frequency.as_deref(), Some("hours 1"));
        let major = process.major_event.unwrap();
        assert_eq!(major.thresholds.len(), 2);
        assert_eq!(major.thresholds[0].process, "rpd");
        assert_eq!(major.thresholds[0].memory_limit.as_deref(), Some("2048"));
        assert_eq!(major.thresholds[1].process, "mgd");
        assert_eq!(major.actions, ["snmp-trap", "terminate-process"]);
        assert!(process.minor_event.is_none());
        assert_eq!(monitor.traceoptions.unwrap().file.as_deref(), Some("monitor.log"));
    }

    #[test]
    fn no_monitor_is_none() {
        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
        assert!(system.monitor.is_none());
    }
}