-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest.rs
More file actions
4093 lines (3686 loc) · 135 KB
/
test.rs
File metadata and controls
4093 lines (3686 loc) · 135 KB
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use crate::{
config::{PeerConfig, RouterConfig},
connection::{BgpConnection, BgpListener},
connection_channel::{BgpConnectionChannel, BgpListenerChannel},
connection_tcp::{BgpConnectionTcp, BgpListenerTcp},
dispatcher::Dispatcher,
params::{Ipv4UnicastConfig, Ipv6UnicastConfig, JitterRange},
router::{EnsureSessionResult, Router},
session::{
AdminEvent, ConnectionKind, FsmEvent, FsmStateKind, PeerId,
SessionEndpoint, SessionInfo, SessionRunner,
},
unnumbered::UnnumberedManager,
unnumbered_mock::UnnumberedManagerMock,
};
use lazy_static::lazy_static;
use mg_common::log::init_file_logger;
use mg_common::test::{IpAllocation, LoopbackIpManager};
use mg_common::*;
use rdb::{Asn, ImportExportPolicy4, ImportExportPolicy6, Prefix, Prefix4};
use std::{
collections::{BTreeMap, BTreeSet},
net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6},
sync::{
Arc, Mutex,
atomic::{AtomicU32, Ordering},
mpsc::channel,
},
thread::{Builder, sleep},
time::{Duration, Instant},
};
// Use non-standard port outside the privileged range to avoid needing privs
const TEST_BGP_PORT: u16 = 10179;
// =============================================================================
// Test timer configuration
// =============================================================================
// All tests use these same BGP timer values. Verification durations are derived
// from these to ensure tests wait long enough without excessive duration.
/// Standard connect_retry timer used by all tests
const TEST_CONNECT_RETRY_SECS: u64 = 1;
/// Standard hold_time used by all tests
const TEST_HOLD_TIME_SECS: u64 = 6;
/// Duration to verify sessions don't establish when they shouldn't.
/// Waits for 3 connect_retry cycles - if FSM was going to incorrectly
/// attempt a connection, it would have done so by now.
const CONNECT_RETRY_VERIFICATION: Duration =
Duration::from_secs(TEST_CONNECT_RETRY_SECS * 3);
/// Duration to verify established sessions stay established.
/// Waits slightly longer than hold_time to ensure keepalives are being
/// exchanged properly and the session doesn't timeout.
const ESTABLISHED_VERIFICATION: Duration =
Duration::from_secs(TEST_HOLD_TIME_SECS + 2);
// XXX: add an iBGP option for the tests
// XXX: Add test impl of BgpConnection (and Clock?) for FSM tests.
// The DUT will still have a SessionRunner & timers, but the test peer will
// be simulated by test code + will inject different events into the DUT's
// FSM event queue so we can test all events in each state. We should have
// explicit expectations for how every possible event is handled in every
// FSM state. Test each state like there's a `match` for events.
// We also need to add tests for IdleHoldTimer and DampPeerOscillations.
lazy_static! {
static ref LOOPBACK_MANAGER: Arc<Mutex<LoopbackIpManager>> = {
let ifname = if cfg!(target_os = "macos") || cfg!(target_os = "illumos")
{
"lo0"
} else if cfg!(target_os = "linux") {
"lo"
} else {
panic!("unsupported platform");
};
// Extract test name from thread name for per-test log files.
// With cargo nextest, each test runs in its own process, so this
// will be unique per test process.
let thread_name = std::thread::current();
let test_name = thread_name
.name()
.and_then(|name| name.split("::").last())
.unwrap_or("unknown");
let log_filename = format!("loopback-manager.{}.log", test_name);
let log = init_file_logger(&log_filename);
Arc::new(Mutex::new(LoopbackIpManager::new(ifname, log)))
};
}
/// Ensure test IP addresses are available for TCP tests
/// Returns a guard that will clean up the IPs when dropped
fn ensure_loop_ips(addresses: &[IpAddr]) -> IpAllocation {
lazy_static::initialize(&LOOPBACK_MANAGER);
mg_common::test::LoopbackIpManager::allocate(
LOOPBACK_MANAGER.clone(),
addresses,
)
.expect("failed to create loopback manager")
}
struct TestRouter<Cnx: BgpConnection + 'static> {
router: Arc<Router<Cnx>>,
dispatcher: Arc<Dispatcher<Cnx>>,
}
impl<Cnx: BgpConnection + 'static> TestRouter<Cnx> {
fn shutdown(&self) {
self.router.shutdown();
self.dispatcher.shutdown();
}
fn run<Listener: BgpListener<Cnx> + 'static>(&self) {
self.router.run();
let d = self.dispatcher.clone();
let listen_addr = self.dispatcher.listen_addr().to_string();
let listen_addr_for_log = listen_addr.clone();
eprintln!("Spawning Dispatcher thread for {}", listen_addr);
Builder::new()
.name(format!("bgp-listener-{}", listen_addr))
.spawn(move || {
d.run::<Listener>();
eprintln!(
"Dispatcher thread for {} exiting",
listen_addr_for_log
);
})
.expect("failed to spawn dispatcher thread");
}
}
/// Test-specific enum describing which route address families are exchanged
/// in a BGP session. This is independent of the TCP/IP connection address.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RouteExchange {
Ipv4 {
nexthop: Option<IpAddr>,
},
Ipv6 {
nexthop: Option<IpAddr>,
},
DualStack {
ipv4_nexthop: Option<IpAddr>,
ipv6_nexthop: Option<IpAddr>,
},
}
struct LogicalRouter {
name: String,
asn: Asn,
id: u32,
listen_addr: SocketAddr,
bind_addr: Option<SocketAddr>,
neighbors: Vec<NeighborConfig>,
}
struct NeighborConfig {
peer_name: String,
remote_host: SocketAddr,
session_info: SessionInfo,
}
/// Create SessionInfo for tests with fixed timer values and route exchange configuration.
/// This constructs SessionInfo directly without using PeerConfig.
///
/// # Arguments
/// * `route_exchange` - Which route address families to exchange
/// * `local_addr` - Local bind address for this session
/// * `remote_addr` - Remote peer address (for nexthop defaults)
/// * `passive` - Whether to use passive TCP establishment
fn create_test_session_info(
route_exchange: RouteExchange,
local_addr: SocketAddr,
remote_addr: SocketAddr,
passive: bool,
) -> SessionInfo {
// Derive AF configuration from route_exchange
// Use remote_addr for nexthop defaults (what this router advertises)
let (ipv4_unicast, ipv6_unicast) = match route_exchange {
RouteExchange::Ipv4 { nexthop } => {
let ipv4_cfg = Ipv4UnicastConfig {
nexthop: nexthop.or_else(|| {
if remote_addr.is_ipv4() {
Some(remote_addr.ip())
} else {
None
}
}),
import_policy: ImportExportPolicy4::default(),
export_policy: ImportExportPolicy4::default(),
};
(Some(ipv4_cfg), None)
}
RouteExchange::Ipv6 { nexthop } => {
let ipv6_cfg = Ipv6UnicastConfig {
nexthop: nexthop.or_else(|| {
if remote_addr.is_ipv6() {
Some(remote_addr.ip())
} else {
None
}
}),
import_policy: ImportExportPolicy6::NoFiltering,
export_policy: ImportExportPolicy6::NoFiltering,
};
(None, Some(ipv6_cfg))
}
RouteExchange::DualStack {
ipv4_nexthop,
ipv6_nexthop,
} => {
let ipv4_cfg = Ipv4UnicastConfig {
nexthop: ipv4_nexthop.or_else(|| {
if remote_addr.is_ipv4() {
Some(remote_addr.ip())
} else {
None
}
}),
import_policy: ImportExportPolicy4::default(),
export_policy: ImportExportPolicy4::default(),
};
let ipv6_cfg = Ipv6UnicastConfig {
nexthop: ipv6_nexthop.or_else(|| {
if remote_addr.is_ipv6() {
Some(remote_addr.ip())
} else {
None
}
}),
import_policy: ImportExportPolicy6::NoFiltering,
export_policy: ImportExportPolicy6::NoFiltering,
};
(Some(ipv4_cfg), Some(ipv6_cfg))
}
};
// Construct SessionInfo directly with fixed test values
SessionInfo {
passive_tcp_establishment: passive,
remote_asn: None,
remote_id: None,
bind_addr: Some(local_addr),
min_ttl: None,
md5_auth_key: None,
multi_exit_discriminator: None,
communities: BTreeSet::new(),
local_pref: None,
enforce_first_as: false,
ipv4_unicast,
ipv6_unicast,
vlan_id: None,
// Fixed test timer values
connect_retry_time: Duration::from_secs(1),
keepalive_time: Duration::from_secs(3),
hold_time: Duration::from_secs(6),
idle_hold_time: Duration::from_secs(0),
delay_open_time: Duration::from_secs(0),
resolution: Duration::from_millis(100),
connect_retry_jitter: None,
idle_hold_jitter: Some(JitterRange {
min: 0.75,
max: 1.0,
}),
deterministic_collision_resolution: false,
}
}
fn test_setup<Cnx, Listener>(
test_name: &str,
routers: &[LogicalRouter],
) -> (Vec<TestRouter<Cnx>>, Option<IpAllocation>)
where
Cnx: BgpConnection + Send + 'static,
Listener: BgpListener<Cnx> + 'static,
{
std::fs::create_dir_all("/tmp").expect("create tmp dir");
let mut test_routers = Vec::with_capacity(routers.len());
let mut session_senders = Vec::new();
let mut ip_addresses = Vec::new();
// Manage local addresses for TCP tests
let ip_guard = if std::any::type_name::<Cnx>().contains("Tcp") {
routers
.iter()
.for_each(|lr| ip_addresses.push(lr.listen_addr.ip()));
Some(ensure_loop_ips(&ip_addresses))
} else {
None
};
// Extract the actual test function name from the thread name.
// The Rust test harness names threads like "test::test_function_name".
// This ensures each test function gets its own database, even if helpers
// are called with identical parameters by different tests.
let thread_name = std::thread::current();
let actual_test_name = thread_name
.name()
.and_then(|name| name.split("::").last())
.map(|s| s.to_string())
.unwrap_or_else(|| test_name.to_string());
// Create all routers first
for logical_router in routers.iter() {
let log = init_file_logger(&format!(
"{}.{actual_test_name}.log",
logical_router.name
));
// Create database with unique path per test function
let db_path =
format!("/tmp/{}.{actual_test_name}.db", logical_router.name);
let _ = std::fs::remove_dir_all(&db_path);
let db = rdb::Db::new(&db_path, log.clone()).expect("create db");
// Create dispatcher
// Phase 4: Use PeerId instead of IpAddr
let peer_to_session: Arc<
Mutex<BTreeMap<PeerId, SessionEndpoint<Cnx>>>,
> = Arc::new(Mutex::new(BTreeMap::new()));
let dispatcher = Arc::new(Dispatcher::new(
peer_to_session.clone(),
logical_router.listen_addr.to_string(),
log.clone(),
None, // No unnumbered manager for tests
));
// Create router
let router = Arc::new(Router::new(
RouterConfig {
asn: logical_router.asn,
id: logical_router.id,
},
log.clone(),
db.clone(),
peer_to_session.clone(),
));
// Start router and dispatcher
router.run();
let d = dispatcher.clone();
let listen_addr = dispatcher.listen_addr().to_string();
let listen_addr_for_log = listen_addr.clone();
eprintln!("Spawning Dispatcher thread for {}", listen_addr);
Builder::new()
.name(format!("bgp-listener-{}", listen_addr))
.spawn(move || {
d.run::<Listener>();
eprintln!(
"Dispatcher thread for {} exiting",
listen_addr_for_log
);
})
.expect("failed to spawn dispatcher thread");
// Set up all peer sessions for this router
for neighbor in &logical_router.neighbors {
// Each session gets its own channel pair for FsmEvents
let (event_tx, event_rx) = channel();
// Create PeerConfig from neighbor's configuration for compatibility with new_session
let peer_config = PeerConfig {
name: neighbor.peer_name.clone(),
group: String::new(),
host: neighbor.remote_host,
hold_time: 6,
idle_hold_time: 0,
delay_open: 0,
connect_retry: 1,
keepalive: 3,
resolution: 100,
};
// Use bind_addr IP from LogicalRouter (port 0 so OS picks ephemeral),
// otherwise use listen_addr IP. The source port for outbound connections
// must not conflict with the dispatcher's listen port.
let bind_addr = logical_router
.bind_addr
.map(|addr| SocketAddr::new(addr.ip(), 0))
.unwrap_or_else(|| {
SocketAddr::new(logical_router.listen_addr.ip(), 0)
});
let session_info = neighbor.session_info.clone();
let session_runner = router
.new_session(
peer_config,
Some(bind_addr),
event_tx.clone(),
event_rx,
session_info,
)
.unwrap_or_else(|_| {
panic!("new session on router {}", logical_router.name)
});
// If LogicalRouter.bind_addr is None, clear the bind_addr
// that was just set by new_session (at router.rs:212)
if logical_router.bind_addr.is_none() {
let mut info = lock!(session_runner.session);
info.bind_addr = None;
}
// Store the sender so we can send ManualStart later
session_senders.push(event_tx);
}
// Store components
test_routers.push(TestRouter {
router: router.clone(),
dispatcher,
});
}
// Start all sessions
for session_tx in session_senders {
session_tx
.send(FsmEvent::Admin(AdminEvent::ManualStart))
.expect("send manual start event");
}
(test_routers, ip_guard)
}
// This test effectively does the following:
// 1. Sets up a basic pair of routers, r1 and r2
// - r1 either uses active or passive tcp establishment
// 2. Brings up a BGP session between r1 and r2
// 3. Ensures the BGP FSM moves into Established on both r1 and r2
// 4. Shuts down r2
// 5. Ensures r2's BGP FSM moves into Idle
// 6. Ensures r1's BGP FSM moves into Active (passive tcp establishment)
// or Connect (active tcp establishment)
// 7. Restarts r2
// 8. Ensures the BGP session between r1 and r2 moves back into Established
fn basic_peering_helper<
Cnx: BgpConnection + 'static,
Listener: BgpListener<Cnx> + 'static,
>(
passive: bool,
route_exchange: RouteExchange,
r1_addr: SocketAddr,
r2_addr: SocketAddr,
) {
let is_tcp = std::any::type_name::<Cnx>().contains("Tcp");
let is_ipv6 = r1_addr.ip().is_ipv6();
let test_str = match (passive, is_tcp, is_ipv6) {
(true, true, true) => "basic_peering_passive_tcp_ipv6",
(false, true, true) => "basic_peering_active_tcp_ipv6",
(true, false, true) => "basic_peering_passive_ipv6",
(false, false, true) => "basic_peering_active_ipv6",
(true, true, false) => "basic_peering_passive_tcp",
(false, true, false) => "basic_peering_active_tcp",
(true, false, false) => "basic_peering_passive",
(false, false, false) => "basic_peering_active",
};
let routers = vec![
LogicalRouter {
name: "r1".to_string(),
asn: Asn::FourOctet(4200000001),
id: 1,
listen_addr: r1_addr,
bind_addr: Some(r1_addr),
neighbors: vec![NeighborConfig {
peer_name: "r2".to_string(),
remote_host: r2_addr,
session_info: create_test_session_info(
route_exchange,
r1_addr,
r2_addr,
passive,
),
}],
},
LogicalRouter {
name: "r2".to_string(),
asn: Asn::FourOctet(4200000002),
id: 2,
listen_addr: r2_addr,
bind_addr: Some(r2_addr),
neighbors: vec![NeighborConfig {
peer_name: "r1".to_string(),
remote_host: r1_addr,
session_info: create_test_session_info(
route_exchange,
r2_addr,
r1_addr,
!passive,
),
}],
},
];
let (test_routers, _ip_guard) =
test_setup::<Cnx, Listener>(test_str, &routers);
let r1 = &test_routers[0];
let r2 = &test_routers[1];
let r1_session = r1
.router
.get_session(r2_addr.ip())
.expect("get session one");
let r2_session = r2
.router
.get_session(r1_addr.ip())
.expect("get session two");
// Give peer sessions a few seconds and ensure we have reached the
// established state on both sides.
wait_for_eq!(r1_session.state(), FsmStateKind::Established);
wait_for_eq!(r2_session.state(), FsmStateKind::Established);
// Verify Arc-based connection query API
// Both sessions should report exactly 1 active connection
assert_eq!(
r1_session.connection_count(),
1,
"r1 should have 1 active connection"
);
assert_eq!(
r2_session.connection_count(),
1,
"r2 should have 1 active connection"
);
// Verify primary connection exists and directions are opposite
let r1_primary = r1_session.primary_connection();
assert!(r1_primary.is_some(), "r1 should have primary connection");
let r1_dir = match &r1_primary.unwrap() {
ConnectionKind::Full(pc) => pc.conn.direction(),
ConnectionKind::Partial(c) => c.direction(),
};
let r2_primary = r2_session.primary_connection();
assert!(r2_primary.is_some(), "r2 should have primary connection");
let r2_dir = match &r2_primary.unwrap() {
ConnectionKind::Full(pc) => pc.conn.direction(),
ConnectionKind::Partial(c) => c.direction(),
};
// One should be Outbound and one Inbound (they're using same physical connection)
assert_ne!(r1_dir, r2_dir, "Connection directions should be opposite");
// Verify all_connections contains single connection in both sessions
assert_eq!(
r1_session.connection_count(),
1,
"r1 should have exactly 1 connection"
);
assert_eq!(
r2_session.connection_count(),
1,
"r2 should have exactly 1 connection"
);
// Shut down r2 and ensure that r2's peer session has gone back to idle.
r2.shutdown();
wait_for_eq!(
r2_session.state(),
FsmStateKind::Idle,
"r2 state should be Idle after being shutdown"
);
// Ensure r1's FSM moves through the correct states after the session drops.
// (r1 should see the Hold Time expire after r2 shuts down)
if passive {
// passive means wait for connections, i.e. the FSM moves from
// Idle -> Active when the IdleHoldTimer expires
wait_for_eq!(
r1_session.state(),
FsmStateKind::Active,
"r1 state should move into Active when session uses passive tcp establishment"
);
} else {
// active (!passive) means actively attempt to open a connection, i.e.
// the FSM moves from Idle -> Connect when the IdleHoldTimer expires
wait_for_eq!(
r1_session.state(),
FsmStateKind::Connect,
"r1 state should move into Connect when session uses active tcp establishment"
);
}
r2.run::<Listener>();
r2.router
.send_admin_event(AdminEvent::ManualStart)
.expect("manual start session two");
wait_for_eq!(
{
let state = r1_session.state();
println!("r1_session.state(): {state}");
state
},
FsmStateKind::Established,
"r1 state should move to Established after manual start of r2"
);
wait_for_eq!(
r2_session.state(),
FsmStateKind::Established,
"r2 state should move to Established after manual start"
);
// Clean up properly
r1.shutdown();
r2.shutdown();
}
// This test does the following:
// 1. Sets up a basic pair of routers
// 2. Configures r1 to originate prefix(es) based on route_exchange
// 3. Brings up a BGP session between r1 and r2
// 4. Ensures the BGP FSM moves into Established on both r1 and r2
// 5. Ensures r2 has succesfully received and installed the prefix(es)
// 6. Shuts down r1
// 7. Ensures the BGP FSM moves out of Established on both r1 and r2
// 8. Ensures r2 has successfully uninstalled the implicitly withdrawn prefix(es)
fn basic_update_helper<
Cnx: BgpConnection + 'static,
Listener: BgpListener<Cnx> + 'static,
>(
route_exchange: RouteExchange,
r1_addr: SocketAddr,
r2_addr: SocketAddr,
) {
let is_tcp = std::any::type_name::<Cnx>().contains("Tcp");
let is_ipv6 = r1_addr.ip().is_ipv6();
let test_name = match (is_tcp, is_ipv6) {
(true, true) => "basic_update_ipv6_tcp",
(true, false) => "basic_update_tcp",
(false, true) => "basic_update_ipv6",
(false, false) => "basic_update",
};
let routers = vec![
LogicalRouter {
name: "r1".to_string(),
asn: Asn::FourOctet(4200000001),
id: 1,
listen_addr: r1_addr,
bind_addr: Some(r1_addr),
neighbors: vec![NeighborConfig {
peer_name: "r2".to_string(),
remote_host: r2_addr,
session_info: create_test_session_info(
route_exchange,
r1_addr,
r2_addr,
false,
),
}],
},
LogicalRouter {
name: "r2".to_string(),
asn: Asn::FourOctet(4200000002),
id: 2,
listen_addr: r2_addr,
bind_addr: Some(r2_addr),
neighbors: vec![NeighborConfig {
peer_name: "r1".to_string(),
remote_host: r1_addr,
session_info: create_test_session_info(
route_exchange,
r2_addr,
r1_addr,
false,
),
}],
},
];
let (test_routers, _ip_guard) =
test_setup::<Cnx, Listener>(test_name, &routers);
let r1 = &test_routers[0];
let r2 = &test_routers[1];
// let the session get into established state
let r1_session = r1
.router
.get_session(r2_addr.ip())
.expect("get session one");
let r2_session = r2
.router
.get_session(r1_addr.ip())
.expect("get session two");
wait_for_eq!(r1_session.state(), FsmStateKind::Established);
wait_for_eq!(r2_session.state(), FsmStateKind::Established);
// Originate and verify routes based on route_exchange variant
match route_exchange {
RouteExchange::Ipv4 {
nexthop: initial_nexthop,
} => {
// IPv4-only: originate and verify IPv4 prefix
r1.router
.create_origin4(vec![cidr!("1.2.3.0/24")])
.expect("originate IPv4");
let prefix_rdb = Prefix::V4(cidr!("1.2.3.0/24"));
wait_for!(!r2.router.db.get_prefix_paths(&prefix_rdb).is_empty());
// Verify initial nexthop if one was configured and test override change
let paths = r2.router.db.get_prefix_paths(&prefix_rdb);
assert_eq!(paths.len(), 1);
if let Some(initial_nh) = initial_nexthop {
assert_eq!(paths[0].nexthop, initial_nh);
// Test nexthop override change
let new_nexthop = match initial_nh {
IpAddr::V4(_) => ip!("10.255.255.254"),
IpAddr::V6(_) => unreachable!(),
};
let peer_config = PeerConfig {
name: "r2".into(),
group: String::new(),
host: r2_addr,
hold_time: 6,
idle_hold_time: 0,
delay_open: 0,
connect_retry: 1,
keepalive: 3,
resolution: 100,
};
let mut session_info = create_test_session_info(
route_exchange,
r1_addr,
r2_addr,
false,
);
session_info.ipv4_unicast.as_mut().unwrap().nexthop =
Some(new_nexthop);
r1.router
.update_session(peer_config, session_info)
.expect("update nexthop");
// Verify nexthop change is reflected in re-advertised route
wait_for!(
{
let paths = r2.router.db.get_prefix_paths(&prefix_rdb);
!paths.is_empty() && paths[0].nexthop == new_nexthop
},
"nexthop should be updated"
);
}
// Shut down r1 and verify withdrawal
r1.shutdown();
wait_for_neq!(r1_session.state(), FsmStateKind::Established);
wait_for_neq!(r2_session.state(), FsmStateKind::Established);
wait_for!(r2.router.db.get_prefix_paths(&prefix_rdb).is_empty());
}
RouteExchange::Ipv6 {
nexthop: initial_nexthop,
} => {
// IPv6-only: originate and verify IPv6 prefix
r1.router
.create_origin6(vec![cidr!("3fff:db8::/32")])
.expect("originate IPv6");
let prefix_rdb = Prefix::V6(cidr!("3fff:db8::/32"));
wait_for!(!r2.router.db.get_prefix_paths(&prefix_rdb).is_empty());
// Verify initial nexthop if one was configured and test override change
let paths = r2.router.db.get_prefix_paths(&prefix_rdb);
assert_eq!(paths.len(), 1);
if let Some(initial_nh) = initial_nexthop {
assert_eq!(paths[0].nexthop, initial_nh);
// Test nexthop override change
let new_nexthop = match initial_nh {
IpAddr::V6(_) => ip!("3fff:ffff:ffff:ffff::ffff:fffe"),
IpAddr::V4(_) => unreachable!(),
};
let peer_config = PeerConfig {
name: "r2".into(),
group: String::new(),
host: r2_addr,
hold_time: 6,
idle_hold_time: 0,
delay_open: 0,
connect_retry: 1,
keepalive: 3,
resolution: 100,
};
let mut session_info = create_test_session_info(
route_exchange,
r1_addr,
r2_addr,
false,
);
session_info.ipv6_unicast.as_mut().unwrap().nexthop =
Some(new_nexthop);
r1.router
.update_session(peer_config, session_info)
.expect("update nexthop");
// Verify nexthop change is reflected in re-advertised route
wait_for!(
{
let paths = r2.router.db.get_prefix_paths(&prefix_rdb);
!paths.is_empty() && paths[0].nexthop == new_nexthop
},
"nexthop should be updated"
);
}
// Shut down r1 and verify withdrawal
r1.shutdown();
wait_for_neq!(r1_session.state(), FsmStateKind::Established);
wait_for_neq!(r2_session.state(), FsmStateKind::Established);
wait_for!(r2.router.db.get_prefix_paths(&prefix_rdb).is_empty());
}
RouteExchange::DualStack {
ipv4_nexthop,
ipv6_nexthop,
} => {
// Dual-stack: originate and verify both IPv4 and IPv6 prefixes
r1.router
.create_origin4(vec![cidr!("1.2.3.0/24")])
.expect("originate IPv4");
r1.router
.create_origin6(vec![cidr!("3fff:db8::/32")])
.expect("originate IPv6");
let prefix4_rdb = Prefix::V4(cidr!("1.2.3.0/24"));
let prefix6_rdb = Prefix::V6(cidr!("3fff:db8::/32"));
wait_for!(!r2.router.db.get_prefix_paths(&prefix4_rdb).is_empty());
wait_for!(!r2.router.db.get_prefix_paths(&prefix6_rdb).is_empty());
// Verify initial nexthops if configured
let paths4 = r2.router.db.get_prefix_paths(&prefix4_rdb);
assert_eq!(paths4.len(), 1);
if let Some(expected_nexthop) = ipv4_nexthop {
assert_eq!(paths4[0].nexthop, expected_nexthop);
}
let paths6 = r2.router.db.get_prefix_paths(&prefix6_rdb);
assert_eq!(paths6.len(), 1);
if let Some(expected_nexthop) = ipv6_nexthop {
assert_eq!(paths6[0].nexthop, expected_nexthop);
}
// Test nexthop override changes if any were configured
if ipv4_nexthop.is_some() || ipv6_nexthop.is_some() {
let new_ipv4_nexthop =
ipv4_nexthop.map(|_| ip!("10.255.255.254"));
let new_ipv6_nexthop =
ipv6_nexthop.map(|_| ip!("3fff:ffff:ffff:ffff::ffff:fffe"));
let peer_config = PeerConfig {
name: "r2".into(),
group: String::new(),
host: r2_addr,
hold_time: 6,
idle_hold_time: 0,
delay_open: 0,
connect_retry: 1,
keepalive: 3,
resolution: 100,
};
let mut session_info = create_test_session_info(
route_exchange,
r1_addr,
r2_addr,
false,
);
if let Some(nexthop) = new_ipv4_nexthop {
session_info.ipv4_unicast.as_mut().unwrap().nexthop =
Some(nexthop);
}
if let Some(nexthop) = new_ipv6_nexthop {
session_info.ipv6_unicast.as_mut().unwrap().nexthop =
Some(nexthop);
}
r1.router
.update_session(peer_config, session_info)
.expect("update nexthop");
// Verify IPv4 nexthop change if applicable
if let Some(new_nh) = new_ipv4_nexthop {
wait_for!(
{
let paths =
r2.router.db.get_prefix_paths(&prefix4_rdb);
!paths.is_empty() && paths[0].nexthop == new_nh
},
"IPv4 nexthop should be updated"
);
}
// Verify IPv6 nexthop change if applicable
if let Some(new_nh) = new_ipv6_nexthop {
wait_for!(
{
let paths =
r2.router.db.get_prefix_paths(&prefix6_rdb);
!paths.is_empty() && paths[0].nexthop == new_nh
},
"IPv6 nexthop should be updated"
);
}
}
// Shut down r1 and verify withdrawal of both
r1.shutdown();
wait_for_neq!(r1_session.state(), FsmStateKind::Established);
wait_for_neq!(r2_session.state(), FsmStateKind::Established);
wait_for!(r2.router.db.get_prefix_paths(&prefix4_rdb).is_empty());
wait_for!(r2.router.db.get_prefix_paths(&prefix6_rdb).is_empty());
}
}
// Clean up properly
r2.shutdown();
}
/// Helper for testing 3-router chain topology: r1 <-> r2 <-> r3
/// This validates that the BgpListener can handle multiple connections.
fn three_router_chain_helper<
Cnx: BgpConnection + 'static,
Listener: BgpListener<Cnx> + 'static,
>(
r1_addr: SocketAddr,
r2_addr: SocketAddr,
r3_addr: SocketAddr,
) {
let is_tcp = std::any::type_name::<Cnx>().contains("Tcp");
let is_ipv6 = r1_addr.ip().is_ipv6();
let test_str = match (is_tcp, is_ipv6) {
(true, true) => "three_router_chain_tcp_ipv6",
(true, false) => "three_router_chain_tcp",
(false, true) => "three_router_chain_ipv6",
(false, false) => "three_router_chain",
};
// Set up 3 routers in a chain topology: r1 <-> r2 <-> r3
let routers = vec![
LogicalRouter {
name: "r1".to_string(),
asn: Asn::FourOctet(4200000001),
id: 1,
listen_addr: r1_addr,
bind_addr: Some(r1_addr),
neighbors: vec![NeighborConfig {
peer_name: "r2".to_string(),
remote_host: r2_addr,
session_info: SessionInfo::from_peer_config(&PeerConfig {
name: "r2".into(),
group: String::new(),
host: r2_addr,
hold_time: 6,
idle_hold_time: 0,
delay_open: 0,
connect_retry: 1,
keepalive: 3,
resolution: 100,
}),
}],
},
LogicalRouter {
name: "r2".to_string(),
asn: Asn::FourOctet(4200000002),
id: 2,
listen_addr: r2_addr,
bind_addr: Some(r2_addr),
neighbors: vec![
NeighborConfig {
peer_name: "r1".to_string(),
remote_host: r1_addr,
session_info: SessionInfo::from_peer_config(&PeerConfig {
name: "r1".into(),
group: String::new(),
host: r1_addr,
hold_time: 6,
idle_hold_time: 0,
delay_open: 0,
connect_retry: 1,
keepalive: 3,