asterust-junos 0.4.2

Typed Juniper JunOS config views (interfaces, OSPF, BGP, IS-IS, routing instances, policy options, firewall filters, system) extracted from an asterust config tree.
Documentation
//! `shared-buffer`, `dedicated-buffer`, `dedicated-buffer-profile` and `dynamic-threshold-profile`
//! `class-of-service { shared-buffer { ingress { ... } egress { ... } } dynamic-threshold-profile <name> { ... } }`.
//!
//! # See also
//!
//! - [shared-buffer](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/shared-buffer-edit-class-of-service-qfx-series.html)
//! - [buffer-partition](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/buffer-partition-edit-class-of-service-egress-qfx-series.html)
//! - [Configuring Ingress and Egress Dedicated Buffers](https://networkingdocs.hpe.com/documentation/us/en/software/junos/traffic-mgmt-qfx/topics/topic-map/cos-dedicated-buffer-configuring.html)
//! - [Configuring Global Ingress and Egress Shared Buffers](https://networkingdocs.hpe.com/documentation/us/en/software/junos/traffic-mgmt-qfx/topics/task/cos-shared-buffer-global-qfx-series-cli.html)
//! - [Dynamic Threshold Profiles for Shared Buffer Pools](https://networkingdocs.hpe.com/documentation/us/en/software/junos/traffic-mgmt-qfx/topics/topic-map/dynamic-threshold-profiles-for-shared-buffer-pools.html)
//! - [dynamic-threshold-profile](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/dynamic-threshold-profile-edit-class-of-service.html)

use super::words;
use crate::{active_children, arg_of, child_block, named_children, value_after};
use asterust::config::ConfigLine;

/// A `buffer-partition <kind>` entry of a shared buffer.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct BufferPartition {
    /// `lossless`, `lossless-headroom`, `lossy` or `multicast`.
    pub kind: String,
    pub percent: Option<String>,
    pub dynamic_threshold: Option<String>,
}

/// The `ingress` or `egress` block of `shared-buffer`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct SharedBufferDirection {
    pub percent: Option<String>,
    pub partitions: Vec<BufferPartition>,
}

/// The `shared-buffer` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct SharedBuffer {
    pub ingress: Option<SharedBufferDirection>,
    pub egress: Option<SharedBufferDirection>,
}

/// The `dedicated-buffer` block: the share of the buffer that is dedicated rather than shared.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct DedicatedBuffer {
    pub ingress_percent: Option<String>,
    pub egress_percent: Option<String>,
}

/// A `dedicated-buffer-profile` entry.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DedicatedBufferProfile {
    pub name: String,
    /// `none` or a size in cells.
    pub ingress_buffer_size: Option<String>,
    pub egress_buffer_size: Option<String>,
}

/// A `priority-group` or `priority-group-all` entry of a dynamic threshold profile.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PriorityGroupThreshold {
    /// `None` for `priority-group-all`.
    pub priority_group: Option<String>,
    pub dynamic_threshold: Option<String>,
}

/// A `dynamic-threshold-profile` entry.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DynamicThresholdProfile {
    pub name: String,
    pub ingress: Vec<PriorityGroupThreshold>,
}

fn parse_direction(block: &ConfigLine) -> SharedBufferDirection {
    SharedBufferDirection {
        percent: arg_of(block, "percent").map(str::to_string),
        partitions: named_children(block, "buffer-partition")
            .map(|(kind, partition)| BufferPartition {
                kind: kind.to_string(),
                percent: arg_of(partition, "percent").map(str::to_string),
                dynamic_threshold: arg_of(partition, "dynamic-threshold").map(str::to_string),
            })
            .collect(),
    }
}

pub(super) fn parse_shared_buffer(cos: &ConfigLine) -> Option<SharedBuffer> {
    let buffer = child_block(cos, "shared-buffer")?;
    Some(SharedBuffer {
        ingress: child_block(buffer, "ingress").map(parse_direction),
        egress: child_block(buffer, "egress").map(parse_direction),
    })
}

pub(super) fn parse_dedicated_buffer(cos: &ConfigLine) -> Option<DedicatedBuffer> {
    let buffer = child_block(cos, "dedicated-buffer")?;
    let percent = |direction: &str| {
        child_block(buffer, direction)
            .and_then(|block| arg_of(block, "percent"))
            .map(str::to_string)
    };
    Some(DedicatedBuffer {
        ingress_percent: percent("ingress"),
        egress_percent: percent("egress"),
    })
}

pub(super) fn parse_dedicated_buffer_profiles(cos: &ConfigLine) -> Vec<DedicatedBufferProfile> {
    named_children(cos, "dedicated-buffer-profile")
        .map(|(name, profile)| {
            let size = |direction: &str| {
                child_block(profile, direction)
                    .and_then(|block| arg_of(block, "buffer-size"))
                    .map(str::to_string)
            };
            DedicatedBufferProfile {
                name: name.to_string(),
                ingress_buffer_size: size("ingress"),
                egress_buffer_size: size("egress"),
            }
        })
        .collect()
}

pub(super) fn parse_dynamic_threshold_profiles(cos: &ConfigLine) -> Vec<DynamicThresholdProfile> {
    named_children(cos, "dynamic-threshold-profile")
        .map(|(name, profile)| DynamicThresholdProfile {
            name: name.to_string(),
            ingress: child_block(profile, "ingress")
                .map(|ingress| {
                    active_children(ingress)
                        .filter_map(|group| {
                            let words = words(group, 0);
                            let (keyword, rest) = (words.first()?, &words[1..]);
                            let priority_group = match *keyword {
                                "priority-group" => Some(rest.first()?.to_string()),
                                "priority-group-all" => None,
                                _ => return None,
                            };
                            Some(PriorityGroupThreshold {
                                priority_group,
                                dynamic_threshold: value_after(rest, "dynamic-threshold"),
                            })
                        })
                        .collect()
                })
                .unwrap_or_default(),
        })
        .collect()
}

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

    // Not from documentation: written from the CLI Reference. See the README "Sources".
    const EXTRA: &str = r#"
class-of-service {
    shared-buffer {
        ingress {
            percent 100;
            buffer-partition lossless {
                percent 50;
                dynamic-threshold 7;
            }
            buffer-partition lossless-headroom {
                percent 10;
            }
        }
        egress {
            percent 90;
            buffer-partition multicast {
                percent 20;
            }
        }
    }
    dynamic-threshold-profile DT1 {
        ingress {
            priority-group 3 dynamic-threshold 5;
            priority-group-all dynamic-threshold 7;
        }
    }
    dynamic-threshold-profile DT2;
}
"#;

    #[test]
    fn reads_the_shared_buffer() {
        let buffer = class_of_service(&juniper::parse_braces(EXTRA))
            .unwrap()
            .shared_buffer
            .unwrap();
        let ingress = buffer.ingress.unwrap();
        assert_eq!(ingress.percent.as_deref(), Some("100"));
        assert_eq!(ingress.partitions.len(), 2);
        assert_eq!(ingress.partitions[0].kind, "lossless");
        assert_eq!(ingress.partitions[0].percent.as_deref(), Some("50"));
        assert_eq!(ingress.partitions[0].dynamic_threshold.as_deref(), Some("7"));
        assert_eq!(ingress.partitions[1].dynamic_threshold, None);
        let egress = buffer.egress.unwrap();
        assert_eq!(egress.percent.as_deref(), Some("90"));
        assert_eq!(egress.partitions[0].kind, "multicast");
    }

    #[test]
    fn reads_the_dynamic_threshold_profiles() {
        let profiles = class_of_service(&juniper::parse_braces(EXTRA))
            .unwrap()
            .dynamic_threshold_profiles;
        assert_eq!(profiles.len(), 2);
        assert_eq!(profiles[0].name, "DT1");
        assert_eq!(profiles[0].ingress[0].priority_group.as_deref(), Some("3"));
        assert_eq!(profiles[0].ingress[0].dynamic_threshold.as_deref(), Some("5"));
        assert_eq!(profiles[0].ingress[1].priority_group, None);
        assert_eq!(profiles[0].ingress[1].dynamic_threshold.as_deref(), Some("7"));
        assert!(profiles[1].ingress.is_empty());
    }

    // The `class-of-service` statements of Configuring Ingress and Egress Dedicated Buffers, Dynamic Threshold Profiles
    // for Shared Buffer Pools and Example: Recommended Configuration of the Shared Buffer Pool for Networks with Mostly
    // Lossless Traffic (Traffic Management User Guide for QFX Series Switches and EX4600 Switches), the last two
    // written in brace form; see the README "Sources".
    const DOC_DEDICATED: &str = r#"
class-of-service {
    dedicated-buffer {
        ingress {
            percent 25;
        }
        egress {
            percent 20;
        }
    }
}
"#;

    const DOC_DYNAMIC_THRESHOLD: &str = r#"
class-of-service {
    dynamic-threshold-profile DT1 {
        ingress {
            priority-group 0 dynamic-threshold 5;
            priority-group 1 dynamic-threshold 6;
            priority-group 5 dynamic-threshold 10;
            priority-group 7 dynamic-threshold 10;
        }
    }
    interfaces {
        et-0/0/0 {
            dynamic-threshold-profile DT1;
        }
    }
}
"#;

    const DOC_LOSSLESS_BUFFER: &str = r#"
class-of-service {
    shared-buffer {
        ingress {
            percent 100;
            buffer-partition lossless {
                percent 15;
            }
            buffer-partition lossless-headroom {
                percent 80;
            }
            buffer-partition lossy {
                percent 5;
            }
        }
        egress {
            percent 100;
            buffer-partition lossless {
                percent 90;
            }
            buffer-partition lossy {
                percent 5;
            }
            buffer-partition multicast {
                percent 5;
            }
        }
    }
}
"#;

    #[test]
    fn reads_the_guide_dedicated_buffer() {
        let buffer = class_of_service(&juniper::parse_braces(DOC_DEDICATED))
            .unwrap()
            .dedicated_buffer
            .unwrap();
        assert_eq!(buffer.ingress_percent.as_deref(), Some("25"));
        assert_eq!(buffer.egress_percent.as_deref(), Some("20"));
    }

    #[test]
    fn reads_the_guide_dynamic_threshold_profile() {
        let cos = class_of_service(&juniper::parse_braces(DOC_DYNAMIC_THRESHOLD)).unwrap();
        let profile = &cos.dynamic_threshold_profiles[0];
        assert_eq!(profile.name, "DT1");
        assert_eq!(profile.ingress.len(), 4);
        assert_eq!(profile.ingress[2].priority_group.as_deref(), Some("5"));
        assert_eq!(profile.ingress[2].dynamic_threshold.as_deref(), Some("10"));
        assert_eq!(
            cos.interfaces[0].settings.dynamic_threshold_profile.as_deref(),
            Some("DT1")
        );
    }

    #[test]
    fn reads_the_guide_lossless_shared_buffer() {
        let buffer = class_of_service(&juniper::parse_braces(DOC_LOSSLESS_BUFFER))
            .unwrap()
            .shared_buffer
            .unwrap();
        let ingress = buffer.ingress.unwrap();
        assert_eq!(ingress.percent.as_deref(), Some("100"));
        assert_eq!(ingress.partitions.len(), 3);
        assert_eq!(ingress.partitions[1].kind, "lossless-headroom");
        assert_eq!(ingress.partitions[1].percent.as_deref(), Some("80"));
        let egress = buffer.egress.unwrap();
        assert_eq!(egress.partitions[0].percent.as_deref(), Some("90"));
        assert_eq!(egress.partitions[2].kind, "multicast");
    }

    // Not from documentation: written from the CLI Reference and the `set` statements of the guide. See the README
    // "Sources".
    #[test]
    fn reads_the_dedicated_buffer_profiles() {
        let cos = class_of_service(&juniper::parse_braces(
            "class-of-service {\n    dedicated-buffer-profile DBP1 {\n        ingress {\n            buffer-size 1000;\n        }\n        egress {\n            buffer-size none;\n        }\n    }\n    dedicated-buffer-profile DBP2;\n    interfaces {\n        xe-0/0/1 {\n            dedicated-buffer-profile DBP1;\n        }\n    }\n}\n",
        ))
        .unwrap();
        assert_eq!(cos.dedicated_buffer_profiles.len(), 2);
        assert_eq!(
            cos.dedicated_buffer_profiles[0].ingress_buffer_size.as_deref(),
            Some("1000")
        );
        assert_eq!(
            cos.dedicated_buffer_profiles[0].egress_buffer_size.as_deref(),
            Some("none")
        );
        assert_eq!(cos.dedicated_buffer_profiles[1].ingress_buffer_size, None);
        assert_eq!(
            cos.interfaces[0].settings.dedicated_buffer_profile.as_deref(),
            Some("DBP1")
        );
    }
}