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