Skip to main content

asterust_junos/policy_options/policy_statement/
term.rs

1//! `term`
2//! `policy-options { policy-statement <name> { term <name> { from { ... } to { ... } then { ... } } } }`.
3//!
4//! A policy written without `term` statements is a single unnamed term. Each term carries `from`,
5//! `to` and `then` statements.
6//!
7//! # See also
8//!
9//! - [policy-statement](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/policy-statement-edit-policy-options.html)
10//! - [load-balance (ecmp)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/load-balance-edit-policy-options-policy-statement-then.html)
11//! - [route-filter](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/route-filter-edit-policy-options.html)
12
13use crate::{list_values, split_keyword, split_name, statements, unquote};
14use asterust::config::ConfigLine;
15
16/// A `route-filter <prefix> <match-type>` condition.
17#[derive(Clone, Debug, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct RouteFilter {
20    pub prefix: String,
21    /// Everything after the prefix, e.g. `"exact"`, `"orlonger"`, `"upto /24"`.
22    pub match_type: Option<String>,
23}
24
25/// The match conditions of a term's `from` or `to` statement. Conditions not listed here are
26/// ignored.
27#[derive(Clone, Debug, Default, PartialEq, Eq)]
28#[non_exhaustive]
29pub struct PolicyConditions {
30    pub protocols: Vec<String>,
31    pub families: Vec<String>,
32    pub communities: Vec<String>,
33    pub as_paths: Vec<String>,
34    pub prefix_lists: Vec<String>,
35    /// The raw `prefix-list-filter` argument, e.g. `"CUSTOMERS orlonger"`.
36    pub prefix_list_filters: Vec<String>,
37    pub route_filters: Vec<RouteFilter>,
38    pub neighbors: Vec<String>,
39    /// Subroutine policies from `policy`.
40    pub policies: Vec<String>,
41}
42
43/// The flow-control action ending a term.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum PolicyAction {
47    Accept,
48    Reject,
49    NextTerm,
50    NextPolicy,
51}
52
53/// How a `then community` action changes the route's communities.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum CommunityOperation {
57    Add,
58    Set,
59    Delete,
60}
61
62/// A `then community (add | set | delete) <name>` action.
63#[derive(Clone, Debug, PartialEq, Eq)]
64#[non_exhaustive]
65pub struct CommunityAction {
66    pub operation: CommunityOperation,
67    pub community: String,
68}
69
70/// A `then srv6 locator <name> <sid>` action, which selects the SRv6 service SID that BGP advertises for the route.
71#[derive(Clone, Debug, PartialEq, Eq)]
72#[non_exhaustive]
73pub struct PolicySrv6Action {
74    pub locator: String,
75    /// `end-dt4-sid`, `micro-dt46-sid` and the like.
76    pub sid_type: Option<String>,
77    /// The static SID value, if given.
78    pub sid_value: Option<String>,
79}
80
81/// The actions of a term's `then` statement. Actions not listed here are ignored.
82#[derive(Clone, Debug, Default, PartialEq, Eq)]
83#[non_exhaustive]
84pub struct PolicyActions {
85    pub action: Option<PolicyAction>,
86    /// Everything after `metric`, e.g. `"63"` or `"add 10"`.
87    pub metric: Option<String>,
88    pub local_preference: Option<String>,
89    pub next_hop: Option<String>,
90    pub as_path_prepend: Option<String>,
91    pub communities: Vec<CommunityAction>,
92    /// Everything after `load-balance`, e.g. `"per-packet"`. A `load-balance { ...; }` block is not read.
93    pub load_balance: Option<String>,
94    /// The `resolution-map` to apply, which is defined under `policy-options`.
95    pub resolution_map: Option<String>,
96    pub multipath_resolve: bool,
97    pub srv6: Option<PolicySrv6Action>,
98}
99
100/// One term of a policy statement.
101#[derive(Clone, Debug, PartialEq, Eq)]
102#[non_exhaustive]
103pub struct PolicyTerm {
104    /// `None` for the unnamed term, which is the only one in a policy written without `term`
105    /// statements.
106    pub name: Option<String>,
107    pub from: PolicyConditions,
108    pub to: PolicyConditions,
109    pub then: PolicyActions,
110}
111
112pub(super) fn parse_term(name: Option<&str>, line: &ConfigLine) -> PolicyTerm {
113    PolicyTerm {
114        name: name.map(str::to_string),
115        from: parse_conditions(line, "from"),
116        to: parse_conditions(line, "to"),
117        then: parse_actions(line),
118    }
119}
120
121fn parse_conditions(line: &ConfigLine, keyword: &str) -> PolicyConditions {
122    let mut conditions = PolicyConditions::default();
123    for statement in statements(line, keyword) {
124        let (condition, arg) = split_keyword(statement);
125        match condition {
126            "protocol" => conditions.protocols.extend(list_values(arg)),
127            "family" => conditions.families.push(unquote(arg).to_string()),
128            "community" => conditions.communities.extend(list_values(arg)),
129            "as-path" => conditions.as_paths.extend(list_values(arg)),
130            "prefix-list" => conditions.prefix_lists.extend(list_values(arg)),
131            "prefix-list-filter" => conditions.prefix_list_filters.push(arg.to_string()),
132            "route-filter" => conditions.route_filters.push(parse_route_filter(arg)),
133            "neighbor" => conditions.neighbors.push(unquote(arg).to_string()),
134            "policy" => conditions.policies.push(unquote(arg).to_string()),
135            _ => {}
136        }
137    }
138    conditions
139}
140
141fn parse_route_filter(arg: &str) -> RouteFilter {
142    let (prefix, match_type) = split_keyword(arg);
143    RouteFilter {
144        prefix: prefix.to_string(),
145        match_type: Some(match_type).filter(|m| !m.is_empty()).map(str::to_string),
146    }
147}
148
149fn parse_actions(line: &ConfigLine) -> PolicyActions {
150    let mut actions = PolicyActions::default();
151    for statement in statements(line, "then") {
152        let (action, arg) = split_keyword(statement);
153        let value = || Some(unquote(arg).to_string());
154        match (action, arg) {
155            ("accept", "") => actions.action = Some(PolicyAction::Accept),
156            ("reject", "") => actions.action = Some(PolicyAction::Reject),
157            ("next", "term") => actions.action = Some(PolicyAction::NextTerm),
158            ("next", "policy") => actions.action = Some(PolicyAction::NextPolicy),
159            ("metric", _) => actions.metric = value(),
160            ("local-preference", _) => actions.local_preference = value(),
161            ("next-hop", _) => actions.next_hop = value(),
162            ("as-path-prepend", _) => actions.as_path_prepend = value(),
163            ("community", _) => actions.communities.extend(parse_community_action(arg)),
164            ("load-balance", _) => actions.load_balance = Some(arg.to_string()).filter(|a| !a.is_empty()),
165            ("resolution-map", _) => actions.resolution_map = value(),
166            ("multipath-resolve", "") => actions.multipath_resolve = true,
167            ("srv6", _) => actions.srv6 = parse_srv6_action(arg),
168            _ => {}
169        }
170    }
171    actions
172}
173
174fn parse_srv6_action(arg: &str) -> Option<PolicySrv6Action> {
175    let (locator, sid) = split_name(arg.strip_prefix("locator")?.trim());
176    let (sid_type, sid_value) = split_keyword(sid);
177    Some(PolicySrv6Action {
178        locator: unquote(locator).to_string(),
179        sid_type: Some(sid_type).filter(|t| !t.is_empty()).map(str::to_string),
180        sid_value: Some(sid_value).filter(|v| !v.is_empty()).map(str::to_string),
181    })
182}
183
184fn parse_community_action(arg: &str) -> Option<CommunityAction> {
185    let (operation, community) = split_name(arg);
186    let operation = match operation {
187        "add" => CommunityOperation::Add,
188        "set" => CommunityOperation::Set,
189        "delete" => CommunityOperation::Delete,
190        _ => return None,
191    };
192    Some(CommunityAction {
193        operation,
194        community: unquote(community).to_string(),
195    })
196}