asterust-junos 0.5.14

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
//! `syslog`
//! `system { syslog { ... } }`.
//!
//! # See also
//!
//! - [syslog (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/syslog-edit-system.html)
//! - [grpc-replay](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/edit-system-syslog-grpc-replay.html)
//! - [console (System Logging)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/console-edit-system-syslog.html)
//! - [routing-instance (Syslog)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/routing-instance-edit-system-syslog.html)
//! - [server (syslog)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/server-edit-system-syslog.html)

mod archive;
mod file;
mod host;
mod user;

pub use archive::SyslogArchive;
pub use file::{SyslogStructuredData, SyslogTarget};
pub use host::{SyslogHost, SyslogTlsDetails};

use crate::{active_children, arg_of, child_block, has_leaf, named_children, value_after};
use archive::parse_archive;
use asterust::config::ConfigLine;
use file::files;
use host::parse_host;
use user::users;

/// A `<facility> <severity>` line selecting which messages go to a syslog destination.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SyslogRule {
    /// e.g. `"any"`, `"authorization"`, `"interactive-commands"`.
    pub facility: String,
    /// e.g. `"info"`, `"notice"`, `"any"`, `"none"`.
    pub severity: String,
}

/// The `grpc-replay` statement: which stored events are replayed before the live ones.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct GrpcReplay {
    /// Minutes, from `last`.
    pub last_minutes: Option<String>,
    pub facility: Option<String>,
    pub priority: Option<String>,
}

/// The `system syslog` configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Syslog {
    pub hosts: Vec<SyslogHost>,
    pub files: Vec<SyslogTarget>,
    pub users: Vec<SyslogTarget>,
    pub console: Vec<SyslogRule>,
    pub source_address: Option<String>,
    /// e.g. `"year millisecond"`.
    pub time_format: Option<String>,
    /// The default archive settings that files inherit.
    pub archive: Option<SyslogArchive>,
    pub allow_duplicates: bool,
    pub log_rotate_frequency: Option<String>,
    /// From `console { application-status (any | error); }`.
    pub console_application_status: Option<String>,
    pub routing_instance: Option<String>,
    pub grpc_replay: Option<GrpcReplay>,
    /// The routing instances (or `all` or `default`) disabled in `server { routing-instances ... { disable; } }`.
    pub server_disabled_routing_instances: Vec<String>,
}

/// Children written `<facility> <severity>`, which tells them apart from options such as `port
/// 514`.
fn syslog_rules(destination: &ConfigLine) -> Vec<SyslogRule> {
    const SEVERITIES: [&str; 10] = [
        "any",
        "none",
        "emergency",
        "alert",
        "critical",
        "error",
        "warning",
        "notice",
        "info",
        "debug",
    ];
    active_children(destination)
        .filter_map(|c| {
            let (facility, severity) = c.text.split_once(' ')?;
            (facility != "application-status" && SEVERITIES.contains(&severity)).then(|| SyslogRule {
                facility: facility.to_string(),
                severity: severity.to_string(),
            })
        })
        .collect()
}

pub(super) fn parse_syslog(syslog: &ConfigLine) -> Syslog {
    Syslog {
        hosts: named_children(syslog, "host")
            .map(|(address, host)| parse_host(address, host))
            .collect(),
        files: files(syslog),
        users: users(syslog),
        console: child_block(syslog, "console").map(syslog_rules).unwrap_or_default(),
        source_address: arg_of(syslog, "source-address").map(str::to_string),
        time_format: arg_of(syslog, "time-format").map(str::to_string),
        archive: parse_archive(syslog),
        allow_duplicates: has_leaf(syslog, "allow-duplicates"),
        log_rotate_frequency: arg_of(syslog, "log-rotate-frequency").map(str::to_string),
        console_application_status: child_block(syslog, "console")
            .and_then(|console| arg_of(console, "application-status"))
            .map(str::to_string),
        routing_instance: arg_of(syslog, "routing-instance").map(str::to_string),
        grpc_replay: arg_of(syslog, "grpc-replay").map(|arg| {
            let words: Vec<&str> = arg.split_whitespace().collect();
            GrpcReplay {
                last_minutes: value_after(&words, "last"),
                facility: value_after(&words, "facility"),
                priority: value_after(&words, "priority"),
            }
        }),
        server_disabled_routing_instances: child_block(syslog, "server")
            .map(|server| {
                named_children(server, "routing-instances")
                    .filter(|(_, instance)| has_leaf(instance, "disable"))
                    .map(|(name, _)| name.to_string())
                    .collect()
            })
            .unwrap_or_default(),
    }
}

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

    const SYSLOG: &str = r#"
system {
    syslog {
        user * {
            any emergency;
        }
        host 192.0.2.5 {
            any notice;
            authorization info;
            port 514;
            source-address 192.0.2.1;
            routing-instance mgmt_junos;
            facility-override local3;
            log-prefix pe1;
        }
        host other-routing-engine {
            any critical;
        }
        file messages {
            any notice;
            authorization info;
            explicit-priority;
        }
        file interactive-commands {
            interactive-commands any;
        }
        inactive: file debug {
            any debug;
        }
        console {
            any critical;
        }
        source-address 192.0.2.1;
        time-format year millisecond;
    }
}
"#;

    #[test]
    fn extracts_syslog_hosts() {
        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
        let addresses: Vec<_> = syslog.hosts.iter().map(|h| h.address.as_str()).collect();
        assert_eq!(addresses, ["192.0.2.5", "other-routing-engine"]);

        let host = &syslog.hosts[0];
        assert_eq!(host.rules.len(), 2);
        assert_eq!(host.rules[1].facility, "authorization");
        assert_eq!(host.rules[1].severity, "info");
        assert_eq!(host.port.as_deref(), Some("514"));
        assert_eq!(host.source_address.as_deref(), Some("192.0.2.1"));
        assert_eq!(host.routing_instance.as_deref(), Some("mgmt_junos"));
        assert_eq!(host.facility_override.as_deref(), Some("local3"));
        assert_eq!(host.log_prefix.as_deref(), Some("pe1"));
    }

    #[test]
    fn extracts_syslog_files_users_and_console() {
        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();

        let files: Vec<_> = syslog.files.iter().map(|f| f.name.as_str()).collect();
        assert_eq!(files, ["messages", "interactive-commands"]);
        // `explicit-priority` is an option, not a facility/severity rule.
        assert_eq!(syslog.files[0].rules.len(), 2);
        assert_eq!(syslog.files[1].rules[0].facility, "interactive-commands");
        assert_eq!(syslog.files[1].rules[0].severity, "any");

        assert_eq!(syslog.users[0].name, "*");
        assert_eq!(syslog.users[0].rules[0].severity, "emergency");
        assert_eq!(syslog.console[0].facility, "any");
        assert_eq!(syslog.console[0].severity, "critical");
    }

    #[test]
    fn extracts_syslog_global_settings() {
        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
        assert_eq!(syslog.source_address.as_deref(), Some("192.0.2.1"));
        assert_eq!(syslog.time_format.as_deref(), Some("year millisecond"));
    }

    #[test]
    fn extracts_syslog_destination_options() {
        let syslog = system(&juniper::parse_braces(
            r#"
system {
    syslog {
        allow-duplicates;
        log-rotate-frequency 5;
        host 192.0.2.5 {
            any notice;
            allow-duplicates;
            explicit-priority;
            exclude-hostname;
            match "UI_COMMIT";
        }
        file messages {
            any notice;
            allow-duplicates;
            explicit-priority;
            match "!(ssh)";
            structured-data {
                brief;
            }
        }
        file plain {
            any info;
            structured-data;
        }
        user admin {
            any alert;
            match "commit";
        }
    }
}
"#,
        ))
        .unwrap()
        .syslog
        .unwrap();
        assert!(syslog.allow_duplicates);
        assert_eq!(syslog.log_rotate_frequency.as_deref(), Some("5"));

        let host = &syslog.hosts[0];
        assert!(host.allow_duplicates);
        assert!(host.explicit_priority);
        assert!(host.exclude_hostname);
        assert_eq!(host.match_regex.as_deref(), Some("UI_COMMIT"));

        let messages = &syslog.files[0];
        assert!(messages.allow_duplicates);
        assert!(messages.explicit_priority);
        assert_eq!(messages.match_regex.as_deref(), Some("!(ssh)"));
        assert!(messages.structured_data.as_ref().unwrap().brief);

        let plain = &syslog.files[1];
        assert!(!plain.structured_data.as_ref().unwrap().brief);
        assert!(!plain.allow_duplicates);
        assert_eq!(plain.match_regex, None);

        assert_eq!(syslog.users[0].match_regex.as_deref(), Some("commit"));
    }

    #[test]
    fn extracts_the_host_tls_details() {
        let host = system(&juniper::parse_braces(
            "system {\n    syslog {\n        host 192.0.2.5 {\n            any notice;\n            transport tls;\n            tlsdetails {\n                local-certificate syslog-cert;\n                trusted-ca-group tcg1 {\n                    ca-profiles [ ca1 ca2 ];\n                }\n            }\n        }\n    }\n}\n",
        ))
        .unwrap()
        .syslog
        .unwrap()
        .hosts
        .remove(0);
        let tls = host.tls_details.unwrap();
        assert_eq!(tls.local_certificate.as_deref(), Some("syslog-cert"));
        assert_eq!(tls.trusted_ca_group.as_deref(), Some("tcg1"));
        assert_eq!(tls.ca_profiles, ["ca1", "ca2"]);
    }

    #[test]
    fn extracts_grpc_replay() {
        let replay = system(&juniper::parse_braces(
            "system {\n    syslog {\n        grpc-replay last 10 facility daemon priority error;\n    }\n}\n",
        ))
        .unwrap()
        .syslog
        .unwrap()
        .grpc_replay
        .unwrap();
        assert_eq!(replay.last_minutes.as_deref(), Some("10"));
        assert_eq!(replay.facility.as_deref(), Some("daemon"));
        assert_eq!(replay.priority.as_deref(), Some("error"));
    }

    #[test]
    fn extracts_console_application_status_and_server_settings() {
        let syslog = system(&juniper::parse_braces(
            r#"
system {
    syslog {
        routing-instance mgmt_junos;
        console {
            any critical;
            application-status error;
        }
        server {
            routing-instances all {
                disable;
            }
            routing-instances blue;
        }
    }
}
"#,
        ))
        .unwrap()
        .syslog
        .unwrap();
        assert_eq!(syslog.routing_instance.as_deref(), Some("mgmt_junos"));
        assert_eq!(syslog.console_application_status.as_deref(), Some("error"));
        // `application-status` is not a facility.
        assert_eq!(syslog.console.len(), 1);
        assert_eq!(syslog.server_disabled_routing_instances, ["all"]);
    }

    #[test]
    fn extracts_match_strings_and_transport() {
        let syslog = system(&juniper::parse_braces(
            r#"
system {
    syslog {
        host 192.0.2.5 {
            any notice;
            transport tls;
            match-strings [ UI_COMMIT SNMP_TRAP ];
        }
        file messages {
            any notice;
            match-strings LINK_DOWN;
        }
    }
}
"#,
        ))
        .unwrap()
        .syslog
        .unwrap();
        assert_eq!(syslog.hosts[0].transport.as_deref(), Some("tls"));
        assert_eq!(syslog.hosts[0].match_strings, ["UI_COMMIT", "SNMP_TRAP"]);
        assert_eq!(syslog.files[0].match_strings, ["LINK_DOWN"]);
        assert_eq!(syslog.files[0].match_regex, None);
    }

    #[test]
    fn syslog_destination_options_default_to_off() {
        let syslog = system(&juniper::parse_braces(
            "system {\n    syslog {\n        host 192.0.2.5 {\n            any notice;\n        }\n    }\n}\n",
        ))
        .unwrap()
        .syslog
        .unwrap();
        assert!(!syslog.allow_duplicates);
        assert_eq!(syslog.log_rotate_frequency, None);
        assert!(!syslog.hosts[0].explicit_priority);
        assert_eq!(syslog.hosts[0].match_regex, None);
    }

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