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
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use clap::Args;
use monocle::database::MonocleDatabase;
use monocle::lens::as2rel::{As2relLens, As2relSearchArgs};
use monocle::utils::{truncate_name, OutputFormat, DEFAULT_NAME_MAX_LEN};
use monocle::MonocleConfig;
use serde::Serialize;
use serde_json::json;
use std::time::Duration;
use tabled::settings::Style;
use tabled::Table;

/// Arguments for the As2rel command
#[derive(Args)]
pub struct As2relArgs {
    /// One or more ASNs to query relationships for
    ///
    /// - Single ASN: shows all relationships for that ASN
    /// - Two ASNs: shows the relationship between them
    /// - Multiple ASNs: shows relationships for all pairs (asn1 < asn2)
    #[clap(required = true)]
    pub asns: Vec<u32>,

    /// Force update the local as2rel database
    #[clap(short, long)]
    pub update: bool,

    /// Update with a custom data file (local path or URL)
    #[clap(long)]
    pub update_with: Option<String>,

    /// Hide the explanation text
    #[clap(long)]
    pub no_explain: bool,

    /// Sort by ASN2 ascending instead of connected percentage descending
    #[clap(long)]
    pub sort_by_asn: bool,

    /// Show organization name for ASN2 (from asinfo database)
    #[clap(long)]
    pub show_name: bool,

    /// Show full organization name without truncation (default truncates to 20 chars)
    #[clap(long)]
    pub show_full_name: bool,

    /// Minimum visibility percentage (0-100) to include in results
    ///
    /// Filters out relationships seen by fewer than this percentage of peers.
    #[clap(long, value_name = "PERCENT")]
    pub min_visibility: Option<f32>,

    /// Only show ASNs that are single-homed to the queried ASN
    ///
    /// An ASN is single-homed if it has exactly one upstream provider.
    /// This finds ASNs where the queried ASN is their ONLY upstream.
    ///
    /// Only applicable when querying a single ASN.
    #[clap(long)]
    pub single_homed: bool,

    /// Only show relationships where the queried ASN is an upstream (provider)
    ///
    /// Shows the downstream customers of the queried ASN.
    /// Only applicable when querying a single ASN.
    #[clap(long, conflicts_with_all = ["is_downstream", "is_peer"])]
    pub is_upstream: bool,

    /// Only show relationships where the queried ASN is a downstream (customer)
    ///
    /// Shows the upstream providers of the queried ASN.
    /// Only applicable when querying a single ASN.
    #[clap(long, conflicts_with_all = ["is_upstream", "is_peer"])]
    pub is_downstream: bool,

    /// Only show peer relationships
    ///
    /// Only applicable when querying a single ASN.
    #[clap(long, conflicts_with_all = ["is_upstream", "is_downstream"])]
    pub is_peer: bool,
}

pub fn run(config: &MonocleConfig, args: As2relArgs, output_format: OutputFormat, no_update: bool) {
    let As2relArgs {
        asns,
        update,
        update_with,
        no_explain,
        sort_by_asn,
        show_name,
        show_full_name,
        min_visibility,
        single_homed,
        is_upstream,
        is_downstream,
        is_peer,
    } = args;

    // show_full_name implies show_name
    let show_name = show_name || show_full_name;

    // Validate ASN count
    if asns.is_empty() {
        eprintln!("ERROR: Please provide at least one ASN");
        std::process::exit(1);
    }

    // Validate single-ASN-only flags
    if asns.len() != 1 {
        if single_homed {
            eprintln!("ERROR: --single-homed can only be used with a single ASN");
            std::process::exit(1);
        }
        if is_upstream || is_downstream || is_peer {
            eprintln!(
                "ERROR: --is-upstream, --is-downstream, and --is-peer can only be used with a single ASN"
            );
            std::process::exit(1);
        }
    }

    // Validate min_visibility range
    if let Some(min_vis) = min_visibility {
        if !(0.0..=100.0).contains(&min_vis) {
            eprintln!("ERROR: --min-visibility must be between 0 and 100");
            std::process::exit(1);
        }
    }

    let sqlite_path = config.sqlite_path();

    // Handle explicit updates
    if update || update_with.is_some() {
        if no_update {
            eprintln!("[monocle] Warning: --update ignored because --no-update is set");
        } else {
            eprintln!("[monocle] Updating AS2rel data...");

            let db = match MonocleDatabase::open(&sqlite_path) {
                Ok(db) => db,
                Err(e) => {
                    eprintln!("Failed to open database: {}", e);
                    std::process::exit(1);
                }
            };

            let lens = As2relLens::with_ttl(&db, config.as2rel_cache_ttl());
            let result = match &update_with {
                Some(path) => lens.update_from(path),
                None => lens.update(),
            };

            match result {
                Ok(count) => {
                    eprintln!(
                        "[monocle] AS2rel data updated: {} relationships loaded",
                        count
                    );
                }
                Err(e) => {
                    eprintln!("[monocle] Failed to update AS2rel data: {}", e);
                    std::process::exit(1);
                }
            }

            // Continue with query using the same connection
            run_query(
                &db,
                &asns,
                sort_by_asn,
                show_name,
                show_full_name,
                no_explain,
                output_format,
                min_visibility,
                single_homed,
                is_upstream,
                is_downstream,
                is_peer,
                config.as2rel_cache_ttl(),
            );
            return;
        }
    }

    // Open the database
    let db = match MonocleDatabase::open(&sqlite_path) {
        Ok(db) => db,
        Err(e) => {
            eprintln!("Failed to open database: {}", e);
            std::process::exit(1);
        }
    };

    let lens = As2relLens::with_ttl(&db, config.as2rel_cache_ttl());

    // Check if data needs to be initialized or updated automatically
    if let Some(reason) = lens.update_reason() {
        if no_update {
            eprintln!(
                "[monocle] Warning: AS2rel {} Results may be incomplete.",
                reason
            );
            eprintln!("[monocle]          Run without --no-update or use 'monocle config update --as2rel' to load data.");
        } else {
            eprintln!("[monocle] AS2rel {}, updating now...", reason);

            match lens.update() {
                Ok(count) => {
                    eprintln!(
                        "[monocle] AS2rel data updated: {} relationships loaded",
                        count
                    );
                }
                Err(e) => {
                    eprintln!("[monocle] Failed to update AS2rel data: {}", e);
                    std::process::exit(1);
                }
            }
        }
    }

    // Run query
    run_query(
        &db,
        &asns,
        sort_by_asn,
        show_name,
        show_full_name,
        no_explain,
        output_format,
        min_visibility,
        single_homed,
        is_upstream,
        is_downstream,
        is_peer,
        config.as2rel_cache_ttl(),
    );
}

#[derive(Debug, Clone, Serialize, tabled::Tabled)]
struct As2relResult {
    asn1: u32,
    asn2: u32,
    connected: String,
    peer: String,
    as1_upstream: String,
    as2_upstream: String,
}

#[derive(Debug, Clone, Serialize, tabled::Tabled)]
struct As2relResultWithName {
    asn1: u32,
    asn2: u32,
    asn2_name: String,
    connected: String,
    peer: String,
    as1_upstream: String,
    as2_upstream: String,
}

#[allow(clippy::too_many_arguments)]
fn run_query(
    db: &MonocleDatabase,
    asns: &[u32],
    sort_by_asn: bool,
    show_name: bool,
    show_full_name: bool,
    no_explain: bool,
    output_format: OutputFormat,
    min_visibility: Option<f32>,
    single_homed: bool,
    is_upstream: bool,
    is_downstream: bool,
    is_peer: bool,
    ttl: Duration,
) {
    let lens = As2relLens::with_ttl(db, ttl);

    // Build search args
    let search_args = As2relSearchArgs {
        asns: asns.to_vec(),
        sort_by_asn,
        show_name,
        no_explain,
        min_visibility,
        single_homed,
        is_upstream,
        is_downstream,
        is_peer,
    };

    // Validate
    if let Err(e) = search_args.validate() {
        eprintln!("ERROR: {}", e);
        std::process::exit(1);
    }

    // Perform search
    let results = match lens.search(&search_args) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("Error searching for AS relationships: {}", e);
            std::process::exit(1);
        }
    };

    // Handle empty results
    if results.is_empty() {
        if output_format.is_json() {
            println!("[]");
        } else if single_homed {
            println!(
                "No single-homed ASNs found for AS{} (with the current filters)",
                asns[0]
            );
        } else if asns.len() == 1 {
            let filter_msg = if is_upstream {
                " with --is-upstream filter"
            } else if is_downstream {
                " with --is-downstream filter"
            } else if is_peer {
                " with --is-peer filter"
            } else {
                ""
            };
            println!("No relationships found for ASN {}{}", asns[0], filter_msg);
        } else if asns.len() == 2 {
            println!(
                "No relationship found between ASN {} and ASN {}",
                asns[0], asns[1]
            );
        } else {
            println!("No relationships found among the provided ASNs");
        }
        return;
    }

    // Print explanation to stderr unless --no-explain is set or JSON output
    if !no_explain && !output_format.is_json() {
        if single_homed {
            eprintln!("{}", lens.get_single_homed_explanation(asns[0]));
        } else {
            eprintln!("{}", lens.get_explanation());
        }
    }

    // Truncate names for table output unless show_full_name is set
    let truncate_names = !show_full_name && output_format.is_table();
    let max_peers = lens.get_max_peers_count();

    // Format and print results based on output format
    match output_format {
        OutputFormat::Table => {
            if show_name {
                let display: Vec<As2relResultWithName> = results
                    .iter()
                    .map(|r| As2relResultWithName {
                        asn1: r.asn1,
                        asn2: r.asn2,
                        asn2_name: format_name(&r.asn2_name, truncate_names),
                        connected: r.connected.clone(),
                        peer: r.peer.clone(),
                        as1_upstream: r.as1_upstream.clone(),
                        as2_upstream: r.as2_upstream.clone(),
                    })
                    .collect();
                println!("{}", Table::new(display).with(Style::rounded()));
            } else {
                let display: Vec<As2relResult> = results
                    .iter()
                    .map(|r| As2relResult {
                        asn1: r.asn1,
                        asn2: r.asn2,
                        connected: r.connected.clone(),
                        peer: r.peer.clone(),
                        as1_upstream: r.as1_upstream.clone(),
                        as2_upstream: r.as2_upstream.clone(),
                    })
                    .collect();
                println!("{}", Table::new(display).with(Style::rounded()));
            }
        }
        OutputFormat::Markdown => {
            if show_name {
                let display: Vec<As2relResultWithName> = results
                    .iter()
                    .map(|r| As2relResultWithName {
                        asn1: r.asn1,
                        asn2: r.asn2,
                        asn2_name: format_name(&r.asn2_name, truncate_names),
                        connected: r.connected.clone(),
                        peer: r.peer.clone(),
                        as1_upstream: r.as1_upstream.clone(),
                        as2_upstream: r.as2_upstream.clone(),
                    })
                    .collect();
                println!("{}", Table::new(display).with(Style::markdown()));
            } else {
                let display: Vec<As2relResult> = results
                    .iter()
                    .map(|r| As2relResult {
                        asn1: r.asn1,
                        asn2: r.asn2,
                        connected: r.connected.clone(),
                        peer: r.peer.clone(),
                        as1_upstream: r.as1_upstream.clone(),
                        as2_upstream: r.as2_upstream.clone(),
                    })
                    .collect();
                println!("{}", Table::new(display).with(Style::markdown()));
            }
        }
        OutputFormat::Json => {
            let output = build_json_output(&results, show_name, max_peers);
            match serde_json::to_string(&output) {
                Ok(json) => println!("{}", json),
                Err(e) => eprintln!("ERROR: Failed to serialize to JSON: {}", e),
            }
        }
        OutputFormat::JsonPretty => {
            let output = build_json_output(&results, show_name, max_peers);
            match serde_json::to_string_pretty(&output) {
                Ok(json) => println!("{}", json),
                Err(e) => eprintln!("ERROR: Failed to serialize to JSON: {}", e),
            }
        }
        OutputFormat::JsonLine => {
            for r in &results {
                let obj = if show_name {
                    json!({
                        "asn1": r.asn1,
                        "asn2": r.asn2,
                        "asn2_name": r.asn2_name.as_deref().unwrap_or(""),
                        "connected": &r.connected,
                        "peer": &r.peer,
                        "as1_upstream": &r.as1_upstream,
                        "as2_upstream": &r.as2_upstream,
                    })
                } else {
                    json!({
                        "asn1": r.asn1,
                        "asn2": r.asn2,
                        "connected": &r.connected,
                        "peer": &r.peer,
                        "as1_upstream": &r.as1_upstream,
                        "as2_upstream": &r.as2_upstream,
                    })
                };
                match serde_json::to_string(&obj) {
                    Ok(json) => println!("{}", json),
                    Err(e) => eprintln!("ERROR: Failed to serialize to JSON: {}", e),
                }
            }
        }
        OutputFormat::Psv => {
            if show_name {
                println!("asn1|asn2|asn2_name|connected|peer|as1_upstream|as2_upstream");
                for r in &results {
                    println!(
                        "{}|{}|{}|{}|{}|{}|{}",
                        r.asn1,
                        r.asn2,
                        r.asn2_name.as_deref().unwrap_or(""),
                        r.connected,
                        r.peer,
                        r.as1_upstream,
                        r.as2_upstream
                    );
                }
            } else {
                println!("asn1|asn2|connected|peer|as1_upstream|as2_upstream");
                for r in &results {
                    println!(
                        "{}|{}|{}|{}|{}|{}",
                        r.asn1, r.asn2, r.connected, r.peer, r.as1_upstream, r.as2_upstream
                    );
                }
            }
        }
    }
}

fn format_name(name: &Option<String>, truncate: bool) -> String {
    let name = name.as_deref().unwrap_or("");
    if truncate {
        truncate_name(name, DEFAULT_NAME_MAX_LEN)
    } else {
        name.to_string()
    }
}

fn build_json_output(
    results: &[monocle::lens::as2rel::As2relSearchResult],
    show_name: bool,
    max_peers: u32,
) -> serde_json::Value {
    let json_results: Vec<_> = results
        .iter()
        .map(|r| {
            if show_name {
                json!({
                    "asn1": r.asn1,
                    "asn2": r.asn2,
                    "asn2_name": r.asn2_name.as_deref().unwrap_or(""),
                    "connected": &r.connected,
                    "peer": &r.peer,
                    "as1_upstream": &r.as1_upstream,
                    "as2_upstream": &r.as2_upstream,
                })
            } else {
                json!({
                    "asn1": r.asn1,
                    "asn2": r.asn2,
                    "connected": &r.connected,
                    "peer": &r.peer,
                    "as1_upstream": &r.as1_upstream,
                    "as2_upstream": &r.as2_upstream,
                })
            }
        })
        .collect();

    json!({
        "max_peers_count": max_peers,
        "results": json_results,
    })
}