Skip to main content

asterust_junos/system/
scripts.rs

1//! `scripts`
2//! `system { scripts { ... } }`.
3//!
4//! # See also
5//!
6//! - [scripts](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/scripts-edit-system.html)
7//! - [source (Commit Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/source-edit-system-commit.html)
8//! - [source (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/source-edit-system-op.html)
9//! - [source (SNMP Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/source-edit-system-scripts-snmp-file.html)
10//! - [checksum (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/checksum-edit-system-scripts.html)
11//! - [cert-file (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/cert-file-edit-system-scripts.html)
12//! - [routing-instance (System Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/routing-instance-edit-system-scripts.html)
13//! - [start (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/start-edit-system-scripts.html)
14//! - [command (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/command-edit-system-scripts.html)
15//! - [arguments (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/arguments-edit-system.html)
16//! - [allow-commands (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/allow-commands-edit-system-scripts.html)
17//! - [optional (Commit Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/optional-edit-system.html)
18//! - [allow-transients](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/allow-transients-edit-system.html)
19//! - [direct-access (Commit Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/direct-access-edit-system.html)
20//! - [allow-url-for-python (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/allow-url-for-python-edit-system-scripts-op.html)
21//! - [no-allow-url (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-allow-url-edit-system-script-op.html)
22//! - [oid (SNMP Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/oid-edit-system-scripts-snmp-file.html)
23//! - [load-scripts-from-flash (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/load-scripts-from-flash-edit-system-scripts.html)
24//! - [translation](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/translation-edit-system.html)
25//! - [traceoptions (Commit, Op, and SNMP Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/traceoptions-edit-system-scripts.html)
26//!
27//! `refresh` and `refresh-from` are not read: setting them runs an operation and does not add a
28//! statement to the configuration.
29
30use crate::protocols::traceoptions::{parse_traceoptions, Traceoptions};
31use crate::{active_children, arg_of, child_block, has_leaf, named_children, split_keyword, unquote};
32use asterust::config::ConfigLine;
33
34/// An `arguments <name>` entry of an op script file.
35#[derive(Clone, Debug, PartialEq, Eq)]
36#[non_exhaustive]
37pub struct ScriptArgument {
38    pub name: String,
39    pub description: Option<String>,
40}
41
42/// An `oid <id>` entry of an SNMP script file.
43#[derive(Clone, Debug, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct ScriptOid {
46    pub id: String,
47    /// Registration priority, 1 to 255.
48    pub priority: Option<String>,
49}
50
51/// A `file <name>` of the commit, op or SNMP scripts. The options only some kinds have are unset or
52/// empty for the others.
53#[derive(Clone, Debug, PartialEq, Eq)]
54#[non_exhaustive]
55pub struct ScriptFile {
56    pub name: String,
57    /// The URL scripts are refreshed from.
58    pub source: Option<String>,
59    /// `md5`, `sha-256` or `sha1`, from `checksum`.
60    pub checksum_algorithm: Option<String>,
61    pub checksum: Option<String>,
62    /// The certificate used to validate the server when refreshing from HTTPS.
63    pub cert_file: Option<String>,
64    pub routing_instance: Option<String>,
65    /// Percentage, from `start { start-options { mem-factor } }`.
66    pub start_mem_factor: Option<String>,
67    /// Commit scripts only.
68    pub optional: bool,
69    /// Commit scripts only.
70    pub allow_transients: bool,
71    /// Op scripts only: an alias for the file name.
72    pub command: Option<String>,
73    /// Op scripts only.
74    pub description: Option<String>,
75    /// Op scripts only.
76    pub allow_commands: Option<String>,
77    /// Op scripts only.
78    pub arguments: Vec<ScriptArgument>,
79    /// SNMP scripts only.
80    pub python_script_user: Option<String>,
81    /// SNMP scripts only.
82    pub oids: Vec<ScriptOid>,
83}
84
85/// The `commit`, `op` or `snmp` block of `system scripts`. The options only some kinds have are unset
86/// for the others.
87#[derive(Clone, Debug, PartialEq, Eq)]
88#[non_exhaustive]
89pub struct ScriptKind {
90    pub files: Vec<ScriptFile>,
91    pub max_datasize: Option<String>,
92    /// Percentage, from `start { start-options { mem-factor } }`.
93    pub start_mem_factor: Option<String>,
94    pub traceoptions: Option<Traceoptions>,
95    /// Commit scripts only.
96    pub allow_transients: bool,
97    /// Commit scripts only.
98    pub direct_access: bool,
99    /// Op scripts only.
100    pub allow_url_for_python: bool,
101    /// Op scripts only.
102    pub no_allow_url: bool,
103}
104
105/// The `system scripts` configuration.
106#[derive(Clone, Debug, PartialEq, Eq)]
107#[non_exhaustive]
108pub struct Scripts {
109    /// File names from `commit { file <name>; }`.
110    pub commit_files: Vec<String>,
111    pub op_files: Vec<String>,
112    pub event_files: Vec<String>,
113    pub snmp_files: Vec<String>,
114    /// e.g. `python3`.
115    pub language: Option<String>,
116    pub synchronize: bool,
117    pub max_datasize: Option<String>,
118    pub commit: Option<ScriptKind>,
119    pub op: Option<ScriptKind>,
120    pub snmp: Option<ScriptKind>,
121    pub load_scripts_from_flash: bool,
122    /// From `translation { max-datasize }`.
123    pub translation_max_datasize: Option<String>,
124}
125
126/// `mem-factor` of `start { start-options { mem-factor <percentage>; } }`.
127pub(super) fn start_mem_factor(parent: &ConfigLine) -> Option<String> {
128    let options = child_block(parent, "start").and_then(|start| child_block(start, "start-options"))?;
129    arg_of(options, "mem-factor").map(str::to_string)
130}
131
132/// The algorithm and hash of `checksum <algorithm> <hash>`.
133pub(super) fn checksum(parent: &ConfigLine) -> (Option<String>, Option<String>) {
134    match arg_of(parent, "checksum").map(split_keyword) {
135        Some((algorithm, hash)) => (
136            Some(algorithm.to_string()),
137            Some(hash.to_string()).filter(|h| !h.is_empty()),
138        ),
139        None => (None, None),
140    }
141}
142
143fn parse_script_file(name: &str, file: &ConfigLine) -> ScriptFile {
144    let (checksum_algorithm, checksum) = checksum(file);
145    ScriptFile {
146        name: name.to_string(),
147        source: arg_of(file, "source").map(str::to_string),
148        checksum_algorithm,
149        checksum,
150        cert_file: arg_of(file, "cert-file").map(str::to_string),
151        routing_instance: arg_of(file, "routing-instance").map(str::to_string),
152        start_mem_factor: start_mem_factor(file),
153        optional: has_leaf(file, "optional"),
154        allow_transients: has_leaf(file, "allow-transients"),
155        command: arg_of(file, "command").map(str::to_string),
156        description: arg_of(file, "description").map(str::to_string),
157        allow_commands: arg_of(file, "allow-commands").map(str::to_string),
158        arguments: child_block(file, "arguments")
159            .map(|arguments| {
160                active_children(arguments)
161                    .map(|argument| ScriptArgument {
162                        name: unquote(&argument.text).to_string(),
163                        description: arg_of(argument, "description").map(str::to_string),
164                    })
165                    .collect()
166            })
167            .unwrap_or_default(),
168        python_script_user: arg_of(file, "python-script-user").map(str::to_string),
169        oids: named_children(file, "oid")
170            .map(|(id, oid)| ScriptOid {
171                id: id.to_string(),
172                priority: arg_of(oid, "priority").map(str::to_string),
173            })
174            .collect(),
175    }
176}
177
178fn parse_script_kind(kind: &ConfigLine) -> ScriptKind {
179    ScriptKind {
180        files: named_children(kind, "file")
181            .map(|(name, file)| parse_script_file(name, file))
182            .collect(),
183        max_datasize: arg_of(kind, "max-datasize").map(str::to_string),
184        start_mem_factor: start_mem_factor(kind),
185        traceoptions: parse_traceoptions(kind),
186        allow_transients: has_leaf(kind, "allow-transients"),
187        direct_access: has_leaf(kind, "direct-access"),
188        allow_url_for_python: has_leaf(kind, "allow-url-for-python"),
189        no_allow_url: has_leaf(kind, "no-allow-url"),
190    }
191}
192
193pub(super) fn parse_scripts(scripts: &ConfigLine) -> Scripts {
194    let files = |kind: &str| -> Vec<String> {
195        child_block(scripts, kind)
196            .map(|block| {
197                named_children(block, "file")
198                    .map(|(name, _)| name.to_string())
199                    .collect()
200            })
201            .unwrap_or_default()
202    };
203    Scripts {
204        commit_files: files("commit"),
205        op_files: files("op"),
206        event_files: files("event"),
207        snmp_files: files("snmp"),
208        language: arg_of(scripts, "language").map(str::to_string),
209        synchronize: has_leaf(scripts, "synchronize"),
210        max_datasize: arg_of(scripts, "max-datasize").map(str::to_string),
211        commit: child_block(scripts, "commit").map(parse_script_kind),
212        op: child_block(scripts, "op").map(parse_script_kind),
213        snmp: child_block(scripts, "snmp").map(parse_script_kind),
214        load_scripts_from_flash: has_leaf(scripts, "load-scripts-from-flash"),
215        translation_max_datasize: child_block(scripts, "translation")
216            .and_then(|translation| arg_of(translation, "max-datasize"))
217            .map(str::to_string),
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use crate::system::system;
224    use asterust::config::juniper;
225
226    // Not from documentation: written from the CLI Reference syntax page. See the README "Sources".
227    #[test]
228    fn extracts_script_files_by_kind() {
229        let scripts = system(&juniper::parse_braces(
230            r#"
231system {
232    scripts {
233        language python3;
234        synchronize;
235        max-datasize 128m;
236        commit {
237            file check-mtu.slax;
238            file require-description.py {
239                optional;
240            }
241        }
242        op {
243            file show-bgp.py;
244        }
245        event {
246            file on-link-down.slax;
247        }
248        snmp {
249            file oid.py;
250        }
251    }
252}
253"#,
254        ))
255        .unwrap()
256        .scripts
257        .unwrap();
258        assert_eq!(scripts.commit_files, ["check-mtu.slax", "require-description.py"]);
259        assert_eq!(scripts.op_files, ["show-bgp.py"]);
260        assert_eq!(scripts.event_files, ["on-link-down.slax"]);
261        assert_eq!(scripts.snmp_files, ["oid.py"]);
262        assert_eq!(scripts.language.as_deref(), Some("python3"));
263        assert!(scripts.synchronize);
264        assert_eq!(scripts.max_datasize.as_deref(), Some("128m"));
265    }
266
267    #[test]
268    fn extracts_commit_script_options() {
269        let commit = system(&juniper::parse_braces(
270            r#"
271system {
272    scripts {
273        load-scripts-from-flash;
274        translation {
275            max-datasize 32m;
276        }
277        commit {
278            allow-transients;
279            direct-access;
280            max-datasize 64m;
281            traceoptions {
282                file commit-scripts.log;
283                flag output;
284                no-remote-trace;
285            }
286            file check-mtu.slax {
287                optional;
288                allow-transients;
289                source https://scripts.example.net/check-mtu.slax;
290                checksum sha-256 abc123;
291                cert-file /var/db/certs/ca.pem;
292                routing-instance mgmt_junos;
293            }
294        }
295    }
296}
297"#,
298        ))
299        .unwrap()
300        .scripts
301        .unwrap();
302        assert!(commit.load_scripts_from_flash);
303        let kind = commit.commit.as_ref().unwrap();
304        assert!(kind.allow_transients);
305        assert!(kind.direct_access);
306        assert!(!kind.no_allow_url);
307        assert_eq!(kind.max_datasize.as_deref(), Some("64m"));
308        assert_eq!(
309            kind.traceoptions.as_ref().unwrap().file.as_deref(),
310            Some("commit-scripts.log")
311        );
312
313        let file = &kind.files[0];
314        assert_eq!(file.name, "check-mtu.slax");
315        assert!(file.optional);
316        assert!(file.allow_transients);
317        assert_eq!(
318            file.source.as_deref(),
319            Some("https://scripts.example.net/check-mtu.slax")
320        );
321        assert_eq!(file.checksum_algorithm.as_deref(), Some("sha-256"));
322        assert_eq!(file.checksum.as_deref(), Some("abc123"));
323        assert_eq!(file.cert_file.as_deref(), Some("/var/db/certs/ca.pem"));
324        assert_eq!(file.routing_instance.as_deref(), Some("mgmt_junos"));
325        assert_eq!(commit.translation_max_datasize.as_deref(), Some("32m"));
326        // The flat list of file names is still filled in.
327        assert_eq!(commit.commit_files, ["check-mtu.slax"]);
328    }
329
330    #[test]
331    fn extracts_op_and_snmp_script_options() {
332        let scripts = system(&juniper::parse_braces(
333            r#"
334system {
335    scripts {
336        op {
337            allow-url-for-python;
338            start {
339                start-options {
340                    mem-factor 50;
341                }
342            }
343            file show-bgp.py {
344                command bgp;
345                description "Summarise BGP";
346                allow-commands "show bgp .*";
347                arguments {
348                    peer {
349                        description "Peer address";
350                    }
351                    vrf;
352                }
353                start {
354                    start-options {
355                        mem-factor 25;
356                    }
357                }
358            }
359        }
360        snmp {
361            no-allow-url;
362            file oid.py {
363                python-script-user ops;
364                oid .1.3.6.1.4.1.2636.13 {
365                    priority 100;
366                }
367                oid ifOperStatus;
368            }
369        }
370    }
371}
372"#,
373        ))
374        .unwrap()
375        .scripts
376        .unwrap();
377        let op = scripts.op.as_ref().unwrap();
378        assert!(op.allow_url_for_python);
379        assert_eq!(op.start_mem_factor.as_deref(), Some("50"));
380        let file = &op.files[0];
381        assert_eq!(file.command.as_deref(), Some("bgp"));
382        assert_eq!(file.description.as_deref(), Some("Summarise BGP"));
383        assert_eq!(file.allow_commands.as_deref(), Some("show bgp .*"));
384        assert_eq!(file.start_mem_factor.as_deref(), Some("25"));
385        assert_eq!(file.arguments.len(), 2);
386        assert_eq!(file.arguments[0].name, "peer");
387        assert_eq!(file.arguments[0].description.as_deref(), Some("Peer address"));
388        assert_eq!(file.arguments[1].description, None);
389
390        let snmp = scripts.snmp.as_ref().unwrap();
391        assert!(snmp.no_allow_url);
392        let file = &snmp.files[0];
393        assert_eq!(file.python_script_user.as_deref(), Some("ops"));
394        assert_eq!(file.oids.len(), 2);
395        assert_eq!(file.oids[0].id, ".1.3.6.1.4.1.2636.13");
396        assert_eq!(file.oids[0].priority.as_deref(), Some("100"));
397        assert_eq!(file.oids[1].priority, None);
398    }
399
400    #[test]
401    fn script_kinds_are_optional() {
402        let scripts = system(&juniper::parse_braces(
403            "system {\n    scripts {\n        synchronize;\n    }\n}\n",
404        ))
405        .unwrap()
406        .scripts
407        .unwrap();
408        assert!(scripts.commit.is_none());
409        assert!(scripts.op.is_none());
410        assert!(scripts.snmp.is_none());
411        assert!(!scripts.load_scripts_from_flash);
412        assert_eq!(scripts.translation_max_datasize, None);
413    }
414
415    #[test]
416    fn scripts_default_to_empty() {
417        let scripts = system(&juniper::parse_braces(
418            "system {\n    scripts {\n        synchronize;\n    }\n}\n",
419        ))
420        .unwrap()
421        .scripts
422        .unwrap();
423        assert!(scripts.commit_files.is_empty());
424        assert!(scripts.op_files.is_empty());
425        assert_eq!(scripts.language, None);
426    }
427
428    #[test]
429    fn no_scripts_is_none() {
430        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
431        assert!(system.scripts.is_none());
432    }
433}