nlink 0.15.1

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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Integration tests for the per-peer impairment helper.
//!
//! These require root + a kernel with `cls_flower` and `sch_netem` loaded.

use std::{net::Ipv4Addr, time::Duration};

use nlink::netlink::{
    impair::{PeerImpairment, PerPeerImpairer},
    link::DummyLink,
    tc::NetemConfig,
};

use crate::common::TestNamespace;

fn netem_50ms() -> NetemConfig {
    NetemConfig::new().delay(Duration::from_millis(50)).build()
}

#[tokio::test]
async fn test_apply_creates_full_tree() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_apply")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 2).into(), netem_50ms())
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 3).into(), netem_50ms())
        .apply(&conn)
        .await?;

    // Root HTB present.
    let qdiscs = conn.get_qdiscs_by_index(ifindex).await?;
    assert!(
        qdiscs
            .iter()
            .any(|q| q.kind() == Some("htb") && q.is_root()),
        "root HTB should exist"
    );

    // 4 netem leaves: one per rule + one default (since no default
    // impairment specified, we don't add a netem leaf for the default
    // class — adjust: exactly 3 netem leaves expected)
    let netem_count = qdiscs.iter().filter(|q| q.kind() == Some("netem")).count();
    assert_eq!(
        netem_count, 3,
        "expected 3 netem leaves (one per rule, no default impairment)"
    );

    // 5 classes total: 1:1 root + 1:2..1:4 per rule + 1:5 default.
    let classes = conn.get_classes_by_index(ifindex).await?;
    let htb_classes = classes.iter().filter(|c| c.kind() == Some("htb")).count();
    assert_eq!(
        htb_classes, 5,
        "expected 5 HTB classes (1 parent + 3 rules + 1 default)"
    );

    // 3 flower filters at parent 1:.
    let filters = conn
        .get_filters_by_parent_index(ifindex, nlink::TcHandle::major_only(1))
        .await?;
    let flower_filters = filters
        .iter()
        .filter(|f| f.kind() == Some("flower"))
        .count();
    assert_eq!(flower_filters, 3, "expected 3 flower filters at parent 1:");

    Ok(())
}

#[tokio::test]
async fn test_apply_with_default_impairment_adds_default_leaf() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_default")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .default_impairment(NetemConfig::new().delay(Duration::from_millis(20)).build())
        .apply(&conn)
        .await?;

    let qdiscs = conn.get_qdiscs_by_index(ifindex).await?;
    let netem_count = qdiscs.iter().filter(|q| q.kind() == Some("netem")).count();
    assert_eq!(
        netem_count, 2,
        "expected 2 netem leaves (1 rule + 1 default impairment)"
    );

    Ok(())
}

#[tokio::test]
async fn test_apply_no_default_means_no_default_leaf() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_no_default")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .apply(&conn)
        .await?;

    let qdiscs = conn.get_qdiscs_by_index(ifindex).await?;
    let netem_count = qdiscs.iter().filter(|q| q.kind() == Some("netem")).count();
    assert_eq!(
        netem_count, 1,
        "expected 1 netem leaf (rule only, no default impairment)"
    );

    Ok(())
}

#[tokio::test]
async fn test_apply_idempotent() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_idempotent")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    let imp = PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 2).into(), netem_50ms());

    imp.apply(&conn).await?;
    let first_filter_count = conn
        .get_filters_by_parent_index(ifindex, nlink::TcHandle::major_only(1))
        .await?
        .iter()
        .filter(|f| f.kind() == Some("flower"))
        .count();

    // Apply again — should give the same shape.
    imp.apply(&conn).await?;
    let second_filter_count = conn
        .get_filters_by_parent_index(ifindex, nlink::TcHandle::major_only(1))
        .await?
        .iter()
        .filter(|f| f.kind() == Some("flower"))
        .count();

    assert_eq!(first_filter_count, second_filter_count);
    assert_eq!(first_filter_count, 2);

    Ok(())
}

#[tokio::test]
async fn test_clear_removes_all() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_clear")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    let imp = PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms());

    imp.apply(&conn).await?;
    assert!(
        conn.get_qdiscs_by_index(ifindex)
            .await?
            .iter()
            .any(|q| q.kind() == Some("htb")),
        "HTB should exist after apply"
    );

    imp.clear(&conn).await?;
    assert!(
        !conn
            .get_qdiscs_by_index(ifindex)
            .await?
            .iter()
            .any(|q| q.kind() == Some("htb")),
        "HTB should be removed after clear"
    );

    // clear() is idempotent — second call is a no-op.
    imp.clear(&conn).await?;

    Ok(())
}

#[tokio::test]
async fn test_apply_with_ipv6_match() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_v6")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    PerPeerImpairer::new("test0")
        .impair_dst_subnet("2001:db8::/32", netem_50ms())?
        .apply(&conn)
        .await?;

    let filters = conn
        .get_filters_by_parent_index(ifindex, nlink::TcHandle::major_only(1))
        .await?;
    let flower_filters: Vec<_> = filters
        .iter()
        .filter(|f| f.kind() == Some("flower"))
        .collect();
    assert_eq!(flower_filters.len(), 1, "one flower filter expected");

    Ok(())
}

#[tokio::test]
async fn test_apply_with_dst_mac_match() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_mac")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    PerPeerImpairer::new("test0")
        .impair_dst_mac([0x52, 0x54, 0x00, 0x12, 0x34, 0x56], netem_50ms())
        .apply(&conn)
        .await?;

    let filters = conn
        .get_filters_by_parent_index(ifindex, nlink::TcHandle::major_only(1))
        .await?;
    assert!(
        filters.iter().any(|f| f.kind() == Some("flower")),
        "flower filter for MAC match should exist"
    );

    Ok(())
}

#[tokio::test]
async fn test_apply_by_index_constructor() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_byidx")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    PerPeerImpairer::new_by_index(ifindex)
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .apply(&conn)
        .await?;

    let qdiscs = conn.get_qdiscs_by_index(ifindex).await?;
    assert!(
        qdiscs.iter().any(|q| q.kind() == Some("htb")),
        "tree should be created when constructed by ifindex"
    );

    Ok(())
}

#[tokio::test]
async fn test_rate_cap_per_rule() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_ratecap")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    PerPeerImpairer::new("test0")
        .impair_dst_ip(
            Ipv4Addr::new(10, 0, 0, 1).into(),
            PeerImpairment::new(netem_50ms()).rate_cap(nlink::Rate::mbit(100)),
        )
        .apply(&conn)
        .await?;

    let classes = conn.get_classes_by_index(ifindex).await?;
    let htb_classes: Vec<_> = classes.iter().filter(|c| c.kind() == Some("htb")).collect();
    // 1 parent + 1 rule + 1 default = 3 HTB classes
    assert_eq!(htb_classes.len(), 3, "expected 3 HTB classes with rate cap");

    Ok(())
}

// ============================================================================
// Reconcile tests
// ============================================================================

#[tokio::test]
async fn test_reconcile_first_call_creates_tree() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_reconcile_first")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    let report = PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 2).into(), netem_50ms())
        .reconcile(&conn)
        .await?;

    assert!(report.changes_made > 0, "first reconcile must mutate");
    assert_eq!(report.rules_added, 2);
    assert!(report.root_modified);

    // Tree exists.
    let qdiscs = conn.get_qdiscs_by_index(ifindex).await?;
    assert!(
        qdiscs
            .iter()
            .any(|q| q.kind() == Some("htb") && q.is_root())
    );
    assert_eq!(
        qdiscs.iter().filter(|q| q.kind() == Some("netem")).count(),
        2,
    );
    Ok(())
}

#[tokio::test]
async fn test_reconcile_idempotent() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_reconcile_idem")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;

    let imp = PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 2).into(), netem_50ms());

    let r1 = imp.reconcile(&conn).await?;
    assert!(r1.changes_made > 0);

    let r2 = imp.reconcile(&conn).await?;
    assert!(
        r2.is_noop(),
        "second reconcile should be a no-op (got {} changes: {:?})",
        r2.changes_made,
        r2,
    );
    Ok(())
}

#[tokio::test]
async fn test_reconcile_modify_netem() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_reconcile_mod")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;

    let imp_a = PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms());
    imp_a.reconcile(&conn).await?;

    // Now bump the delay and reconcile.
    let imp_b = PerPeerImpairer::new("test0").impair_dst_ip(
        Ipv4Addr::new(10, 0, 0, 1).into(),
        NetemConfig::new().delay(Duration::from_millis(120)).build(),
    );
    let r = imp_b.reconcile(&conn).await?;
    assert_eq!(
        r.rules_modified, 1,
        "rule should be modified, not added/removed (report: {:?})",
        r,
    );
    assert_eq!(r.rules_added, 0);
    assert_eq!(r.rules_removed, 0);
    Ok(())
}

#[tokio::test]
async fn test_reconcile_remove_rule() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_reconcile_rm")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;

    PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 2).into(), netem_50ms())
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 3).into(), netem_50ms())
        .reconcile(&conn)
        .await?;

    // Reconcile a 2-rule version — should remove the third.
    let r = PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 2).into(), netem_50ms())
        .reconcile(&conn)
        .await?;
    assert!(
        r.rules_removed >= 1,
        "expected at least 1 rule removed: {r:?}"
    );
    Ok(())
}

#[tokio::test]
async fn test_reconcile_dry_run_makes_no_changes() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_reconcile_dry")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    let report = PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .reconcile_dry_run(&conn)
        .await?;

    assert!(report.dry_run);
    assert!(report.changes_made > 0, "would-do count should be > 0");

    // No qdisc was actually installed.
    let qdiscs = conn.get_qdiscs_by_index(ifindex).await?;
    assert!(
        qdiscs.iter().all(|q| q.kind() != Some("htb")),
        "dry-run installed an HTB qdisc",
    );
    Ok(())
}

#[tokio::test]
async fn test_reconcile_wrong_root_kind_errors() -> nlink::Result<()> {
    require_root!();
    use nlink::netlink::tc::PrioConfig;

    let ns = TestNamespace::new("impair_reconcile_wrongroot")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;

    // Install a non-HTB qdisc at root manually.
    conn.add_qdisc_full(
        "test0",
        nlink::TcHandle::ROOT,
        Some(nlink::TcHandle::major_only(1)),
        PrioConfig::new().build(),
    )
    .await?;

    let r = PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .reconcile(&conn)
        .await;
    assert!(r.is_err(), "expected error for wrong root kind, got {r:?}");
    Ok(())
}

#[tokio::test]
async fn test_reconcile_with_fallback_to_apply() -> nlink::Result<()> {
    require_root!();
    use nlink::ReconcileOptions;
    use nlink::netlink::tc::PrioConfig;

    let ns = TestNamespace::new("impair_reconcile_fallback")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    // Wrong root.
    conn.add_qdisc_full(
        "test0",
        nlink::TcHandle::ROOT,
        Some(nlink::TcHandle::major_only(1)),
        PrioConfig::new().build(),
    )
    .await?;

    PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .reconcile_with_options(&conn, ReconcileOptions::new().with_fallback_to_apply(true))
        .await?;

    let qdiscs = conn.get_qdiscs_by_index(ifindex).await?;
    assert!(
        qdiscs
            .iter()
            .any(|q| q.kind() == Some("htb") && q.is_root()),
        "fallback should have rebuilt the HTB tree",
    );
    Ok(())
}

#[tokio::test]
async fn test_get_filters_by_parent_filters_correctly() -> nlink::Result<()> {
    require_root!();

    let ns = TestNamespace::new("impair_byparent")?;
    let conn = ns.connection()?;

    conn.add_link(DummyLink::new("test0")).await?;
    conn.set_link_up("test0").await?;
    let link = conn.get_link_by_name("test0").await?.expect("dummy exists");
    let ifindex = link.ifindex();

    PerPeerImpairer::new("test0")
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 1).into(), netem_50ms())
        .impair_dst_ip(Ipv4Addr::new(10, 0, 0, 2).into(), netem_50ms())
        .apply(&conn)
        .await?;

    // All filters at parent 1: should be the helper's flower filters.
    let at_root = conn
        .get_filters_by_parent_index(ifindex, nlink::TcHandle::major_only(1))
        .await?;
    assert_eq!(at_root.len(), 2, "expected 2 filters at parent 1:");
    assert!(at_root.iter().all(|f| f.kind() == Some("flower")));

    // No filters at parent 2: (a parent that doesn't exist).
    let at_other = conn
        .get_filters_by_parent_index(ifindex, nlink::TcHandle::major_only(2))
        .await?;
    assert!(at_other.is_empty(), "no filters expected at parent 2:");

    Ok(())
}