asterust-junos 0.5.9

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
//! `processes`
//! `system { processes { ... } }`.
//!
//! # See also
//!
//! - [processes](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/processes-edit-system.html)
//! - [traceoptions (DHCP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/traceoptions-edit-system-processes-dhcp-service.html)
//! - [interface-traceoptions (DHCP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/interface-traceoptions-edit-system-processes-dhcp-service.html)
//! - [dhcp-snooping-file](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/dhcp-snooping-file-edit-system-processess-dhcp-service.html)
//! - [dhcpv6-snooping-file](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/dhcpv6-snooping-file-edit-system-processess-dhcp-service.html)
//! - [accept-max-tcp-connections](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/accept-max-tcp-connections-edit-system-process.html)
//! - [request-max-tcp-connections](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/request-max-tcp-connections-edit-system-process.html)
//! - [ltv-syslog-interval](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/ltv-syslog-interval-edit-system-process.html)
//! - [routing (System Processes)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/routing-edit-system-processes.html)
//! - [watchdog](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/watchdog-edit-system-processes.html)
//! - [process-monitor](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/process-monitor-edit-system.html)
//! - [resource-cleanup](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/resource-cleanup-edit-system.html)
//! - [smg-service](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/smg-service-edit-system-processes.html)

use crate::protocols::traceoptions::{parse_named_traceoptions, parse_traceoptions, Traceoptions};
use crate::{active_children, arg_of};
use asterust::config::ConfigLine;

/// A `dhcp-snooping-file` or `dhcpv6-snooping-file` of `dhcp-service`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct SnoopingFile {
    /// A local path or a remote URL.
    pub location: Option<String>,
    /// Seconds between writes of the database.
    pub write_interval: Option<String>,
    pub timeout: Option<String>,
}

/// A process under `system processes`, e.g. `routing` or `dhcp-service`; `all-processes` appears
/// here too. The options only some processes have are `None` for the others.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Process {
    pub name: String,
    /// `Some(true)` for `enable`, `Some(false)` for `disable`, `None` if neither is written.
    pub enabled: Option<bool>,
    /// `alternate-media` or `other-routing-engine`.
    pub failover: Option<String>,
    /// Seconds.
    pub timeout: Option<String>,
    pub no_livecore_dump_on_crash: bool,
    /// Path of the process binary, from `command`.
    pub command: Option<String>,
    pub traceoptions: Option<Traceoptions>,
    /// `force-32-bit`, `force-64-bit` or `auto-64-bit`, on `routing`.
    pub address_mode: Option<String>,
    /// `dhcp-service` `interface-traceoptions`.
    pub interface_traceoptions: Option<Traceoptions>,
    pub accept_max_tcp_connections: Option<String>,
    pub request_max_tcp_connections: Option<String>,
    /// Seconds, on `dhcp-service`.
    pub ltv_syslog_interval: Option<String>,
    pub dhcp_snooping_file: Option<SnoopingFile>,
    pub dhcpv6_snooping_file: Option<SnoopingFile>,
}

/// `<keyword> <location>;`, or a block with `location`, `write-interval` and `timeout`.
fn snooping_file(process: &ConfigLine, keyword: &str) -> Option<SnoopingFile> {
    let statement = active_children(process).find(|c| c.text == keyword || c.arg(keyword).is_some())?;
    Some(SnoopingFile {
        location: statement
            .arg(keyword)
            .or_else(|| arg_of(statement, "location"))
            .map(|location| location.trim_matches('"').to_string()),
        write_interval: arg_of(statement, "write-interval").map(str::to_string),
        timeout: arg_of(statement, "timeout").map(str::to_string),
    })
}

/// Processes written either as `<name> disable;` or as `<name> { disable; failover ...; }`.
pub(super) fn parse_processes(processes: &ConfigLine) -> Vec<Process> {
    active_children(processes)
        .filter_map(|child| {
            let mut name_and_rest = child.text.split_whitespace();
            let name = name_and_rest.next()?.to_string();
            let mut words = name_and_rest.chain(active_children(child).flat_map(|c| c.text.split_whitespace()));
            let mut process = Process {
                name,
                enabled: None,
                failover: None,
                timeout: None,
                no_livecore_dump_on_crash: false,
                command: None,
                traceoptions: parse_traceoptions(child),
                address_mode: None,
                interface_traceoptions: parse_named_traceoptions(child, "interface-traceoptions"),
                accept_max_tcp_connections: None,
                request_max_tcp_connections: None,
                ltv_syslog_interval: None,
                dhcp_snooping_file: snooping_file(child, "dhcp-snooping-file"),
                dhcpv6_snooping_file: snooping_file(child, "dhcpv6-snooping-file"),
            };
            while let Some(word) = words.next() {
                match word {
                    "enable" => process.enabled = Some(true),
                    "disable" => process.enabled = Some(false),
                    "failover" => process.failover = words.next().map(str::to_string),
                    "timeout" => process.timeout = words.next().map(str::to_string),
                    "no-livecore-dump-on-crash" => process.no_livecore_dump_on_crash = true,
                    "command" => process.command = words.next().map(str::to_string),
                    "force-32-bit" | "force-64-bit" | "auto-64-bit" => process.address_mode = Some(word.to_string()),
                    "accept-max-tcp-connections" => {
                        process.accept_max_tcp_connections = words.next().map(str::to_string)
                    }
                    "request-max-tcp-connections" => {
                        process.request_max_tcp_connections = words.next().map(str::to_string)
                    }
                    "ltv-syslog-interval" => process.ltv_syslog_interval = words.next().map(str::to_string),
                    _ => {}
                }
            }
            Some(process)
        })
        .collect()
}

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

    // Not from documentation: written from the CLI Reference syntax page. See the README "Sources".
    const PROCESSES: &str = r#"
system {
    processes {
        dhcp-service disable;
        routing enable failover other-routing-engine;
        mib-process {
            enable;
            timeout 60;
            traceoptions {
                file mib.log;
                flag all;
            }
        }
        inactive: ntp disable;
        all-processes {
            no-livecore-dump-on-crash;
        }
    }
}
"#;

    #[test]
    fn extracts_processes_in_line_and_block_form() {
        let processes = system(&juniper::parse_braces(PROCESSES)).unwrap().processes;
        let names: Vec<_> = processes.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, ["dhcp-service", "routing", "mib-process", "all-processes"]);

        assert_eq!(processes[0].enabled, Some(false));
        assert_eq!(processes[1].enabled, Some(true));
        assert_eq!(processes[1].failover.as_deref(), Some("other-routing-engine"));
        assert_eq!(processes[2].enabled, Some(true));
        assert_eq!(processes[2].timeout.as_deref(), Some("60"));
    }

    #[test]
    fn extracts_process_flags() {
        let processes = system(&juniper::parse_braces(PROCESSES)).unwrap().processes;
        assert!(processes[3].no_livecore_dump_on_crash);
        assert_eq!(processes[3].enabled, None);
        assert!(!processes[0].no_livecore_dump_on_crash);
    }

    #[test]
    fn extracts_process_commands_and_traceoptions() {
        let processes = system(&juniper::parse_braces(
            r#"
system {
    processes {
        usb-control {
            command /usr/sbin/usbd;
            disable;
        }
        process-monitor {
            traceoptions {
                file pmond.log files 3 size 1m world-readable;
                flag all;
                level verbose;
                no-remote-trace;
            }
        }
        tcp-forwarding {
            traceoptions {
                file tcpfwd {
                    files 4;
                    size 2m;
                    match "error";
                }
                flag configuration;
            }
        }
        routing {
            force-64-bit;
        }
    }
}
"#,
        ))
        .unwrap()
        .processes;
        assert_eq!(processes[0].command.as_deref(), Some("/usr/sbin/usbd"));
        assert_eq!(processes[0].enabled, Some(false));

        let trace = processes[1].traceoptions.as_ref().unwrap();
        assert_eq!(trace.file.as_deref(), Some("pmond.log"));
        assert_eq!(trace.files.as_deref(), Some("3"));
        assert_eq!(trace.size.as_deref(), Some("1m"));
        assert_eq!(trace.world_readable, Some(true));
        assert_eq!(trace.level.as_deref(), Some("verbose"));
        assert!(trace.no_remote_trace);
        assert_eq!(trace.flags[0].name, "all");

        let block_form = processes[2].traceoptions.as_ref().unwrap();
        assert_eq!(block_form.file.as_deref(), Some("tcpfwd"));
        assert_eq!(block_form.files.as_deref(), Some("4"));
        assert_eq!(block_form.size.as_deref(), Some("2m"));
        assert_eq!(block_form.match_regex.as_deref(), Some("error"));

        assert_eq!(processes[3].address_mode.as_deref(), Some("force-64-bit"));
        assert!(processes[0].traceoptions.is_none());
    }

    #[test]
    fn extracts_dhcp_service_options() {
        let processes = system(&juniper::parse_braces(
            r#"
system {
    processes {
        dhcp-service {
            accept-max-tcp-connections 8;
            request-max-tcp-connections 4;
            ltv-syslog-interval 900;
            dhcp-snooping-file /var/db/snoop.db {
                write-interval 600;
            }
            dhcpv6-snooping-file {
                location "ftp://192.0.2.9/snoop6.db";
                timeout 30;
                write-interval 120;
            }
            interface-traceoptions {
                file dhcp-if.log;
                flag all;
            }
        }
    }
}
"#,
        ))
        .unwrap()
        .processes;
        let dhcp = &processes[0];
        assert_eq!(dhcp.accept_max_tcp_connections.as_deref(), Some("8"));
        assert_eq!(dhcp.request_max_tcp_connections.as_deref(), Some("4"));
        assert_eq!(dhcp.ltv_syslog_interval.as_deref(), Some("900"));
        let v4 = dhcp.dhcp_snooping_file.as_ref().unwrap();
        assert_eq!(v4.location.as_deref(), Some("/var/db/snoop.db"));
        assert_eq!(v4.write_interval.as_deref(), Some("600"));
        assert_eq!(v4.timeout, None);
        let v6 = dhcp.dhcpv6_snooping_file.as_ref().unwrap();
        assert_eq!(v6.location.as_deref(), Some("ftp://192.0.2.9/snoop6.db"));
        assert_eq!(v6.timeout.as_deref(), Some("30"));
        assert_eq!(v6.write_interval.as_deref(), Some("120"));
        assert_eq!(
            dhcp.interface_traceoptions.as_ref().unwrap().file.as_deref(),
            Some("dhcp-if.log")
        );
        // The snooping file's `timeout` is not the process timeout.
        assert_eq!(dhcp.timeout, None);
    }

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