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
//! `dhcp`
//! `system { services { dhcp { ... } } }`.
//!
//! The DHCP server of EX Series switches and J Series Services Routers. Its pools and static bindings take
//! most of the same settings as the server.
//!
//! # See also
//!
//! - [dhcp](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/dhcp-edit-system.html)
//! - [pool (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/pool-edit-system.html)
//! - [static-binding](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/static-binding-edit-system.html)
//! - [boot-server (DHCP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/boot-server-edit-system-services.html)
//! - [domain-name (DHCP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/domain-name-edit-system-services-dhcp.html)
//! - [domain-search](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/domain-search-edit-system.html)
//! - [maximum-lease-time (DHCP)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/maximum-lease-time-edit-system.html)
//! - [next-server](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/next-server-edit-system.html)
//! - [option (DHCP server)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/dhcp-user-option.html)
//! - [propagate-settings](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/system-edit-propagate-settings.html)
//! - [server-identifier](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/server-identifier-edit-system.html)
//! - [sip-server](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/sip-server-edit-system.html)
//! - [wins-server (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/wins-server-edit-system.html)

use crate::{active_children, arg_of, args_of, child_block, list_values, named_children};
use asterust::config::ConfigLine;

/// The settings shared by the DHCP server, its pools and its static bindings.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct DhcpServerSettings {
    pub boot_file: Option<String>,
    /// An address or a hostname.
    pub boot_server: Option<String>,
    /// Seconds.
    pub default_lease_time: Option<String>,
    pub domain_name: Option<String>,
    pub domain_search: Vec<String>,
    /// Seconds.
    pub maximum_lease_time: Option<String>,
    pub name_servers: Vec<String>,
    pub next_server: Option<String>,
    /// The lines of `option { ... }`, as written, e.g. `"15 string example.net"`.
    pub options: Vec<String>,
    pub propagate_settings: Option<String>,
    pub routers: Vec<String>,
    pub server_identifier: Option<String>,
    /// Addresses or names.
    pub sip_servers: Vec<String>,
    pub wins_servers: Vec<String>,
}

/// A `pool <address>/<prefix-length>`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DhcpPool {
    pub address: String,
    pub address_range_low: Option<String>,
    pub address_range_high: Option<String>,
    pub exclude_addresses: Vec<String>,
    pub settings: DhcpServerSettings,
}

/// A `static-binding <mac-address>`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DhcpStaticBinding {
    pub mac_address: String,
    pub fixed_addresses: Vec<String>,
    pub host_name: Option<String>,
    /// `ascii <id>` or `hexadecimal <id>`, as written.
    pub client_identifier: Option<String>,
    pub settings: DhcpServerSettings,
}

/// The `system services dhcp` server.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DhcpServer {
    pub settings: DhcpServerSettings,
    pub pools: Vec<DhcpPool>,
    pub static_bindings: Vec<DhcpStaticBinding>,
}

/// Addresses written inline, in a list, or as `<keyword> { <address>; ... }`.
fn addresses(block: &ConfigLine, keyword: &str) -> Vec<String> {
    let mut found: Vec<String> = args_of(block, keyword).into_iter().flat_map(list_values).collect();
    if let Some(list) = child_block(block, keyword) {
        found.extend(active_children(list).map(|address| address.text.clone()));
    }
    found
}

fn parse_settings(block: &ConfigLine) -> DhcpServerSettings {
    let field = |keyword: &str| arg_of(block, keyword).map(str::to_string);
    DhcpServerSettings {
        boot_file: field("boot-file"),
        boot_server: field("boot-server"),
        default_lease_time: field("default-lease-time"),
        domain_name: field("domain-name"),
        domain_search: args_of(block, "domain-search")
            .into_iter()
            .flat_map(list_values)
            .collect(),
        maximum_lease_time: field("maximum-lease-time"),
        name_servers: addresses(block, "name-server"),
        next_server: field("next-server"),
        options: child_block(block, "option")
            .map(|options| {
                active_children(options)
                    .map(|o| o.text.trim_matches('"').to_string())
                    .collect()
            })
            .unwrap_or_default(),
        propagate_settings: field("propagate-settings"),
        routers: addresses(block, "router"),
        server_identifier: field("server-identifier"),
        sip_servers: args_of(block, "sip-server").into_iter().flat_map(list_values).collect(),
        wins_servers: addresses(block, "wins-server"),
    }
}

pub(super) fn parse_dhcp_server(dhcp: &ConfigLine) -> DhcpServer {
    DhcpServer {
        settings: parse_settings(dhcp),
        pools: named_children(dhcp, "pool")
            .map(|(address, pool)| {
                let range = child_block(pool, "address-range");
                DhcpPool {
                    address: address.to_string(),
                    address_range_low: range.and_then(|r| arg_of(r, "low")).map(str::to_string),
                    address_range_high: range.and_then(|r| arg_of(r, "high")).map(str::to_string),
                    exclude_addresses: addresses(pool, "exclude-address"),
                    settings: parse_settings(pool),
                }
            })
            .collect(),
        static_bindings: named_children(dhcp, "static-binding")
            .map(|(mac, binding)| DhcpStaticBinding {
                mac_address: mac.to_string(),
                fixed_addresses: addresses(binding, "fixed-address"),
                host_name: arg_of(binding, "host-name").map(str::to_string),
                client_identifier: arg_of(binding, "client-identifier").map(str::to_string),
                settings: parse_settings(binding),
            })
            .collect(),
    }
}

#[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_dhcp_server_pools_and_static_bindings() {
        let dhcp = system(&juniper::parse_braces(
            r#"
system {
    services {
        dhcp {
            boot-file pxelinux.0;
            boot-server 192.0.2.8;
            default-lease-time 3600;
            domain-name lab.example.net;
            domain-search [ lab.example.net example.net ];
            maximum-lease-time 7200;
            name-server {
                192.0.2.53;
                192.0.2.54;
            }
            next-server 192.0.2.9;
            option {
                15 string lab.example.net;
            }
            pool 10.0.0.0/24 {
                address-range {
                    low 10.0.0.10;
                    high 10.0.0.200;
                }
                exclude-address {
                    10.0.0.50;
                }
                router {
                    10.0.0.1;
                }
                wins-server {
                    10.0.0.2;
                }
                propagate-settings ge-0/0/0.0;
            }
            static-binding 00:11:22:33:44:55 {
                fixed-address {
                    10.0.0.60;
                }
                host-name printer1;
                client-identifier ascii printer1;
                server-identifier 192.0.2.1;
                sip-server [ sip.example.net ];
            }
        }
    }
}
"#,
        ))
        .unwrap()
        .services
        .unwrap()
        .dhcp
        .unwrap();
        let settings = &dhcp.settings;
        assert_eq!(settings.boot_file.as_deref(), Some("pxelinux.0"));
        assert_eq!(settings.boot_server.as_deref(), Some("192.0.2.8"));
        assert_eq!(settings.default_lease_time.as_deref(), Some("3600"));
        assert_eq!(settings.domain_name.as_deref(), Some("lab.example.net"));
        assert_eq!(settings.domain_search, ["lab.example.net", "example.net"]);
        assert_eq!(settings.maximum_lease_time.as_deref(), Some("7200"));
        assert_eq!(settings.name_servers, ["192.0.2.53", "192.0.2.54"]);
        assert_eq!(settings.next_server.as_deref(), Some("192.0.2.9"));
        assert_eq!(settings.options, ["15 string lab.example.net"]);

        let pool = &dhcp.pools[0];
        assert_eq!(pool.address, "10.0.0.0/24");
        assert_eq!(pool.address_range_low.as_deref(), Some("10.0.0.10"));
        assert_eq!(pool.address_range_high.as_deref(), Some("10.0.0.200"));
        assert_eq!(pool.exclude_addresses, ["10.0.0.50"]);
        assert_eq!(pool.settings.routers, ["10.0.0.1"]);
        assert_eq!(pool.settings.wins_servers, ["10.0.0.2"]);
        assert_eq!(pool.settings.propagate_settings.as_deref(), Some("ge-0/0/0.0"));

        let binding = &dhcp.static_bindings[0];
        assert_eq!(binding.mac_address, "00:11:22:33:44:55");
        assert_eq!(binding.fixed_addresses, ["10.0.0.60"]);
        assert_eq!(binding.host_name.as_deref(), Some("printer1"));
        assert_eq!(binding.client_identifier.as_deref(), Some("ascii printer1"));
        assert_eq!(binding.settings.server_identifier.as_deref(), Some("192.0.2.1"));
        assert_eq!(binding.settings.sip_servers, ["sip.example.net"]);
    }

    #[test]
    fn no_dhcp_server_is_none() {
        let services = system(&juniper::parse_braces(
            "system {\n    services {\n        telnet;\n    }\n}\n",
        ))
        .unwrap()
        .services
        .unwrap();
        assert!(services.dhcp.is_none());
    }
}