Skip to main content

asterust_junos/system/
extensions.rs

1//! `extensions`
2//! `system { extensions { ... } }`.
3//!
4//! # See also
5//!
6//! - [extensions](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/extensions-edit-system.html)
7//! - [source (JET Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/source-edit-system-extensions.html)
8//! - [routing-instance (JET Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/routing-instance-edit-system-extensions.html)
9//! - [traceoptions (Extensions)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/traceoptions-edit-system-extensions-jet.html)
10//! - [start (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/start-edit-system-scripts.html)
11//! - [checksum (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/checksum-edit-system-scripts.html)
12//! - [cert-file (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/cert-file-edit-system-scripts.html)
13//!
14//! `refresh` and `refresh-from` are not read: setting them runs an operation and does not add a
15//! statement to the configuration.
16
17use super::scripts::{checksum, start_mem_factor};
18use crate::protocols::traceoptions::{parse_traceoptions, Traceoptions};
19use crate::{active_children, arg_of, args_of, child_block, has_leaf, list_values, named_children, split_name};
20use asterust::config::ConfigLine;
21
22/// A `file <name>` of `extension-service application`.
23#[derive(Clone, Debug, PartialEq, Eq)]
24#[non_exhaustive]
25pub struct ExtensionApplication {
26    pub name: String,
27    pub arguments: Option<String>,
28    pub daemonize: bool,
29    /// `bash`, `python` or `python3`.
30    pub interpreter: Option<String>,
31    pub optional: bool,
32    pub routing_instance: Option<String>,
33    pub username: Option<String>,
34    pub respawn_on_normal_exit: bool,
35    /// The URL the file is refreshed from.
36    pub source: Option<String>,
37    /// `md5`, `sha-256` or `sha1`, from `checksum`.
38    pub checksum_algorithm: Option<String>,
39    pub checksum: Option<String>,
40    /// The certificate used to validate the server when refreshing from HTTPS.
41    pub cert_file: Option<String>,
42    /// Percentage, from `start { start-options { mem-factor } }`.
43    pub start_mem_factor: Option<String>,
44    pub traceoptions: Option<Traceoptions>,
45}
46
47/// A `license-type <license> deployment-scope [ ... ]` line of a provider.
48#[derive(Clone, Debug, PartialEq, Eq)]
49#[non_exhaustive]
50pub struct ProviderLicense {
51    pub license_type: String,
52    pub deployment_scopes: Vec<String>,
53}
54
55/// A provider under `extensions providers`.
56#[derive(Clone, Debug, PartialEq, Eq)]
57#[non_exhaustive]
58pub struct ExtensionProvider {
59    pub id: String,
60    pub licenses: Vec<ProviderLicense>,
61}
62
63/// The `system extensions` configuration.
64#[derive(Clone, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct Extensions {
67    /// Files from `extension-service { application { file ... } }`.
68    pub applications: Vec<ExtensionApplication>,
69    pub max_datasize: Option<String>,
70    /// Percentage, from the application-level `start { start-options { mem-factor } }`.
71    pub start_mem_factor: Option<String>,
72    /// The application-level `traceoptions`.
73    pub traceoptions: Option<Traceoptions>,
74    pub providers: Vec<ExtensionProvider>,
75}
76
77pub(super) fn parse_extensions(extensions: &ConfigLine) -> Extensions {
78    let application =
79        child_block(extensions, "extension-service").and_then(|service| child_block(service, "application"));
80    Extensions {
81        applications: application
82            .map(|application| {
83                named_children(application, "file")
84                    .map(|(name, file)| {
85                        let (checksum_algorithm, checksum) = checksum(file);
86                        ExtensionApplication {
87                            name: name.to_string(),
88                            arguments: arg_of(file, "arguments").map(str::to_string),
89                            daemonize: has_leaf(file, "daemonize"),
90                            interpreter: arg_of(file, "interpreter").map(str::to_string),
91                            optional: has_leaf(file, "optional"),
92                            routing_instance: arg_of(file, "routing-instance").map(str::to_string),
93                            username: arg_of(file, "username").map(str::to_string),
94                            respawn_on_normal_exit: has_leaf(file, "respawn-on-normal-exit"),
95                            source: arg_of(file, "source").map(str::to_string),
96                            checksum_algorithm,
97                            checksum,
98                            cert_file: arg_of(file, "cert-file").map(str::to_string),
99                            start_mem_factor: start_mem_factor(file),
100                            traceoptions: parse_traceoptions(file),
101                        }
102                    })
103                    .collect()
104            })
105            .unwrap_or_default(),
106        max_datasize: application
107            .and_then(|application| arg_of(application, "max-datasize"))
108            .map(str::to_string),
109        start_mem_factor: application.and_then(start_mem_factor),
110        traceoptions: application.and_then(parse_traceoptions),
111        providers: child_block(extensions, "providers")
112            .map(|providers| {
113                active_children(providers)
114                    .map(|provider| ExtensionProvider {
115                        id: provider.text.clone(),
116                        licenses: args_of(provider, "license-type")
117                            .into_iter()
118                            .map(|arg| {
119                                let (license_type, rest) = split_name(arg);
120                                ProviderLicense {
121                                    license_type: license_type.to_string(),
122                                    deployment_scopes: rest
123                                        .strip_prefix("deployment-scope")
124                                        .map(list_values)
125                                        .unwrap_or_default(),
126                                }
127                            })
128                            .collect(),
129                    })
130                    .collect()
131            })
132            .unwrap_or_default(),
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use crate::system::system;
139    use asterust::config::juniper;
140
141    // Not from documentation: written from the CLI Reference syntax page. See the README "Sources".
142    const EXTENSIONS: &str = r#"
143system {
144    extensions {
145        extension-service {
146            application {
147                file monitor.py {
148                    arguments "--verbose";
149                    daemonize;
150                    interpreter python3;
151                    optional;
152                    routing-instance mgmt_junos;
153                    username jet;
154                    checksum sha-256 abc123;
155                }
156                file plain.sh;
157                max-datasize 64m;
158            }
159        }
160        providers {
161            ISV1 {
162                license-type juniper deployment-scope [ commercial ];
163                license-type customer deployment-scope [ poc commercial ];
164            }
165        }
166    }
167}
168"#;
169
170    #[test]
171    fn extracts_extension_applications() {
172        let extensions = system(&juniper::parse_braces(EXTENSIONS)).unwrap().extensions.unwrap();
173        assert_eq!(extensions.max_datasize.as_deref(), Some("64m"));
174        let names: Vec<_> = extensions.applications.iter().map(|a| a.name.as_str()).collect();
175        assert_eq!(names, ["monitor.py", "plain.sh"]);
176
177        let monitor = &extensions.applications[0];
178        assert_eq!(monitor.arguments.as_deref(), Some("--verbose"));
179        assert!(monitor.daemonize);
180        assert!(monitor.optional);
181        assert_eq!(monitor.interpreter.as_deref(), Some("python3"));
182        assert_eq!(monitor.routing_instance.as_deref(), Some("mgmt_junos"));
183        assert_eq!(monitor.username.as_deref(), Some("jet"));
184
185        let plain = &extensions.applications[1];
186        assert!(!plain.daemonize);
187        assert_eq!(plain.interpreter, None);
188    }
189
190    #[test]
191    fn extracts_extension_providers() {
192        let extensions = system(&juniper::parse_braces(EXTENSIONS)).unwrap().extensions.unwrap();
193        assert_eq!(extensions.providers.len(), 1);
194        let provider = &extensions.providers[0];
195        assert_eq!(provider.id, "ISV1");
196        assert_eq!(provider.licenses.len(), 2);
197        assert_eq!(provider.licenses[0].license_type, "juniper");
198        assert_eq!(provider.licenses[0].deployment_scopes, ["commercial"]);
199        assert_eq!(provider.licenses[1].deployment_scopes, ["poc", "commercial"]);
200    }
201
202    #[test]
203    fn extracts_application_sources_and_tracing() {
204        let extensions = system(&juniper::parse_braces(
205            r#"
206system {
207    extensions {
208        extension-service {
209            application {
210                start {
211                    start-options {
212                        mem-factor 40;
213                    }
214                }
215                traceoptions {
216                    file jet.log;
217                    flag all;
218                }
219                file monitor.py {
220                    respawn-on-normal-exit;
221                    source https://jet.example.net/monitor.py;
222                    checksum sha-256 abc123;
223                    cert-file /var/db/certs/ca.pem;
224                    start {
225                        start-options {
226                            mem-factor 60;
227                        }
228                    }
229                    traceoptions {
230                        file monitor.log;
231                        flag init;
232                    }
233                }
234            }
235        }
236    }
237}
238"#,
239        ))
240        .unwrap()
241        .extensions
242        .unwrap();
243        assert_eq!(extensions.start_mem_factor.as_deref(), Some("40"));
244        assert_eq!(extensions.traceoptions.unwrap().file.as_deref(), Some("jet.log"));
245        let monitor = &extensions.applications[0];
246        assert!(monitor.respawn_on_normal_exit);
247        assert_eq!(monitor.source.as_deref(), Some("https://jet.example.net/monitor.py"));
248        assert_eq!(monitor.checksum_algorithm.as_deref(), Some("sha-256"));
249        assert_eq!(monitor.checksum.as_deref(), Some("abc123"));
250        assert_eq!(monitor.cert_file.as_deref(), Some("/var/db/certs/ca.pem"));
251        assert_eq!(monitor.start_mem_factor.as_deref(), Some("60"));
252        assert_eq!(
253            monitor.traceoptions.as_ref().unwrap().file.as_deref(),
254            Some("monitor.log")
255        );
256    }
257
258    #[test]
259    fn extensions_with_only_providers() {
260        let extensions = system(&juniper::parse_braces(
261            "system {\n    extensions {\n        providers {\n            ISV2;\n        }\n    }\n}\n",
262        ))
263        .unwrap()
264        .extensions
265        .unwrap();
266        assert!(extensions.applications.is_empty());
267        assert_eq!(extensions.max_datasize, None);
268        assert_eq!(extensions.providers[0].id, "ISV2");
269        assert!(extensions.providers[0].licenses.is_empty());
270    }
271
272    #[test]
273    fn no_extensions_is_none() {
274        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
275        assert!(system.extensions.is_none());
276    }
277}