monocle 1.2.0

A commandline application to search, parse, and process BGP information in public sources.
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
//! Shared formatting utilities for BGP elements (BgpElem)
//!
//! This module provides common functionality for formatting BGP elements
//! across parse and search commands, including field selection and
//! multiple output format support.

use bgpkit_parser::BgpElem;
use monocle::utils::{OrderByField, OrderDirection, OutputFormat, TimestampFormat};
use serde_json::json;
use tabled::builder::Builder;
use tabled::settings::Style;

/// All available output fields for BGP elements
pub const AVAILABLE_FIELDS: &[&str] = &[
    "type",
    "timestamp",
    "peer_ip",
    "peer_asn",
    "prefix",
    "as_path",
    "origin",
    "next_hop",
    "local_pref",
    "med",
    "communities",
    "atomic",
    "aggr_asn",
    "aggr_ip",
    "collector",
];

/// Default fields to output for parse command (no collector)
pub const DEFAULT_FIELDS_PARSE: &[&str] = &[
    "type",
    "timestamp",
    "peer_ip",
    "peer_asn",
    "prefix",
    "as_path",
    "origin",
    "next_hop",
    "local_pref",
    "med",
    "communities",
    "atomic",
    "aggr_asn",
    "aggr_ip",
];

/// Default fields to output for search command (includes collector)
pub const DEFAULT_FIELDS_SEARCH: &[&str] = &[
    "type",
    "timestamp",
    "peer_ip",
    "peer_asn",
    "prefix",
    "as_path",
    "origin",
    "next_hop",
    "local_pref",
    "med",
    "communities",
    "atomic",
    "aggr_asn",
    "aggr_ip",
    "collector",
];

/// Format a collection of BgpElems as a tabled table with selected fields
pub fn format_elems_table(
    elems: &[(BgpElem, Option<String>)],
    fields: &[&str],
    time_format: TimestampFormat,
) -> String {
    let mut builder = Builder::default();

    // Add header row
    builder.push_record(fields.iter().copied());

    // Add data rows
    for (elem, collector) in elems {
        let row: Vec<String> = fields
            .iter()
            .map(|f| get_field_value_with_time_format(elem, f, collector.as_deref(), time_format))
            .collect();
        builder.push_record(row);
    }

    let mut table = builder.build();
    table.with(Style::rounded());
    table.to_string()
}

/// Generate help text for the fields argument
pub fn available_fields_help() -> String {
    format!(
        "Comma-separated list of fields to output. Available fields: {}",
        AVAILABLE_FIELDS.join(", ")
    )
}

/// Parse and validate the fields argument
/// Returns the validated fields. If fields_arg is None, returns the appropriate defaults.
/// `include_collector_default` should be true for search command, false for parse command.
pub fn parse_fields(
    fields_arg: &Option<String>,
    include_collector_default: bool,
) -> Result<Vec<&'static str>, String> {
    match fields_arg {
        None => {
            if include_collector_default {
                Ok(DEFAULT_FIELDS_SEARCH.to_vec())
            } else {
                Ok(DEFAULT_FIELDS_PARSE.to_vec())
            }
        }
        Some(fields_str) => {
            let requested: Vec<&str> = fields_str.split(',').map(|s| s.trim()).collect();
            let mut validated = Vec::new();

            for field in requested {
                if field.is_empty() {
                    continue;
                }
                if let Some(&valid_field) = AVAILABLE_FIELDS.iter().find(|&&f| f == field) {
                    validated.push(valid_field);
                } else {
                    return Err(format!(
                        "Unknown field '{}'. Available fields: {}",
                        field,
                        AVAILABLE_FIELDS.join(", ")
                    ));
                }
            }

            if validated.is_empty() {
                if include_collector_default {
                    Ok(DEFAULT_FIELDS_SEARCH.to_vec())
                } else {
                    Ok(DEFAULT_FIELDS_PARSE.to_vec())
                }
            } else {
                Ok(validated)
            }
        }
    }
}

/// Get the value of a specific field from a BgpElem
/// For the "collector" field, pass the collector value via the `collector` parameter.
/// Uses default Unix timestamp format for backward compatibility.
#[allow(dead_code)]
pub fn get_field_value(elem: &BgpElem, field: &str, collector: Option<&str>) -> String {
    get_field_value_with_time_format(elem, field, collector, TimestampFormat::Unix)
}

/// Get the value of a specific field from a BgpElem with configurable timestamp format
/// For the "collector" field, pass the collector value via the `collector` parameter.
pub fn get_field_value_with_time_format(
    elem: &BgpElem,
    field: &str,
    collector: Option<&str>,
    time_format: TimestampFormat,
) -> String {
    match field {
        "type" => {
            if elem.elem_type == bgpkit_parser::models::ElemType::ANNOUNCE {
                "A".to_string()
            } else {
                "W".to_string()
            }
        }
        "timestamp" => time_format.format_timestamp(elem.timestamp),
        "peer_ip" => elem.peer_ip.to_string(),
        "peer_asn" => elem.peer_asn.to_string(),
        "prefix" => elem.prefix.to_string(),
        "as_path" => elem
            .as_path
            .as_ref()
            .map(|p| p.to_string())
            .unwrap_or_default(),
        "origin" => elem
            .origin
            .as_ref()
            .map(|o| o.to_string())
            .unwrap_or_default(),
        "next_hop" => elem
            .next_hop
            .as_ref()
            .map(|h| h.to_string())
            .unwrap_or_default(),
        "local_pref" => elem
            .local_pref
            .as_ref()
            .map(|l| l.to_string())
            .unwrap_or_default(),
        "med" => elem.med.as_ref().map(|m| m.to_string()).unwrap_or_default(),
        "communities" => elem
            .communities
            .as_ref()
            .map(|c| {
                c.iter()
                    .map(|comm| comm.to_string())
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .unwrap_or_default(),
        "atomic" => elem.atomic.to_string(),
        "aggr_asn" => elem
            .aggr_asn
            .as_ref()
            .map(|a| a.to_string())
            .unwrap_or_default(),
        "aggr_ip" => elem
            .aggr_ip
            .as_ref()
            .map(|i| i.to_string())
            .unwrap_or_default(),
        "collector" => collector.unwrap_or("").to_string(),
        _ => String::new(),
    }
}

/// Format a BgpElem according to the output format and selected fields.
/// The `collector` parameter provides the collector value for the "collector" field.
/// The `time_format` parameter controls how timestamps are displayed in non-JSON formats.
/// Note: For Table format, this returns an empty string - use format_elems_table() instead
/// after collecting all elements.
pub fn format_elem(
    elem: &BgpElem,
    output_format: OutputFormat,
    fields: &[&str],
    collector: Option<&str>,
    time_format: TimestampFormat,
) -> Option<String> {
    match output_format {
        OutputFormat::Json | OutputFormat::JsonLine => {
            // JSON always uses Unix timestamp as number for backward compatibility
            let obj = build_json_object(elem, fields, collector);
            Some(serde_json::to_string(&obj).unwrap_or_else(|_| elem.to_string()))
        }
        OutputFormat::JsonPretty => {
            // JSON always uses Unix timestamp as number for backward compatibility
            let obj = build_json_object(elem, fields, collector);
            Some(serde_json::to_string_pretty(&obj).unwrap_or_else(|_| elem.to_string()))
        }
        OutputFormat::Psv => {
            // Pipe-separated values (no header for backward compatibility)
            let values: Vec<String> = fields
                .iter()
                .map(|f| get_field_value_with_time_format(elem, f, collector, time_format))
                .collect();
            Some(values.join("|"))
        }
        OutputFormat::Table => {
            // Table format buffers all elements and formats at the end
            // Return None to signal caller should buffer this element
            None
        }
        OutputFormat::Markdown => {
            // Markdown table row
            let values: Vec<String> = fields
                .iter()
                .map(|f| get_field_value_with_time_format(elem, f, collector, time_format))
                .collect();
            Some(format!("| {} |", values.join(" | ")))
        }
    }
}

/// Build a JSON object with only the selected fields
/// The `collector` parameter provides the collector value for the "collector" field.
pub fn build_json_object(
    elem: &BgpElem,
    fields: &[&str],
    collector: Option<&str>,
) -> serde_json::Value {
    // If all default parse fields are selected and no collector field, use the original serialization
    if fields == DEFAULT_FIELDS_PARSE && !fields.contains(&"collector") {
        return json!(elem);
    }

    let mut obj = serde_json::Map::new();
    for field in fields {
        let value = match *field {
            "type" => json!(elem.elem_type),
            "timestamp" => json!(elem.timestamp),
            "peer_ip" => json!(elem.peer_ip.to_string()),
            "peer_asn" => json!(elem.peer_asn),
            "prefix" => json!(elem.prefix.to_string()),
            "as_path" => match &elem.as_path {
                Some(p) => json!(p.to_string()),
                None => serde_json::Value::Null,
            },
            "origin" => match &elem.origin {
                Some(o) => json!(o.to_string()),
                None => serde_json::Value::Null,
            },
            "next_hop" => match &elem.next_hop {
                Some(h) => json!(h.to_string()),
                None => serde_json::Value::Null,
            },
            "local_pref" => match elem.local_pref {
                Some(l) => json!(l),
                None => serde_json::Value::Null,
            },
            "med" => match elem.med {
                Some(m) => json!(m),
                None => serde_json::Value::Null,
            },
            "communities" => match &elem.communities {
                Some(c) => json!(c.iter().map(|comm| comm.to_string()).collect::<Vec<_>>()),
                None => serde_json::Value::Null,
            },
            "atomic" => json!(elem.atomic),
            "aggr_asn" => match &elem.aggr_asn {
                Some(a) => json!(a),
                None => serde_json::Value::Null,
            },
            "aggr_ip" => match &elem.aggr_ip {
                Some(i) => json!(i.to_string()),
                None => serde_json::Value::Null,
            },
            "collector" => match collector {
                Some(c) => json!(c),
                None => serde_json::Value::Null,
            },
            _ => serde_json::Value::Null,
        };
        obj.insert((*field).to_string(), value);
    }

    serde_json::Value::Object(obj)
}

/// Get the header line for markdown output format.
/// Returns None for JSON, PSV (backward compatibility), and Table (uses tabled) formats.
pub fn get_header(output_format: OutputFormat, fields: &[&str]) -> Option<String> {
    match output_format {
        // JSON formats don't need headers
        OutputFormat::Json | OutputFormat::JsonPretty | OutputFormat::JsonLine => None,
        // PSV: no header for backward compatibility
        OutputFormat::Psv => None,
        // Table: handled by tabled, no streaming header needed
        OutputFormat::Table => None,
        // Markdown: needs header row with separator
        OutputFormat::Markdown => {
            let header = format!("| {} |", fields.join(" | "));
            let separator = format!(
                "| {} |",
                fields.iter().map(|_| "---").collect::<Vec<_>>().join(" | ")
            );
            Some(format!("{}\n{}", header, separator))
        }
    }
}

/// Sort a collection of BgpElems by the specified field and direction.
///
/// This function sorts the elements in place, which is more efficient than
/// creating a new vector.
pub fn sort_elems(
    elems: &mut [(BgpElem, Option<String>)],
    order_by: OrderByField,
    direction: OrderDirection,
) {
    elems.sort_by(|(a, _), (b, _)| {
        let cmp = match order_by {
            OrderByField::Timestamp => a
                .timestamp
                .partial_cmp(&b.timestamp)
                .unwrap_or(std::cmp::Ordering::Equal),
            OrderByField::Prefix => a.prefix.to_string().cmp(&b.prefix.to_string()),
            OrderByField::PeerIp => a.peer_ip.to_string().cmp(&b.peer_ip.to_string()),
            OrderByField::PeerAsn => a.peer_asn.cmp(&b.peer_asn),
            OrderByField::AsPath => {
                let a_path = a
                    .as_path
                    .as_ref()
                    .map(|p| p.to_string())
                    .unwrap_or_default();
                let b_path = b
                    .as_path
                    .as_ref()
                    .map(|p| p.to_string())
                    .unwrap_or_default();
                a_path.cmp(&b_path)
            }
            OrderByField::NextHop => {
                let a_hop = a
                    .next_hop
                    .as_ref()
                    .map(|h| h.to_string())
                    .unwrap_or_default();
                let b_hop = b
                    .next_hop
                    .as_ref()
                    .map(|h| h.to_string())
                    .unwrap_or_default();
                a_hop.cmp(&b_hop)
            }
        };
        match direction {
            OrderDirection::Asc => cmp,
            OrderDirection::Desc => cmp.reverse(),
        }
    });
}