nlink 0.19.0

Async netlink library for Linux network configuration
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
//! Integration tests for the diagnostics module.

use nlink::netlink::diagnostics::{
    BottleneckType, Diagnostics, DiagnosticsConfig, IssueCategory, LinkRates, Severity,
};

use crate::common::TestNamespace;

// ============================================================================
// Unit Tests (no network namespace required)
// ============================================================================

#[test]
fn test_severity_ordering() {
    assert!(Severity::Info < Severity::Warning);
    assert!(Severity::Warning < Severity::Error);
    assert!(Severity::Error < Severity::Critical);
}

#[test]
fn test_severity_display() {
    assert_eq!(format!("{}", Severity::Info), "INFO");
    assert_eq!(format!("{}", Severity::Warning), "WARN");
    assert_eq!(format!("{}", Severity::Error), "ERROR");
    assert_eq!(format!("{}", Severity::Critical), "CRITICAL");
}

#[test]
fn test_issue_category_display() {
    assert_eq!(format!("{}", IssueCategory::LinkDown), "LinkDown");
    assert_eq!(format!("{}", IssueCategory::NoCarrier), "NoCarrier");
    assert_eq!(
        format!("{}", IssueCategory::HighPacketLoss),
        "HighPacketLoss"
    );
    assert_eq!(format!("{}", IssueCategory::QdiscDrops), "QdiscDrops");
    assert_eq!(format!("{}", IssueCategory::NoRoute), "NoRoute");
}

#[test]
fn test_link_rates() {
    let rates = LinkRates {
        rx_bps: 1000,
        tx_bps: 2000,
        rx_pps: 10,
        tx_pps: 20,
        sample_duration_ms: 1000,
    };

    assert_eq!(rates.total_bps(), 3000);
    assert_eq!(rates.total_pps(), 30);
}

#[test]
fn test_link_rates_default() {
    let rates = LinkRates::default();
    assert_eq!(rates.rx_bps, 0);
    assert_eq!(rates.tx_bps, 0);
    assert_eq!(rates.total_bps(), 0);
}

#[test]
fn test_config_defaults() {
    let config = DiagnosticsConfig::default();
    assert_eq!(config.packet_loss_threshold, 0.01);
    assert_eq!(config.error_rate_threshold, 0.001);
    assert_eq!(config.qdisc_drop_threshold, 0.01);
    assert_eq!(config.backlog_threshold, 100_000);
    assert_eq!(config.qlen_threshold, 1000);
    assert!(config.skip_loopback);
    assert!(!config.skip_down);
    assert_eq!(config.min_bytes_for_rate, 1000);
}

#[test]
fn test_bottleneck_type_display() {
    assert_eq!(format!("{}", BottleneckType::QdiscDrops), "Qdisc Drops");
    assert_eq!(
        format!("{}", BottleneckType::InterfaceDrops),
        "Interface Drops"
    );
    assert_eq!(format!("{}", BottleneckType::BufferFull), "Buffer Full");
    assert_eq!(format!("{}", BottleneckType::RateLimited), "Rate Limited");
    assert_eq!(
        format!("{}", BottleneckType::HardwareErrors),
        "Hardware Errors"
    );
}

// ============================================================================
// Integration Tests (require network namespace — root-gated)
//
// Migrated from `#[ignore]` to `nlink::require_root!()` in 0.17
// (Plan 179) so they run under privileged CI but skip cleanly on
// non-root developer runs.
// ============================================================================

#[tokio::test]
async fn test_diagnostics_scan() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_scan")?;

    // Create a dummy interface
    ns.add_dummy("dummy0")?;
    ns.link_up("dummy0")?;
    ns.add_addr("dummy0", "10.0.0.1/24")?;

    // Create diagnostics runner
    let conn = ns.connection()?;
    let diag = Diagnostics::new(conn);

    // Run scan
    let report = diag.scan().await?;

    // Verify we got results
    assert!(!report.interfaces.is_empty());

    // Find our dummy interface
    let dummy = report
        .interfaces
        .iter()
        .find(|i| i.name == "dummy0")
        .expect("dummy0 not found in report");

    assert_eq!(dummy.name, "dummy0");
    assert!(dummy.mtu.is_some());
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_scan_interface() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_scan_if")?;

    // Create a dummy interface
    ns.add_dummy("eth0")?;
    ns.link_up("eth0")?;
    ns.add_addr("eth0", "192.168.1.1/24")?;

    let conn = ns.connection()?;
    let diag = Diagnostics::new(conn);

    // Scan specific interface
    let iface = diag.scan_interface("eth0").await?;

    assert_eq!(iface.name, "eth0");
    assert!(iface.mtu.is_some());
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_scan_interface_not_found() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_notfound")?;

    let conn = ns.connection()?;
    let diag = Diagnostics::new(conn);

    // Try to scan non-existent interface
    let result = diag.scan_interface("nonexistent0").await;
    assert!(result.is_err());

    let err = result.unwrap_err();
    assert!(err.is_not_found());
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_check_connectivity_no_route() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_conn")?;

    // Create a dummy interface without any routes
    ns.add_dummy("eth0")?;
    ns.link_up("eth0")?;

    let conn = ns.connection()?;
    let diag = Diagnostics::new(conn);

    // Check connectivity to external IP - should fail (no route)
    let report = diag
        .check_connectivity("8.8.8.8".parse().unwrap())
        .await?;

    // Should have a NoRoute issue
    assert!(!report.issues.is_empty());
    assert!(
        report
            .issues
            .iter()
            .any(|i| i.category == IssueCategory::NoRoute)
    );
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_check_connectivity_with_route() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_route")?;

    // Create interface with address and default route
    ns.add_dummy("eth0")?;
    ns.link_up("eth0")?;
    ns.add_addr("eth0", "192.168.1.1/24")?;
    // Add a default route (may fail if kernel requires a real gateway)
    let _ = ns.exec("ip", &["route", "add", "default", "via", "192.168.1.254"]);

    let conn = ns.connection()?;
    let diag = Diagnostics::new(conn);

    // Check connectivity to local subnet - should have a route
    let report = diag
        .check_connectivity("192.168.1.100".parse().unwrap())
        .await?;

    // Should find a route (even if not the default)
    assert!(
        report.route.is_some() || report.issues.is_empty(),
        "Expected route or no issues"
    );
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_find_bottleneck() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_bottle")?;

    // Create a dummy interface
    ns.add_dummy("eth0")?;
    ns.link_up("eth0")?;

    let conn = ns.connection()?;
    let diag = Diagnostics::new(conn);

    // Find bottleneck - likely none on a fresh interface
    let bottleneck = diag.find_bottleneck().await?;

    // Fresh interface shouldn't have a bottleneck
    // (unless there's a pre-existing issue)
    if let Some(b) = bottleneck {
        println!("Found bottleneck: {} ({:?})", b.location, b.bottleneck_type);
    }
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_with_tc() -> nlink::Result<()> {
    nlink::require_root!();
    nlink::require_module!("sch_htb");
    let ns = TestNamespace::new("diag_tc")?;

    // Create a dummy interface with TC
    ns.add_dummy("eth0")?;
    ns.link_up("eth0")?;

    // Add a qdisc
    ns.exec_ignore(
        "tc",
        &[
            "qdisc", "add", "dev", "eth0", "root", "handle", "1:", "htb", "default", "10",
        ],
    );

    let conn = ns.connection()?;
    let diag = Diagnostics::new(conn);

    let report = diag.scan().await?;

    // Find eth0 and check TC info
    let eth0 = report
        .interfaces
        .iter()
        .find(|i| i.name == "eth0")
        .expect("eth0 not found in report");

    if let Some(tc) = &eth0.tc {
        assert_eq!(tc.qdisc, "htb");
    }
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_link_down_detection() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_down")?;

    // Create a dummy interface but leave it down
    ns.add_dummy("eth0")?;
    // Don't bring it up

    let conn = ns.connection()?;

    // Use config that doesn't skip down interfaces
    let config = DiagnosticsConfig {
        skip_down: false,
        ..Default::default()
    };

    let diag = Diagnostics::with_config(conn, config);

    let report = diag.scan().await?;

    // Find eth0
    let eth0 = report
        .interfaces
        .iter()
        .find(|i| i.name == "eth0")
        .expect("eth0 not found in report");

    // Should have LinkDown issue
    assert!(
        eth0.issues
            .iter()
            .any(|i| i.category == IssueCategory::LinkDown)
    );
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_no_address_detection() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_noaddr")?;

    // Create interface without an IPv4 address. After link-up
    // the kernel auto-assigns an IPv6 link-local fe80::/64
    // (SLAAC) on modern kernels, which would count as an
    // address and suppress the `NoAddress` issue the test
    // means to verify. Flush IPv6 addrs post-up. There's no
    // RA source in this isolated namespace, so SLAAC won't
    // re-add anything.
    //
    // Avoid `sysctl(8)` here — the CI container
    // (`rust:bookworm` per integration-tests.yml) installs only
    // `iproute2 kmod conntrack`; `procps` (sysctl) isn't there.
    // `ip` is. (Plan 179.)
    ns.add_dummy("eth0")?;
    ns.link_up("eth0")?;
    let _ = ns.exec("ip", &["-6", "addr", "flush", "dev", "eth0"]);

    let conn = ns.connection()?;
    let diag = Diagnostics::new(conn);

    let report = diag.scan().await?;

    let eth0 = report
        .interfaces
        .iter()
        .find(|i| i.name == "eth0")
        .expect("eth0 not found in report");

    assert!(
        eth0.issues
            .iter()
            .any(|i| i.category == IssueCategory::NoAddress),
        "expected NoAddress issue; got issues={:?}",
        eth0.issues.iter().map(|i| &i.category).collect::<Vec<_>>(),
    );
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_route_summary() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_routes")?;

    // Create interface and add routes
    ns.add_dummy("eth0")?;
    ns.link_up("eth0")?;
    ns.add_addr("eth0", "10.0.0.1/24")?;
    ns.exec("ip", &["route", "add", "192.168.0.0/16", "dev", "eth0"])?;

    let conn = ns.connection()?;
    let diag = Diagnostics::new(conn);

    let report = diag.scan().await?;

    // Check route diagnostics
    assert!(report.routes.ipv4_route_count >= 1);
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_custom_config() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_config")?;

    ns.add_dummy("eth0")?;
    ns.link_up("eth0")?;

    let conn = ns.connection()?;

    // Custom config with stricter thresholds
    let config = DiagnosticsConfig {
        packet_loss_threshold: 0.001, // 0.1%
        error_rate_threshold: 0.0001, // 0.01%
        skip_loopback: true,
        skip_down: true,
        ..Default::default()
    };

    let diag = Diagnostics::with_config(conn, config);

    assert_eq!(diag.config().packet_loss_threshold, 0.001);
    assert_eq!(diag.config().error_rate_threshold, 0.0001);

    let report = diag.scan().await?;
    assert!(!report.interfaces.is_empty());
    Ok(())
}

#[tokio::test]
async fn test_diagnostics_skip_loopback() -> nlink::Result<()> {
    nlink::require_root!();
    let ns = TestNamespace::new("diag_lo")?;

    let conn = ns.connection()?;

    // Default config skips loopback
    let diag = Diagnostics::new(conn);
    let report = diag.scan().await?;

    // lo should not be in the results
    assert!(!report.interfaces.iter().any(|i| i.name == "lo"));
    Ok(())
}