asterust-junos 0.5.13

Typed Juniper JunOS config views (interfaces, protocols, routing instances and options, policy options, firewall filters, class of service, system, services) extracted from an asterust config tree.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! `scripts`
//! `system { scripts { ... } }`.
//!
//! # See also
//!
//! - [scripts](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/scripts-edit-system.html)
//! - [source (Commit Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/source-edit-system-commit.html)
//! - [source (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/source-edit-system-op.html)
//! - [source (SNMP Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/source-edit-system-scripts-snmp-file.html)
//! - [checksum (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/checksum-edit-system-scripts.html)
//! - [cert-file (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/cert-file-edit-system-scripts.html)
//! - [routing-instance (System Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/routing-instance-edit-system-scripts.html)
//! - [start (Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/start-edit-system-scripts.html)
//! - [command (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/command-edit-system-scripts.html)
//! - [arguments (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/arguments-edit-system.html)
//! - [allow-commands (Op Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/allow-commands-edit-system-scripts.html)
//! - [optional (Commit Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/optional-edit-system.html)
//! - [allow-transients](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/allow-transients-edit-system.html)
//! - [direct-access (Commit Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/direct-access-edit-system.html)
//! - [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)
//! - [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)
//! - [oid (SNMP Scripts)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/oid-edit-system-scripts-snmp-file.html)
//! - [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)
//! - [dampen](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/dampen-edit-event-options-event-script.html)
//! - [dampen-options](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/dampen-options-edit-event-options-dampen.html)
//! - [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)
//! - [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)
//! - [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)
//! - [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)
//! - [translation](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/translation-edit-system.html)
//! - [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)
//!
//! `refresh` and `refresh-from` are not read: setting them runs an operation and does not add a
//! statement to the configuration.

use crate::protocols::traceoptions::{parse_traceoptions, Traceoptions};
use crate::{active_children, arg_of, child_block, has_leaf, named_children, split_keyword, unquote};
use asterust::config::ConfigLine;

/// The `dampen { dampen-options { ... } }` settings that slow scripts down when the CPU is busy.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScriptDampen {
    pub cpu_factor: Option<String>,
    pub line_interval: Option<String>,
    /// Microseconds.
    pub time_interval: Option<String>,
}

/// An `arguments <name>` entry of an op script file.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScriptArgument {
    pub name: String,
    pub description: Option<String>,
}

/// An `oid <id>` entry of an SNMP script file.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScriptOid {
    pub id: String,
    /// Registration priority, 1 to 255.
    pub priority: Option<String>,
}

/// A `file <name>` of the commit, op or SNMP scripts. The options only some kinds have are unset or
/// empty for the others.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScriptFile {
    pub name: String,
    /// The URL scripts are refreshed from.
    pub source: Option<String>,
    /// `md5`, `sha-256` or `sha1`, from `checksum`.
    pub checksum_algorithm: Option<String>,
    pub checksum: Option<String>,
    /// The certificate used to validate the server when refreshing from HTTPS.
    pub cert_file: Option<String>,
    pub routing_instance: Option<String>,
    /// Percentage, from `start { start-options { mem-factor } }`.
    pub start_mem_factor: Option<String>,
    /// Commit scripts only.
    pub optional: bool,
    /// Commit scripts only.
    pub allow_transients: bool,
    /// Op scripts only: an alias for the file name.
    pub command: Option<String>,
    /// Op scripts only.
    pub description: Option<String>,
    /// Op scripts only.
    pub allow_commands: Option<String>,
    /// Op scripts only.
    pub arguments: Vec<ScriptArgument>,
    /// SNMP scripts only.
    pub python_script_user: Option<String>,
    /// SNMP scripts only.
    pub oids: Vec<ScriptOid>,
    /// Op scripts only.
    pub dampen: Option<ScriptDampen>,
}

/// The `commit`, `op` or `snmp` block of `system scripts`. The options only some kinds have are unset
/// for the others.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScriptKind {
    pub files: Vec<ScriptFile>,
    pub max_datasize: Option<String>,
    /// Percentage, from `start { start-options { mem-factor } }`.
    pub start_mem_factor: Option<String>,
    pub traceoptions: Option<Traceoptions>,
    /// Commit scripts only.
    pub allow_transients: bool,
    /// Commit scripts only.
    pub direct_access: bool,
    /// Op scripts only.
    pub allow_url_for_python: bool,
    /// Op scripts only.
    pub no_allow_url: bool,
    /// Commit and op scripts only.
    pub dampen: Option<ScriptDampen>,
}

/// The `system scripts` configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Scripts {
    /// File names from `commit { file <name>; }`.
    pub commit_files: Vec<String>,
    pub op_files: Vec<String>,
    pub event_files: Vec<String>,
    pub snmp_files: Vec<String>,
    /// e.g. `python3`.
    pub language: Option<String>,
    pub synchronize: bool,
    pub max_datasize: Option<String>,
    pub commit: Option<ScriptKind>,
    pub op: Option<ScriptKind>,
    pub snmp: Option<ScriptKind>,
    pub load_scripts_from_flash: bool,
    /// From `translation { max-datasize }`.
    pub translation_max_datasize: Option<String>,
}

/// `mem-factor` of `start { start-options { mem-factor <percentage>; } }`.
pub(super) fn start_mem_factor(parent: &ConfigLine) -> Option<String> {
    let options = child_block(parent, "start").and_then(|start| child_block(start, "start-options"))?;
    arg_of(options, "mem-factor").map(str::to_string)
}

/// The algorithm and hash of `checksum <algorithm> <hash>`.
pub(super) fn checksum(parent: &ConfigLine) -> (Option<String>, Option<String>) {
    match arg_of(parent, "checksum").map(split_keyword) {
        Some((algorithm, hash)) => (
            Some(algorithm.to_string()),
            Some(hash.to_string()).filter(|h| !h.is_empty()),
        ),
        None => (None, None),
    }
}

fn parse_dampen(parent: &ConfigLine) -> Option<ScriptDampen> {
    let options = child_block(child_block(parent, "dampen")?, "dampen-options")?;
    Some(ScriptDampen {
        cpu_factor: arg_of(options, "cpu-factor").map(str::to_string),
        line_interval: arg_of(options, "line-interval").map(str::to_string),
        time_interval: arg_of(options, "time-interval").map(str::to_string),
    })
}

fn parse_script_file(name: &str, file: &ConfigLine) -> ScriptFile {
    let (checksum_algorithm, checksum) = checksum(file);
    ScriptFile {
        name: name.to_string(),
        source: arg_of(file, "source").map(str::to_string),
        checksum_algorithm,
        checksum,
        cert_file: arg_of(file, "cert-file").map(str::to_string),
        routing_instance: arg_of(file, "routing-instance").map(str::to_string),
        start_mem_factor: start_mem_factor(file),
        optional: has_leaf(file, "optional"),
        allow_transients: has_leaf(file, "allow-transients"),
        command: arg_of(file, "command").map(str::to_string),
        description: arg_of(file, "description").map(str::to_string),
        allow_commands: arg_of(file, "allow-commands").map(str::to_string),
        arguments: child_block(file, "arguments")
            .map(|arguments| {
                active_children(arguments)
                    .map(|argument| ScriptArgument {
                        name: unquote(&argument.text).to_string(),
                        description: arg_of(argument, "description").map(str::to_string),
                    })
                    .collect()
            })
            .unwrap_or_default(),
        python_script_user: arg_of(file, "python-script-user").map(str::to_string),
        oids: named_children(file, "oid")
            .map(|(id, oid)| ScriptOid {
                id: id.to_string(),
                priority: arg_of(oid, "priority").map(str::to_string),
            })
            .collect(),
        dampen: parse_dampen(file),
    }
}

fn parse_script_kind(kind: &ConfigLine) -> ScriptKind {
    ScriptKind {
        files: named_children(kind, "file")
            .map(|(name, file)| parse_script_file(name, file))
            .collect(),
        max_datasize: arg_of(kind, "max-datasize").map(str::to_string),
        start_mem_factor: start_mem_factor(kind),
        traceoptions: parse_traceoptions(kind),
        allow_transients: has_leaf(kind, "allow-transients"),
        direct_access: has_leaf(kind, "direct-access"),
        allow_url_for_python: has_leaf(kind, "allow-url-for-python"),
        no_allow_url: has_leaf(kind, "no-allow-url"),
        dampen: parse_dampen(kind),
    }
}

pub(super) fn parse_scripts(scripts: &ConfigLine) -> Scripts {
    let files = |kind: &str| -> Vec<String> {
        child_block(scripts, kind)
            .map(|block| {
                named_children(block, "file")
                    .map(|(name, _)| name.to_string())
                    .collect()
            })
            .unwrap_or_default()
    };
    Scripts {
        commit_files: files("commit"),
        op_files: files("op"),
        event_files: files("event"),
        snmp_files: files("snmp"),
        language: arg_of(scripts, "language").map(str::to_string),
        synchronize: has_leaf(scripts, "synchronize"),
        max_datasize: arg_of(scripts, "max-datasize").map(str::to_string),
        commit: child_block(scripts, "commit").map(parse_script_kind),
        op: child_block(scripts, "op").map(parse_script_kind),
        snmp: child_block(scripts, "snmp").map(parse_script_kind),
        load_scripts_from_flash: has_leaf(scripts, "load-scripts-from-flash"),
        translation_max_datasize: child_block(scripts, "translation")
            .and_then(|translation| arg_of(translation, "max-datasize"))
            .map(str::to_string),
    }
}

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

    // Not from documentation: written from the CLI Reference syntax page. See the README "Sources".
    #[test]
    fn extracts_script_files_by_kind() {
        let scripts = system(&juniper::parse_braces(
            r#"
system {
    scripts {
        language python3;
        synchronize;
        max-datasize 128m;
        commit {
            file check-mtu.slax;
            file require-description.py {
                optional;
            }
        }
        op {
            file show-bgp.py;
        }
        event {
            file on-link-down.slax;
        }
        snmp {
            file oid.py;
        }
    }
}
"#,
        ))
        .unwrap()
        .scripts
        .unwrap();
        assert_eq!(scripts.commit_files, ["check-mtu.slax", "require-description.py"]);
        assert_eq!(scripts.op_files, ["show-bgp.py"]);
        assert_eq!(scripts.event_files, ["on-link-down.slax"]);
        assert_eq!(scripts.snmp_files, ["oid.py"]);
        assert_eq!(scripts.language.as_deref(), Some("python3"));
        assert!(scripts.synchronize);
        assert_eq!(scripts.max_datasize.as_deref(), Some("128m"));
    }

    #[test]
    fn extracts_commit_script_options() {
        let commit = system(&juniper::parse_braces(
            r#"
system {
    scripts {
        load-scripts-from-flash;
        translation {
            max-datasize 32m;
        }
        commit {
            allow-transients;
            direct-access;
            max-datasize 64m;
            traceoptions {
                file commit-scripts.log;
                flag output;
                no-remote-trace;
            }
            file check-mtu.slax {
                optional;
                allow-transients;
                source https://scripts.example.net/check-mtu.slax;
                checksum sha-256 abc123;
                cert-file /var/db/certs/ca.pem;
                routing-instance mgmt_junos;
            }
        }
    }
}
"#,
        ))
        .unwrap()
        .scripts
        .unwrap();
        assert!(commit.load_scripts_from_flash);
        let kind = commit.commit.as_ref().unwrap();
        assert!(kind.allow_transients);
        assert!(kind.direct_access);
        assert!(!kind.no_allow_url);
        assert_eq!(kind.max_datasize.as_deref(), Some("64m"));
        assert_eq!(
            kind.traceoptions.as_ref().unwrap().file.as_deref(),
            Some("commit-scripts.log")
        );

        let file = &kind.files[0];
        assert_eq!(file.name, "check-mtu.slax");
        assert!(file.optional);
        assert!(file.allow_transients);
        assert_eq!(
            file.source.as_deref(),
            Some("https://scripts.example.net/check-mtu.slax")
        );
        assert_eq!(file.checksum_algorithm.as_deref(), Some("sha-256"));
        assert_eq!(file.checksum.as_deref(), Some("abc123"));
        assert_eq!(file.cert_file.as_deref(), Some("/var/db/certs/ca.pem"));
        assert_eq!(file.routing_instance.as_deref(), Some("mgmt_junos"));
        assert_eq!(commit.translation_max_datasize.as_deref(), Some("32m"));
        // The flat list of file names is still filled in.
        assert_eq!(commit.commit_files, ["check-mtu.slax"]);
    }

    #[test]
    fn extracts_op_and_snmp_script_options() {
        let scripts = system(&juniper::parse_braces(
            r#"
system {
    scripts {
        op {
            allow-url-for-python;
            start {
                start-options {
                    mem-factor 50;
                }
            }
            file show-bgp.py {
                command bgp;
                description "Summarise BGP";
                allow-commands "show bgp .*";
                arguments {
                    peer {
                        description "Peer address";
                    }
                    vrf;
                }
                start {
                    start-options {
                        mem-factor 25;
                    }
                }
            }
        }
        snmp {
            no-allow-url;
            file oid.py {
                python-script-user ops;
                oid .1.3.6.1.4.1.2636.13 {
                    priority 100;
                }
                oid ifOperStatus;
            }
        }
    }
}
"#,
        ))
        .unwrap()
        .scripts
        .unwrap();
        let op = scripts.op.as_ref().unwrap();
        assert!(op.allow_url_for_python);
        assert_eq!(op.start_mem_factor.as_deref(), Some("50"));
        let file = &op.files[0];
        assert_eq!(file.command.as_deref(), Some("bgp"));
        assert_eq!(file.description.as_deref(), Some("Summarise BGP"));
        assert_eq!(file.allow_commands.as_deref(), Some("show bgp .*"));
        assert_eq!(file.start_mem_factor.as_deref(), Some("25"));
        assert_eq!(file.arguments.len(), 2);
        assert_eq!(file.arguments[0].name, "peer");
        assert_eq!(file.arguments[0].description.as_deref(), Some("Peer address"));
        assert_eq!(file.arguments[1].description, None);

        let snmp = scripts.snmp.as_ref().unwrap();
        assert!(snmp.no_allow_url);
        let file = &snmp.files[0];
        assert_eq!(file.python_script_user.as_deref(), Some("ops"));
        assert_eq!(file.oids.len(), 2);
        assert_eq!(file.oids[0].id, ".1.3.6.1.4.1.2636.13");
        assert_eq!(file.oids[0].priority.as_deref(), Some("100"));
        assert_eq!(file.oids[1].priority, None);
    }

    #[test]
    fn extracts_script_dampening() {
        let scripts = system(&juniper::parse_braces(
            r#"
system {
    scripts {
        commit {
            dampen {
                dampen-options {
                    cpu-factor 70;
                    line-interval 500;
                    time-interval 100000;
                }
            }
        }
        op {
            file slow.py {
                dampen {
                    dampen-options {
                        cpu-factor 50;
                    }
                }
            }
        }
    }
}
"#,
        ))
        .unwrap()
        .scripts
        .unwrap();
        let commit = scripts.commit.unwrap().dampen.unwrap();
        assert_eq!(commit.cpu_factor.as_deref(), Some("70"));
        assert_eq!(commit.line_interval.as_deref(), Some("500"));
        assert_eq!(commit.time_interval.as_deref(), Some("100000"));
        let file = scripts.op.unwrap().files.remove(0);
        assert_eq!(file.dampen.unwrap().cpu_factor.as_deref(), Some("50"));
    }

    #[test]
    fn script_kinds_are_optional() {
        let scripts = system(&juniper::parse_braces(
            "system {\n    scripts {\n        synchronize;\n    }\n}\n",
        ))
        .unwrap()
        .scripts
        .unwrap();
        assert!(scripts.commit.is_none());
        assert!(scripts.op.is_none());
        assert!(scripts.snmp.is_none());
        assert!(!scripts.load_scripts_from_flash);
        assert_eq!(scripts.translation_max_datasize, None);
    }

    #[test]
    fn scripts_default_to_empty() {
        let scripts = system(&juniper::parse_braces(
            "system {\n    scripts {\n        synchronize;\n    }\n}\n",
        ))
        .unwrap()
        .scripts
        .unwrap();
        assert!(scripts.commit_files.is_empty());
        assert!(scripts.op_files.is_empty());
        assert_eq!(scripts.language, None);
    }

    #[test]
    fn no_scripts_is_none() {
        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
        assert!(system.scripts.is_none());
    }
}