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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
// Snowcap: Synthesizing Network-Wide Configuration Updates
// Copyright (C) 2021  Tibor Schneider
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

//! Import functions for importing topology zoo graphml files

use crate::hard_policies::*;
use crate::netsim::config::{
    Config,
    ConfigExpr::{self, *},
};
use crate::netsim::route_map::*;
use crate::netsim::{AsId, BgpSessionType::*, LinkWeight, Network, NetworkError, Prefix, RouterId};
use crate::Error;

use itertools::iproduct;
use log::*;
use petgraph::prelude::*;
use rand::prelude::*;
use std::collections::{HashMap, HashSet, VecDeque};

mod error;
pub use error::ZooTopologyError;

mod gml_parser;

type NodeIdx = NodeIndex<u32>;

/// # ZooTopology
/// This struct can be used to generate a network from a ZooTopology graphml file. In addition, you
/// can set (predictably) random link weights, and generate a (predictably) random iBGP topologies.
///
/// ```rust
/// # use snowcap::topology_zoo::ZooTopology;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let gml_filename: String = format!("{}/test_files/switch.gml", env!("CARGO_MANIFEST_DIR"));
/// let mut t = ZooTopology::new(gml_filename, 42)?;
/// t.randomize_link_weights(100);
/// t.ibgp_spanning_forest(4);
///
/// let mut net = t.get_net();
/// net.set_config(&t.get_config()?)?;
/// t.advertise_prefixes(&mut net, 16, 0.5)?;
/// # Ok(())
/// # }
/// ```
///
/// You can choose from the following iBGP topologies:
/// - Full-mesh
/// - Topology with a single route reflector, and all other routers being clients connected to that
///   route reflector
/// - Spanning forest topology with `num_roots` different root nodes, chosen randomly, and a
///   hierarchie of route reflectors, where each internal non-root node has exactly one parent route
///   reflector.
#[derive(Debug, Clone)]
pub struct ZooTopology {
    rng: StdRng,
    graph: Graph<NodeData, LinkWeight, Undirected, u32>,
    /// The node data of this graph is the node index into the physical graph.
    ibgp_graph: Graph<(), (), Directed, u32>,
    ibgp_roots: HashSet<NodeIdx>,
    /// Every node in this set is in its separate network!
    disconnected: HashSet<NodeIdx>,
    maintenance: HashSet<NodeIdx>,
    create_ibgp_peers: bool,
}

impl ZooTopology {
    /// Return a new ZooTopology instance by reading and parsing the privided GML file. Per default,
    /// it will generate a ZooTopology with 100 prefixes. The iBGP topology is not generated by
    /// default.
    ///
    /// # Panics
    /// Panics if somehow, petgraph does not play along and creates nodes in a wierd order.
    pub fn new(gml_filename: impl AsRef<str>, seed: u64) -> Result<Self, ZooTopologyError> {
        info!("Parsing the file and reading the graph");
        let graph = gml_parser::parse_gml_graph(gml_filename.as_ref())?;
        info!("Successfully read the GML file.");
        // clone the nodes of the physical graph and make sure that the nodes indices are always the same
        let mut ibgp_graph: Graph<(), (), Directed, u32> = Graph::new();
        for _ in graph.node_indices() {
            ibgp_graph.add_node(());
        }

        Ok(Self {
            rng: StdRng::seed_from_u64(seed),
            graph,
            ibgp_graph,
            ibgp_roots: HashSet::new(),
            disconnected: HashSet::new(),
            maintenance: HashSet::new(),
            create_ibgp_peers: true,
        })
    }

    /// This funciton applies a scenario to a topology (including some common configuration). This
    /// function may panic, if the topology does not support the scenario.
    pub fn apply_scenario(
        &mut self,
        scenario: Scenario,
        random_root: bool,
        max_weight: u32,
        num_prefixes: usize,
        prefix_probability: f64,
    ) -> Result<(Network, Config, HardPolicy), Error> {
        let mut net = self.get_net();
        // build initial config

        let (config_a, config_b) = match scenario {
            Scenario::FullMesh2RouteReflector | Scenario::RouteReflector2FullMesh => {
                self.randomize_link_weights(max_weight);
                self.ibgp_full_mesh();
                let config_a = self.get_config()?;

                // build final config with different iBGP topology
                if random_root {
                    self.ibgp_single_route_reflector_random()?;
                } else {
                    self.ibgp_single_route_reflector_most_important()?;
                }
                let config_b = self.get_config()?;
                (config_a, config_b)
            }
            Scenario::DoubleIgpWeight | Scenario::HalveIgpWeight => {
                self.randomize_link_weights(max_weight);
                // build initial config
                if random_root {
                    self.ibgp_single_route_reflector_random()?;
                } else {
                    self.ibgp_single_route_reflector_most_important()?;
                }
                let config_a = self.get_config()?;
                let mut config_b = Config::new();
                for expr in config_a.iter() {
                    config_b.add(match expr.clone() {
                        ConfigExpr::IgpLinkWeight { source, target, weight }
                            if net.get_device(source).is_internal()
                                && net.get_device(target).is_internal() =>
                        {
                            ConfigExpr::IgpLinkWeight { source, target, weight: weight * 2.0 }
                        }
                        e => e,
                    })?;
                }
                (config_a, config_b)
            }
            Scenario::DoubleLocalPref | Scenario::HalveLocalPref => {
                self.randomize_link_weights(max_weight);
                if random_root {
                    self.ibgp_single_route_reflector_random()?;
                } else {
                    self.ibgp_single_route_reflector_most_important()?;
                }
                let config_a = self.get_config()?;
                let mut config_b = config_a.clone();
                let mut order_id = 1;
                for expr in config_a.iter() {
                    let (r_int, r_ext) = match expr {
                        ConfigExpr::BgpSession { source: r_int, target: r_ext, session_type }
                            if session_type.is_ebgp()
                                && net.get_external_routers().contains(r_ext) =>
                        {
                            (r_int, r_ext)
                        }
                        ConfigExpr::BgpSession { source: r_ext, target: r_int, session_type }
                            if session_type.is_ebgp()
                                && net.get_external_routers().contains(r_ext) =>
                        {
                            (r_int, r_ext)
                        }
                        _ => continue,
                    };
                    config_b.add(ConfigExpr::BgpRouteMap {
                        router: *r_int,
                        direction: RouteMapDirection::Incoming,
                        map: RouteMapBuilder::new()
                            .order(order_id)
                            .allow()
                            .match_neighbor(*r_ext)
                            .set_local_pref(200)
                            .build(),
                    })?;
                    order_id += 1;
                }
                (config_a, config_b)
            }
            Scenario::IntroduceSecondRouteReflector | Scenario::RemoveSecondRouteReflector => {
                self.randomize_link_weights(max_weight);
                // set route-reflector topology
                if random_root {
                    self.ibgp_single_route_reflector_random()?;
                } else {
                    self.ibgp_single_route_reflector_most_important()?;
                }
                let config_a = self.get_config()?;
                let root = self
                    .get_roots()
                    .into_iter()
                    .next()
                    .expect("exactly one root must exist!")
                    .to_string();

                if random_root {
                    self.ibgp_two_route_reflectors_one_named_other_random(root.as_str())?;
                } else {
                    self.ibgp_two_route_reflectors_one_named_other_important(root.as_str())?;
                }
                let config_b = self.get_config()?;
                (config_a, config_b)
            }
            Scenario::NetworkAcquisition | Scenario::NetworkSplit => {
                self.randomize_link_weights(max_weight);
                self.acquisition_before(0.1)?;
                let config_a = self.get_config()?;
                let mut t_clone = self.clone();
                t_clone.acquisition_after(0.1, max_weight);
                let config_b = t_clone.get_config()?;
                (config_a, config_b)
            }
            Scenario::DisconnectRouter | Scenario::ConnectRouter => {
                // setup weights and the single route-reflector topology
                self.randomize_link_weights(max_weight);
                if random_root {
                    self.ibgp_single_route_reflector_random()?;
                } else {
                    self.ibgp_single_route_reflector_most_important()?;
                }
                let config_a = self.get_config()?;

                // select a router that is the most important
                let mut possible_routers = self
                    .graph
                    .node_indices()
                    .into_iter()
                    .filter(|x| {
                        !self.ibgp_roots.contains(x)
                            && self
                                .graph
                                .neighbors(*x)
                                .filter(|n| self.graph.node_weight(*n).unwrap().external)
                                .count()
                                == 0
                    })
                    .collect::<Vec<_>>();
                possible_routers.shuffle(&mut self.rng);
                let selected_router = possible_routers
                    .into_iter()
                    .next()
                    .ok_or(ZooTopologyError::TooFewNonBorderRouters)?;
                self.maintenance.insert(selected_router);
                // set all link weights around this router to infinity
                self.graph
                    .edges_directed(selected_router, Direction::Outgoing)
                    .chain(self.graph.edges_directed(selected_router, Direction::Incoming))
                    .map(|e| e.id())
                    .collect::<Vec<_>>() // collect in order to get a mutable reference to graph
                    .into_iter()
                    .for_each(|e| *self.graph.edge_weight_mut(e).unwrap() = LinkWeight::INFINITY);

                let config_b = self.get_config()?;
                (config_a, config_b)
            }
            Scenario::VerifyTransientCondition | Scenario::VerifyTransientConditionReverse => {
                return self.apply_transient_condition_scenario(
                    net,
                    max_weight,
                    scenario.is_inverse(),
                    None,
                );
            }
        };

        // inverse the configuration if necessary
        let (config_a, config_b) =
            if scenario.is_inverse() { (config_b, config_a) } else { (config_a, config_b) };

        // apply config A to network
        net.set_config(&config_a)?;

        // advertise the same prefix on every router
        self.advertise_prefixes(&mut net, num_prefixes, prefix_probability)?;

        // prepare the hard polcies
        let hard_policy = match scenario {
            Scenario::ConnectRouter => {
                let prop_vars =
                    iproduct!(net.get_routers().iter(), net.get_known_prefixes().iter())
                        .map(|(r, p)| Condition::Reachable(*r, *p, None))
                        .collect::<Vec<Condition>>();

                let prop_vars_without = prop_vars
                    .iter()
                    .enumerate()
                    .filter(|(_, p)| !self.maintenance.contains(&p.router_id()))
                    .map(|(i, _)| i)
                    .collect::<Vec<_>>();

                let prop_vars_with = (0..prop_vars.len()).collect::<Vec<_>>();

                HardPolicy::until_globally(prop_vars, &prop_vars_without, &prop_vars_with)
            }
            Scenario::DisconnectRouter => {
                let prop_vars =
                    iproduct!(net.get_routers().iter(), net.get_known_prefixes().iter())
                        .map(|(r, p)| Condition::Reachable(*r, *p, None))
                        .collect::<Vec<Condition>>();

                let prop_vars_without = prop_vars
                    .iter()
                    .enumerate()
                    .filter(|(_, p)| !self.maintenance.contains(&p.router_id()))
                    .map(|(i, _)| i)
                    .collect::<Vec<_>>();

                let prop_vars_with = (0..prop_vars.len()).collect::<Vec<_>>();

                HardPolicy::until_globally(prop_vars, &prop_vars_with, &prop_vars_without)
            }
            _ => {
                HardPolicy::reachability(net.get_routers().iter(), net.get_known_prefixes().iter())
            }
        };

        Ok((net, config_b, hard_policy))
    }

    /// Applies the transient condition scenario, and returns (if possible) the tuple `Network`,
    /// `Config` and `HardPolicy`. If the arguemnt `external_routers` is given, their values
    /// represent the following:
    /// 1. Name of the router configured with local-pref 100
    /// 2. Name of the router configured with local-pref 50
    /// 3. Name of the router added (or removed) during reconfiguration.
    ///
    /// This function is called when calling [`ZooTopology::apply_scenario`] with the scenario
    /// [`Scenario::VerifyTransientCondition`] or [`Scenario::VerifyTransientConditionReverse`]
    pub fn apply_transient_condition_scenario(
        &mut self,
        mut net: Network,
        max_weight: u32,
        reverse: bool,
        external_routers: Option<(&str, &str, &str)>,
    ) -> Result<(Network, Config, HardPolicy), Error> {
        // first, randomize the link weights
        self.randomize_link_weights(max_weight);
        // then generate the 3-RR topology
        self.ibgp_general_route_reflectors(3)?;
        // generate the config, but without any external router configuration
        let mut c1 = self.prepare_config(false)?;
        // select three distinct border routers (to do this, iterate over all routers and filter out
        // the ones that are external, and those that have no neighbor that is an external router.)
        let (ext_lp100, ext_lp50, ext_new) = match external_routers {
            None => {
                let mut border_routers = self
                    .graph
                    .node_indices()
                    .into_iter()
                    .filter(|x| !self.graph.node_weight(*x).unwrap().external)
                    .filter(|x| {
                        self.graph
                            .neighbors(*x)
                            .find(|n| self.graph.node_weight(*n).unwrap().external)
                            .is_some()
                    })
                    .collect::<Vec<_>>();
                if border_routers.len() < 3 {
                    return Err(Error::ZooTopologyError(ZooTopologyError::TooFewExternalRouters));
                }
                border_routers.shuffle(&mut self.rng);
                // generate an iterator that iterates over each border routers and returns the first
                // external neighbor
                let mut ext = border_routers.into_iter().map(|x| {
                    self.graph
                        .neighbors(x)
                        .filter(|n| self.graph.node_weight(*n).unwrap().external)
                        .next()
                        .unwrap()
                });
                (ext.next().unwrap(), ext.next().unwrap(), ext.next().unwrap())
            }
            Some((n_lp100, n_lp50, n_new)) => {
                let names = [n_lp100, n_lp50, n_new];
                let mut ext = names.iter().map(|ext| {
                    self.graph
                        .node_indices()
                        .into_iter()
                        .filter(|x| self.graph.node_weight(*x).unwrap().name == **ext)
                        .next()
                        .unwrap()
                });
                (ext.next().unwrap(), ext.next().unwrap(), ext.next().unwrap())
            }
        };

        // configure neighbor of ext_lp50 to set lp to 50
        let int_lp50 = self.graph.neighbors(ext_lp50).next().unwrap();
        let ext_net_idx = self.graph.node_weight(ext_lp50).unwrap().net_idx.unwrap();
        let int_net_idx = self.graph.node_weight(int_lp50).unwrap().net_idx.unwrap();
        c1.add(BgpRouteMap {
            router: int_net_idx,
            direction: RouteMapDirection::Incoming,
            map: RouteMapBuilder::new()
                .order(10)
                .allow()
                .match_neighbor(ext_net_idx)
                .set_local_pref(50)
                .build(),
        })?;

        // generate ebgp sessions to the two old neighbors
        for &ext in &[ext_lp100, ext_lp50] {
            let neighbor = self.graph.neighbors(ext).next().unwrap();
            let ext_net_idx = self.graph.node_weight(ext).unwrap().net_idx.unwrap();
            let int_net_idx = self.graph.node_weight(neighbor).unwrap().net_idx.unwrap();
            c1.add(BgpSession { source: ext_net_idx, target: int_net_idx, session_type: EBgp })?;
        }

        // generate the new session for the second configuration
        let mut c2 = c1.clone();
        for &ext in &[ext_new] {
            let neighbor = self.graph.neighbors(ext).next().unwrap();
            let ext_net_idx = self.graph.node_weight(ext).unwrap().net_idx.unwrap();
            let int_net_idx = self.graph.node_weight(neighbor).unwrap().net_idx.unwrap();
            c2.add(BgpSession { source: ext_net_idx, target: int_net_idx, session_type: EBgp })?;
        }

        // the hard policy will be empty!
        let policy = HardPolicy::globally(vec![]);

        let final_config = if reverse {
            net.set_config(&c2)?;
            c1
        } else {
            net.set_config(&c1)?;
            c2
        };

        net.advertise_external_route(
            self.graph.node_weight(ext_lp100).unwrap().net_idx.unwrap(),
            Prefix(0),
            vec![AsId(65101), AsId(65200)],
            None,
            None,
        )?;
        net.advertise_external_route(
            self.graph.node_weight(ext_lp50).unwrap().net_idx.unwrap(),
            Prefix(0),
            vec![AsId(65102), AsId(65200)],
            None,
            None,
        )?;
        net.advertise_external_route(
            self.graph.node_weight(ext_new).unwrap().net_idx.unwrap(),
            Prefix(0),
            vec![AsId(65103), AsId(65200)],
            None,
            None,
        )?;

        Ok((net, final_config, policy))
    }

    /// Returns a reference to the iBGP roots
    pub fn get_roots(&self) -> Vec<&str> {
        self.ibgp_roots
            .iter()
            .map(|idx| self.graph.node_weight(*idx).unwrap().name.as_str())
            .collect()
    }

    /// Randomize all link weights
    pub fn randomize_link_weights(&mut self, max: u32) -> &mut Self {
        info!("Randomize the link weights.");
        for edge_index in self.graph.edge_indices() {
            let edge_weight = self.graph.edge_weight_mut(edge_index).unwrap();
            let weight: u32 = (self.rng.next_u32() % max) + 1u32;
            *edge_weight = weight as LinkWeight;
        }
        self
    }

    /// Reset the seed to a known value
    pub fn set_seed(&mut self, seed: u64) -> &mut Self {
        self.rng = StdRng::seed_from_u64(seed);
        self
    }

    /// Forms an iBGP full mesh between all routers.
    pub fn ibgp_full_mesh(&mut self) -> &mut Self {
        self.ibgp_graph.clear_edges();
        // here, all nodes are roots.
        self.ibgp_roots = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .collect();
        self
    }

    /// Forms an iBGP graph by choosing one route reflector in the network, where all other routers
    /// are connected to that router as client. Here, we choose the router having the most IGP
    /// connections to other internal routers.
    ///
    /// # Panics
    /// This function panics if there exists no internal router.
    pub fn ibgp_single_route_reflector_most_important(
        &mut self,
    ) -> Result<&mut Self, ZooTopologyError> {
        // choose the node with the most neighbors
        let best_root: NodeIdx = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .max_by_key(|x| {
                self.graph
                    .neighbors(*x)
                    .filter(|n| !self.graph.node_weight(*n).unwrap().external)
                    .count()
            })
            .ok_or(ZooTopologyError::TooFewInternalRouters)?;

        Ok(self.ibgp_single_route_reflector(best_root))
    }

    /// Forms an iBGP graph by choosing one route reflector in the network, where all other routers
    /// are connected to that router as client. Here, we choose the route reflector at random.
    ///
    /// # Panics
    /// This function panics if there exists no internal router.
    pub fn ibgp_single_route_reflector_random(&mut self) -> Result<&mut Self, ZooTopologyError> {
        // choose the node with the most neighbors
        let mut nodes = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .collect::<Vec<NodeIdx>>();
        nodes.shuffle(&mut self.rng);
        Ok(self.ibgp_single_route_reflector(
            *nodes.first().ok_or(ZooTopologyError::TooFewInternalRouters)?,
        ))
    }

    /// Forms an iBGP graph by choosing one route reflector in the network, where all other routers
    /// are connected to that router as client. Here, the router with the given name is selected.
    ///
    /// # Panics
    /// This function panics if there exists no internal router with the given name.
    pub fn ibgp_single_route_reflector_named(
        &mut self,
        root_name: &str,
    ) -> Result<&mut Self, ZooTopologyError> {
        // choose the node with the most neighbors
        let root = self
            .graph
            .node_indices()
            .into_iter()
            .find(|x| {
                let node_info = self.graph.node_weight(*x).unwrap();
                !node_info.external && node_info.name == root_name
            })
            .ok_or_else(|| ZooTopologyError::NameNotFound(root_name.to_string()))?;

        Ok(self.ibgp_single_route_reflector(root))
    }

    /// Form an iBGP graph by choosing two route reflectors in the network. All non-root routers
    /// are connected to both route reflectors, and the two route reflectors form a peering session.
    ///
    /// # Panics
    /// This funciton panics if there are less than 2 internal routers
    pub fn ibgp_two_route_reflectors_most_important(
        &mut self,
    ) -> Result<&mut Self, ZooTopologyError> {
        let mut internal_nodes = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .collect::<Vec<_>>();
        internal_nodes.sort_by_key(|x| {
            self.graph
                .neighbors(*x)
                .filter(|n| !self.graph.node_weight(*n).unwrap().external)
                .count()
        });
        let mut internal_nodes_iter = internal_nodes.into_iter().rev();
        let roots = [
            internal_nodes_iter.next().ok_or(ZooTopologyError::TooFewInternalRouters)?,
            internal_nodes_iter.next().ok_or(ZooTopologyError::TooFewInternalRouters)?,
        ];

        Ok(self.ibgp_two_route_reflectors(roots))
    }

    /// Form an iBGP graph by choosing two route reflectors in the network. All non-root routers
    /// are connected to both route reflectors, and the two route reflectors form a peering session.
    /// One route reflector is chosen based on its importance, and the other is selected by name.
    ///
    /// # Panics
    /// This funciton panics if there exists less than 2 internal routers, and if the named router
    /// does not exist
    pub fn ibgp_two_route_reflectors_one_named_other_important(
        &mut self,
        root_name: &str,
    ) -> Result<&mut Self, ZooTopologyError> {
        let root_a = self
            .graph
            .node_indices()
            .into_iter()
            .find(|x| {
                let node_info = self.graph.node_weight(*x).unwrap();
                !node_info.external && node_info.name == root_name
            })
            .ok_or(ZooTopologyError::TooFewInternalRouters)?;

        let root_b = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .filter(|x| *x != root_a)
            .max_by_key(|x| {
                self.graph
                    .neighbors(*x)
                    .filter(|n| !self.graph.node_weight(*n).unwrap().external)
                    .count()
            })
            .ok_or(ZooTopologyError::TooFewInternalRouters)?;

        let roots = [root_a, root_b];
        Ok(self.ibgp_two_route_reflectors(roots))
    }

    /// Form an iBGP graph by choosing two route reflectors in the network. All non-root routers
    /// are connected to both route reflectors, and the two route reflectors form a peering session.
    /// One route reflector is chosen randomly, and the other is selected by name.
    ///
    /// # Panics
    /// This funciton panics if there exists less than 2 internal routers, and if the named router
    /// does not exist
    pub fn ibgp_two_route_reflectors_one_named_other_random(
        &mut self,
        root_name: &str,
    ) -> Result<&mut Self, ZooTopologyError> {
        let root_a = self
            .graph
            .node_indices()
            .into_iter()
            .find(|x| {
                let node_info = self.graph.node_weight(*x).unwrap();
                !node_info.external && node_info.name == root_name
            })
            .ok_or(ZooTopologyError::TooFewInternalRouters)?;

        let mut nodes = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .filter(|x| *x != root_a)
            .collect::<Vec<NodeIdx>>();
        nodes.shuffle(&mut self.rng);
        let root_b = nodes
            .into_iter()
            .next()
            .ok_or_else(|| ZooTopologyError::NameNotFound(root_name.to_string()))?;

        let roots = [root_a, root_b];
        Ok(self.ibgp_two_route_reflectors(roots))
    }

    /// Form an iBGP graph by choosing two route reflectors in the network. All non-root routers
    /// are connected to both route reflectors, and the two route reflectors form a peering session.
    ///
    /// # Panics
    /// This funciton panics if the two routers don't exist or are external routers
    pub fn ibgp_two_route_reflectors_named(
        &mut self,
        root_name_a: &str,
        root_name_b: &str,
    ) -> Result<&mut Self, ZooTopologyError> {
        let root_a = self
            .graph
            .node_indices()
            .into_iter()
            .find(|x| {
                let node_info = self.graph.node_weight(*x).unwrap();
                !node_info.external && node_info.name == root_name_a
            })
            .ok_or_else(|| ZooTopologyError::NameNotFound(root_name_a.to_string()))?;

        let root_b = self
            .graph
            .node_indices()
            .into_iter()
            .find(|x| {
                let node_info = self.graph.node_weight(*x).unwrap();
                !node_info.external && node_info.name == root_name_b
            })
            .ok_or_else(|| ZooTopologyError::NameNotFound(root_name_b.to_string()))?;

        let roots = [root_a, root_b];
        Ok(self.ibgp_two_route_reflectors(roots))
    }

    /// Prepares the ibgp graph such that it forms a spanning forest, originating from n root noes.
    /// This result will always be the same given the same seed
    ///
    /// # Panics
    /// This function panics if num_roots is larger than the number of internal routers in the
    /// network.
    pub fn ibgp_spanning_forest(&mut self, num_roots: usize) -> &mut Self {
        info!("Generate a spanning forest for the iBGP graph.");
        // clear everything that was before
        self.ibgp_roots.drain();
        self.ibgp_graph.clear_edges();

        // get a list of all internal nodes
        let mut nodes: Vec<NodeIdx> = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .collect();
        // sort before shuffle, to guarantee that we always get the same result
        nodes.sort();
        // shuffle the vector and get the n roots
        nodes.shuffle(&mut self.rng);
        // select the roots
        for n in nodes.iter().take(num_roots) {
            self.ibgp_roots.insert(*n);
        }

        debug!(
            "Chosen roots: {:?}",
            self.ibgp_roots
                .iter()
                .map(|x| &self.graph.node_weight(*x).unwrap().name)
                .collect::<Vec<&String>>()
        );

        // setup the algorithm for building a spanning forest based around all roots
        let mut visited_nodes: HashSet<NodeIdx> = self.ibgp_roots.clone();
        let mut current_nodes: VecDeque<NodeIdx> = VecDeque::new();
        for n in nodes.iter().take(num_roots) {
            current_nodes.push_back(*n);
        }

        // prepare the current nodes
        while let Some(node) = current_nodes.pop_front() {
            let mut neighbors: Vec<NodeIdx> = self
                .graph
                .neighbors(node)
                .into_iter()
                .filter(|x| !self.graph.node_weight(*x).unwrap().external)
                .collect();
            neighbors.sort();
            neighbors.shuffle(&mut self.rng);
            for next in neighbors {
                if visited_nodes.insert(next) {
                    trace!(
                        "Adding link to spanning tree: {} -> {}",
                        self.graph.node_weight(node).unwrap().name,
                        self.graph.node_weight(next).unwrap().name
                    );
                    self.ibgp_graph.add_edge(node, next, ());
                    current_nodes.push_back(next);
                } // else, value was already present and we do nothing
            }
        }

        self
    }

    /// Prepares the network to be set up for a BGP acquisition. The following is done:
    /// 1. The netowrk is split into two connected parts. All links between the two components are
    ///    disabled. The two connected parts will both have at least one node connected to external
    ///    devices.
    /// 2. In one of the two components, the IGP weights will be scaled by the `igp_scale_factor`
    /// 3. Both components will select a route reflector, and all nodes in the component will have a
    ///    session to this route reflector.
    ///
    /// # Panics
    /// This function panics if the network cannot be split into two connected components. This can
    /// be the case if there exists only one router, that is connected to external devices.
    pub fn acquisition_before(
        &mut self,
        igp_scale_factor: f32,
    ) -> Result<&mut Self, ZooTopologyError> {
        // split the network into two components
        let mut component_a = Vec::new();
        let mut component_b = Vec::new();

        // chose two border routers as seeds to grow the two components
        let mut border_routers = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .filter(|x| {
                self.graph
                    .neighbors(*x)
                    .filter(|n| self.graph.node_weight(*n).unwrap().external)
                    .count()
                    > 0
            });

        // choose two border routers as seeds
        component_a.push(border_routers.next().ok_or(ZooTopologyError::TooFewBorderRouters)?);
        component_b.push(border_routers.next().ok_or(ZooTopologyError::TooFewBorderRouters)?);

        let mut changed: bool = true;
        while changed {
            changed = false;
            // extend component a
            if let Some(next_a) = self.extend_node(&component_a, &component_b) {
                component_a.push(next_a);
                changed = true;
            }
            // extend component b
            if let Some(next_b) = self.extend_node(&component_b, &component_a) {
                component_b.push(next_b);
                changed = true;
            }
        }

        // network is now split into two parts. Go through and change the links
        for edge_idx in self.graph.edge_indices().collect::<Vec<_>>() {
            let (n1, n2) = self.graph.edge_endpoints(edge_idx).unwrap();
            let n1_member_a = if component_a.contains(&n1) {
                true
            } else if component_b.contains(&n1) {
                false
            } else {
                continue; // node is neither member of A or B
            };
            let n2_member_a = if component_a.contains(&n2) {
                true
            } else if component_b.contains(&n2) {
                false
            } else {
                continue; // node is neither member of A or B
            };
            match (n1_member_a, n2_member_a) {
                // if both are in a, nothing to do
                (true, true) => {}
                (false, false) => {
                    // we need to multiply the weight by the factor
                    let current_weight = self.graph.edge_weight_mut(edge_idx).unwrap();
                    *current_weight = (*current_weight * igp_scale_factor).round().max(1.0);
                }
                (false, true) | (true, false) => {
                    // we need to set the weight to infinity
                    *self.graph.edge_weight_mut(edge_idx).unwrap() = LinkWeight::INFINITY;
                }
            }
        }

        // get the two roots
        let root_a = component_a
            .iter()
            .cloned()
            .max_by_key(|x| {
                self.graph
                    .neighbors(*x)
                    .filter(|n| !self.graph.node_weight(*n).unwrap().external)
                    .count()
            })
            .expect("component_a cannot be empty!");
        let root_b = component_b
            .iter()
            .cloned()
            .max_by_key(|x| {
                self.graph
                    .neighbors(*x)
                    .filter(|n| !self.graph.node_weight(*n).unwrap().external)
                    .count()
            })
            .expect("component_b cannot be empty!");

        // clear the already existing information.
        self.ibgp_roots.drain();
        self.ibgp_graph.clear_edges();
        // setup the root node
        self.ibgp_roots.insert(root_a);
        self.ibgp_roots.insert(root_b);
        // create the edges
        for node_a in component_a.iter() {
            if *node_a == root_a {
                continue;
            }
            self.ibgp_graph.add_edge(root_a, *node_a, ());
        }
        for node_b in component_b.iter() {
            if *node_b == root_b {
                continue;
            }
            self.ibgp_graph.add_edge(root_b, *node_b, ());
        }

        self.create_ibgp_peers = false;
        self.disconnected = component_b.into_iter().collect();

        Ok(self)
    }

    /// Prepares the network to be set up after BGP acquisition. The following is done:
    /// 1. The two split network parts are reconnected, and their
    /// 2. In one of the two components, the IGP weights will be scaled by the inverse of `igp_scale_factor`
    /// 3. Both route reflectors will be connected.
    ///
    /// # Panics
    /// This function panics if the network cannot be split into two connected components. This can
    /// be the case if there exists only one router, that is connected to external devices.
    pub fn acquisition_after(&mut self, igp_scale_factor: f32, weight_max: u32) -> &mut Self {
        // split the network into two components
        let component_a = self
            .graph
            .node_indices()
            .filter(|idx| !self.disconnected.contains(idx))
            .filter(|idx| !self.graph.node_weight(*idx).unwrap().external)
            .collect::<Vec<_>>();
        let component_b = self.disconnected.iter().cloned().collect::<Vec<_>>();

        // network is now split into two parts. Go through and change the links
        for edge_idx in self.graph.edge_indices().collect::<Vec<_>>() {
            let (n1, n2) = self.graph.edge_endpoints(edge_idx).unwrap();
            let n1_member_a = if component_a.contains(&n1) {
                true
            } else if component_b.contains(&n1) {
                false
            } else {
                continue; // node is neither member of A or B
            };
            let n2_member_a = if component_a.contains(&n2) {
                true
            } else if component_b.contains(&n2) {
                false
            } else {
                continue; // node is neither member of A or B
            };
            match (n1_member_a, n2_member_a) {
                // if both are in a, nothing to do
                (true, true) => {}
                (false, false) => {
                    // we need to multiply the weight by the factor
                    let current_weight = self.graph.edge_weight_mut(edge_idx).unwrap();
                    *current_weight = (*current_weight / igp_scale_factor).round().max(1.0);
                }
                (false, true) | (true, false) => {
                    // we need to set the weight to infinity
                    let weight: u32 = (self.rng.next_u32() % weight_max) + 1u32;
                    *self.graph.edge_weight_mut(edge_idx).unwrap() = weight as LinkWeight;
                }
            }
        }

        self.create_ibgp_peers = true;
        self.disconnected.clear();

        self
    }

    /// Helper function to extend a component by one node, if possible.
    fn extend_node(&mut self, component: &[NodeIdx], other: &[NodeIdx]) -> Option<NodeIdx> {
        let mut choices = component
            .iter()
            .map(|idx| self.graph.neighbors(*idx))
            .flatten()
            .filter(|neighbor| !self.graph.node_weight(*neighbor).unwrap().external)
            .filter(|neighbor| !(component.contains(neighbor) || other.contains(neighbor)))
            .collect::<Vec<NodeIdx>>();
        choices.shuffle(&mut self.rng);
        choices.into_iter().next()
    }

    /// Generates a `netsim::network::Network` structure, and updates the internal datastructure
    /// to point to the correct indices of the network. This is required before you call the
    /// `get_config` method.
    pub fn get_net(&mut self) -> Network {
        info!("Generating the network");
        let mut net = Network::new();

        // generate the nodes
        for node in self.graph.node_indices() {
            let mut node_data = self.graph.node_weight_mut(node).unwrap();
            trace!("Adding node: {} with AS {}", node_data.name, node_data.as_id.0);
            let net_idx = if node_data.external {
                net.add_external_router(node_data.name.clone(), node_data.as_id)
            } else {
                net.add_router(node_data.name.clone())
            };
            node_data.net_idx = Some(net_idx);
        }

        // generate the links
        for edge_idx in self.graph.edge_indices() {
            let (src, dst) = self.graph.edge_endpoints(edge_idx).unwrap();
            trace!(
                "Adding link: {} -> {}",
                self.graph.node_weight(src).unwrap().name,
                self.graph.node_weight(dst).unwrap().name
            );
            let src_net_idx = self.graph.node_weight(src).unwrap().net_idx.unwrap();
            let dst_net_idx = self.graph.node_weight(dst).unwrap().net_idx.unwrap();
            net.add_link(src_net_idx, dst_net_idx);
        }

        net
    }

    /// # Advertise prefixes
    /// This function will make sure that external routers advertise some prefixes in the following
    /// way:
    ///
    /// For each prefix and for each external router, determine (by using randomness), if the route
    /// should be advertised by by this external router, based on the probability given as argument.
    pub fn advertise_prefixes(
        &mut self,
        net: &mut Network,
        num_prefixes: usize,
        probability: f64,
    ) -> Result<(), NetworkError> {
        info!("Advertise {} prefixes in the network", num_prefixes);
        let mut external_nodes: Vec<NodeIdx> = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| self.graph.node_weight(*x).unwrap().external)
            .collect();
        // sort before shuffle, to guarantee that we always get the same result
        external_nodes.sort();

        let mut prefixes: Vec<(Prefix, AsId)> = Vec::with_capacity(num_prefixes);
        for i in 0..num_prefixes {
            prefixes.push((Prefix(i as u32), AsId(65300 + i as u32)));
        }

        let mut component_known_prefixes = [HashSet::new(), HashSet::new()];

        for node in external_nodes.iter().cloned() {
            let node_as_id = self.graph.node_weight(node).unwrap().as_id;
            for (prefix, origin_as) in prefixes.iter() {
                // check the probability
                let choice: f64 = self.rng.gen();
                if choice <= probability {
                    trace!(
                        "{} advertises {}",
                        self.graph.node_weight(node).unwrap().name,
                        prefix.0
                    );
                    net.advertise_external_route(
                        node,
                        *prefix,
                        vec![node_as_id, *origin_as],
                        None,
                        None,
                    )?;
                    match self.graph.neighbors(node).next() {
                        Some(neighbor) => {
                            if self.disconnected.contains(&neighbor) {
                                component_known_prefixes[1].insert(*prefix);
                            } else {
                                component_known_prefixes[0].insert(*prefix);
                            }
                        }
                        None => {}
                    }
                }
            }
        }

        // if we are disconnected, we need to make sure that both components know the same prefixes
        if !self.disconnected.is_empty() {
            // prepare the must known prefixes and the lookup for the AS id
            let must_known_prefixes: HashSet<Prefix> =
                prefixes.iter().map(|(p, _)| p).cloned().collect();
            let prefix_as: HashMap<Prefix, AsId> = prefixes.iter().cloned().collect();

            // get the set of all external routers in the components
            let mut component_external_routers = [
                self.graph
                    .node_indices()
                    .filter(|idx| !self.disconnected.contains(idx))
                    .map(|idx| self.graph.neighbors(idx))
                    .flatten()
                    .filter(|idx| self.graph.node_weight(*idx).unwrap().external)
                    .collect::<Vec<_>>(),
                self.graph
                    .node_indices()
                    .filter(|idx| self.disconnected.contains(idx))
                    .map(|idx| self.graph.neighbors(idx))
                    .flatten()
                    .filter(|idx| self.graph.node_weight(*idx).unwrap().external)
                    .collect::<Vec<_>>(),
            ];
            // sort and dedup them both
            component_external_routers[0].sort();
            component_external_routers[1].sort();
            component_external_routers[0].dedup();
            component_external_routers[1].dedup();

            // go through both components
            for (known_prefixes, external_routers) in
                component_known_prefixes.iter().zip(component_external_routers.iter())
            {
                // compute the difference between the components
                let mut differences: Vec<Prefix> =
                    must_known_prefixes.difference(&known_prefixes).cloned().collect();
                differences.sort_by_key(|x| x.0);

                // for each of the missing prefixes, we need to advertise at a single router
                for prefix in differences {
                    let origin_as = prefix_as.get(&prefix).expect("must be known at this point");
                    // choose a random router
                    let node = external_routers
                        .get(self.rng.gen_range(0, external_routers.len()))
                        .unwrap();
                    let node_as_id = self.graph.node_weight(*node).unwrap().as_id;

                    // advertise the prefix
                    trace!(
                        "{} advertises {}",
                        self.graph.node_weight(*node).unwrap().name,
                        prefix.0
                    );
                    net.advertise_external_route(
                        *node,
                        prefix,
                        vec![node_as_id, *origin_as],
                        None,
                        None,
                    )?;
                }
            }
        }

        Ok(())
    }

    /// Returns the current configuration based on the already prepared data.
    ///
    /// # Panics
    /// This function panics if the network was not already generated, and the node indexes are not
    /// yet present!
    pub fn get_config(&self) -> Result<Config, ZooTopologyError> {
        self.prepare_config(true)
    }

    /// Internal function to prepare the config, with some flags to describe how the config should
    /// be generated.
    fn prepare_config(&self, generate_ebgp: bool) -> Result<Config, ZooTopologyError> {
        info!("Generate configuration.");
        let mut c = Config::new();

        // first, add all igp link weights
        for edge_idx in self.graph.edge_indices() {
            let (src, dst) = self.graph.edge_endpoints(edge_idx).unwrap();
            let src_net_idx = self.graph.node_weight(src).unwrap().net_idx.unwrap();
            let dst_net_idx = self.graph.node_weight(dst).unwrap().net_idx.unwrap();
            let weight = *self.graph.edge_weight(edge_idx).unwrap();
            trace!(
                "Configure link {} <--> {}, weight: {:.0}",
                self.graph.node_weight(src).unwrap().name,
                self.graph.node_weight(dst).unwrap().name,
                weight
            );
            c.add(IgpLinkWeight { source: src_net_idx, target: dst_net_idx, weight })
                .map_err(|_| ZooTopologyError::MultipleLinkWeights)?;
            c.add(IgpLinkWeight { target: src_net_idx, source: dst_net_idx, weight })
                .map_err(|_| ZooTopologyError::MultipleLinkWeights)?;
        }

        // then, add all ebgp sessions
        if generate_ebgp {
            for external_router in self
                .graph
                .node_indices()
                .into_iter()
                .filter(|x| self.graph.node_weight(*x).unwrap().external)
            {
                for neighbor in self.graph.neighbors(external_router) {
                    let ext_net_idx =
                        self.graph.node_weight(external_router).unwrap().net_idx.unwrap();
                    let int_net_idx = self.graph.node_weight(neighbor).unwrap().net_idx.unwrap();
                    trace!(
                        "Add eBGP session: {} --> {}",
                        self.graph.node_weight(int_net_idx).unwrap().name,
                        self.graph.node_weight(ext_net_idx).unwrap().name,
                    );
                    match c.add(BgpSession {
                        source: ext_net_idx,
                        target: int_net_idx,
                        session_type: EBgp,
                    }) {
                        Ok(()) => {}
                        Err(_) => return Err(ZooTopologyError::MultipleBgpSessions),
                    }
                }
            }
        }

        // then, add the ibgp full mesh between the root nodes. But only, if it is enabled
        if self.create_ibgp_peers {
            let roots: Vec<NodeIdx> = self.ibgp_roots.iter().cloned().collect();
            for ia in 0..roots.len() {
                for ib in (ia + 1)..roots.len() {
                    let (src, dst) = (roots[ia], roots[ib]);
                    let src_net_idx = self.graph.node_weight(src).unwrap().net_idx.unwrap();
                    let dst_net_idx = self.graph.node_weight(dst).unwrap().net_idx.unwrap();
                    trace!(
                        "Add iBGP peer session: {} --> {}",
                        self.graph.node_weight(src_net_idx).unwrap().name,
                        self.graph.node_weight(dst_net_idx).unwrap().name,
                    );
                    c.add(BgpSession {
                        source: src_net_idx,
                        target: dst_net_idx,
                        session_type: IBgpPeer,
                    })
                    .unwrap();
                }
            }
        }

        // finally, add all iBGP client -> RR sessions
        for edge_idx in self.ibgp_graph.edge_indices() {
            let (src, dst) = self.ibgp_graph.edge_endpoints(edge_idx).unwrap();
            let src_net_idx = self.graph.node_weight(src).unwrap().net_idx.unwrap();
            let dst_net_idx = self.graph.node_weight(dst).unwrap().net_idx.unwrap();
            trace!(
                "Add iBGP RR-client session: {} --> {}",
                self.graph.node_weight(src_net_idx).unwrap().name,
                self.graph.node_weight(dst_net_idx).unwrap().name,
            );
            c.add(BgpSession {
                source: src_net_idx,
                target: dst_net_idx,
                session_type: IBgpClient,
            })
            .unwrap();
        }

        Ok(c)
    }

    /// Generates a iBGP route reflector topology, where the root is the only route reflector, and
    /// all other internal routers are connected to it.
    fn ibgp_single_route_reflector(&mut self, root: NodeIdx) -> &mut Self {
        // clear the already existing information.
        self.ibgp_roots.drain();
        self.ibgp_graph.clear_edges();

        // setup the root node
        self.ibgp_roots.insert(root);

        // iterate over all internal routers, except the root
        for node in self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .filter(|x| x != &root)
            // we need to collect because we already borrow self inside the filter.
            .collect::<Vec<_>>()
        {
            self.ibgp_graph.add_edge(root, node, ());
        }

        self
    }

    /// Generates a iBGP route reflector topology, where the two root are the only route reflectors,
    /// and all other internal routers are connected to both of them. The two route reflectors have
    /// a peer session between them.
    fn ibgp_two_route_reflectors(&mut self, root: [NodeIdx; 2]) -> &mut Self {
        // clear the already existing information.
        self.ibgp_roots.drain();
        self.ibgp_graph.clear_edges();

        // setup the root node
        self.ibgp_roots.insert(root[0]);
        self.ibgp_roots.insert(root[1]);

        // iterate over all internal routers, except the root
        for node in self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .filter(|x| x != &root[0] && x != &root[1])
            // we need to collect because we already borrow self inside the filter.
            .collect::<Vec<_>>()
        {
            self.ibgp_graph.add_edge(root[0], node, ());
            self.ibgp_graph.add_edge(root[1], node, ());
        }
        self
    }

    /// Generates a iBGP route reflector topology, by selecting n routers as route reflectors,
    /// connected in a full mesh, and every other router to choose the closest reflector.
    fn ibgp_general_route_reflectors(
        &mut self,
        num_roots: usize,
    ) -> Result<&mut Self, ZooTopologyError> {
        // clear the already existing information.
        self.ibgp_roots.drain();
        self.ibgp_graph.clear_edges();

        // choose the most important n route reflectors
        let mut internal_nodes = self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .collect::<Vec<_>>();
        internal_nodes.sort_by_key(|x| {
            self.graph
                .neighbors(*x)
                .filter(|n| !self.graph.node_weight(*n).unwrap().external)
                .count()
        });
        self.ibgp_roots = internal_nodes.into_iter().rev().take(num_roots).collect();

        for node in self
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !self.graph.node_weight(*x).unwrap().external)
            .filter(|x| !self.ibgp_roots.contains(x))
            // we need to collect because we already borrow self inside the filter.
            .collect::<Vec<_>>()
        {
            let closest_root = self.find_closest_root(node)?;
            self.ibgp_graph.add_edge(closest_root, node, ());
        }

        Ok(self)
    }

    /// helper function to find the closest root in BFS manner.
    fn find_closest_root(&self, node: NodeIndex<u32>) -> Result<NodeIndex<u32>, ZooTopologyError> {
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();

        queue.push_back(node);
        while !queue.is_empty() {
            let node = queue.pop_front().unwrap();
            for neighbor in self.graph.neighbors_undirected(node) {
                if self.ibgp_roots.contains(&neighbor) {
                    return Ok(neighbor);
                }
                if !visited.contains(&neighbor) {
                    visited.insert(neighbor);
                    queue.push_back(neighbor);
                }
            }
        }

        Err(ZooTopologyError::NoClosestRootFound)
    }
}

/// Scenario to apply to a topology in TopologyZoo
#[derive(Debug, Clone)]
pub enum Scenario {
    /// Scenario, where we start with a iBGP full mesh, and end up with a topology, where one single
    /// router is elected as a Route Reflectors, and all others pair with that router.
    FullMesh2RouteReflector,
    /// Scenario, where we start with a topology, where one single router is elected as a Route
    /// Reflectors, and all others pair with that router, and we end up wiht an iBGP full mesh.
    RouteReflector2FullMesh,
    /// Scenario, where every IGP weight is doubled
    DoubleIgpWeight,
    /// Scenario, where every IGP weight is halved
    HalveIgpWeight,
    /// Scenario, where we start with a single Route-Reflector, to which all other routers pair, and
    /// end with a second Route-Reflector as a backup, where all other routers have a session to
    /// both reflectors, and the two reflectors are connected with a peer.
    IntroduceSecondRouteReflector,
    /// Scenario, where we start with a second Route-Reflector as a backup, where all other routers
    /// have a session to both reflectors, and the two reflectors are connected with a peer, and end
    /// with a single Route-Reflector, to which all other routers pair.
    RemoveSecondRouteReflector,
    /// Scenario, where we start with two different connected components, both having connection to
    /// the outside world, and we merge them by adding the links in between.
    NetworkAcquisition,
    /// Reverse scenario of the Network Acquisition
    NetworkSplit,
    /// Shutdown a router by setting all link weights around a specific router to infinity
    DisconnectRouter,
    /// Introduce a new router by starting with infinite weight of all links around a specific
    /// router, and setting them to something reasonable.
    ConnectRouter,
    /// Scenario where every local-pref configuration is doulbed
    DoubleLocalPref,
    /// Scenario where every local-pref is halved
    HalveLocalPref,
    /// Test scenario for verifying transient state conditions. This scenario contains only a single
    /// modifier, which adds an eBGP session.
    VerifyTransientCondition,
    /// Test scenario for verifying transient state conditions. This scenario contains only a single
    /// modifier, which adds an eBGP session.
    VerifyTransientConditionReverse,
}

impl Scenario {
    fn is_inverse(&self) -> bool {
        match self {
            Scenario::FullMesh2RouteReflector
            | Scenario::DoubleIgpWeight
            | Scenario::IntroduceSecondRouteReflector
            | Scenario::NetworkAcquisition
            | Scenario::DisconnectRouter
            | Scenario::DoubleLocalPref
            | Scenario::VerifyTransientCondition => false,
            Scenario::RouteReflector2FullMesh
            | Scenario::HalveIgpWeight
            | Scenario::RemoveSecondRouteReflector
            | Scenario::NetworkSplit
            | Scenario::ConnectRouter
            | Scenario::HalveLocalPref
            | Scenario::VerifyTransientConditionReverse => true,
        }
    }
}

/// Node Data of ZooTopology graph
#[derive(Debug, Clone)]
pub struct NodeData {
    /// Name of the node
    pub name: String,
    /// Wether the node is an external router or not
    pub external: bool,
    /// As Id
    pub as_id: AsId,
    /// The index of the node in `netsim::network::Network`
    pub net_idx: Option<RouterId>,
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn link_weight() {
        let gml_filename: String = format!("{}/test_files/switch.gml", env!("CARGO_MANIFEST_DIR"));
        let mut t = ZooTopology::new(gml_filename, 42).unwrap();

        // test before
        for edge_idx in t.graph.edge_indices() {
            let weight = t.graph.edge_weight(edge_idx).unwrap();
            let weight = weight.round() as u32;
            assert_eq!(weight, 1);
        }

        // randomize link weights
        let max_val = 100;
        t.randomize_link_weights(max_val);

        // test after
        for edge_idx in t.graph.edge_indices() {
            let weight = t.graph.edge_weight(edge_idx).unwrap();
            let weight = weight.round() as u32;
            assert!(weight >= 1);
            assert!(weight <= 100);
        }
    }

    #[test]
    fn ibgp_spanning_forest() {
        let gml_filename: String = format!("{}/test_files/switch.gml", env!("CARGO_MANIFEST_DIR"));
        let mut t = ZooTopology::new(gml_filename, 42).unwrap();

        // check that the ibgp graph has the same nodes as graph, but has absolutely no edges
        assert_eq!(t.ibgp_graph.node_count(), t.graph.node_count());
        assert_eq!(t.ibgp_graph.edge_count(), 0);

        t.ibgp_spanning_forest(4);

        assert_eq!(t.ibgp_roots.len(), 4);

        // check that everything is connected properly
        for node_idx in t.ibgp_graph.node_indices() {
            let node_data = t.graph.node_weight(node_idx).unwrap();
            if node_data.external {
                // assert that the node has no neighbor in the ibgp graph
                assert_eq!(t.ibgp_graph.neighbors_undirected(node_idx).next(), None);
            } else {
                // assert that either it has a single incoming edge, or is root
                if t.ibgp_roots.contains(&node_idx) {
                    // can have no incoming edge
                    assert_eq!(
                        t.ibgp_graph.neighbors_directed(node_idx, Direction::Incoming).next(),
                        None
                    );
                } else {
                    // can have only one incoming edge
                    let mut parents_iter =
                        t.ibgp_graph.neighbors_directed(node_idx, Direction::Incoming);
                    assert!(parents_iter.next().is_some());
                    assert!(parents_iter.next().is_none());
                }
            }
        }
    }

    #[test]
    fn ibgp_full_mesh() {
        let gml_filename: String = format!("{}/test_files/switch.gml", env!("CARGO_MANIFEST_DIR"));
        let mut t = ZooTopology::new(gml_filename, 42).unwrap();

        // check that the ibgp graph has the same nodes as graph, but has absolutely no edges
        assert_eq!(t.ibgp_graph.node_count(), t.graph.node_count());
        assert_eq!(t.ibgp_graph.edge_count(), 0);

        t.ibgp_full_mesh();

        let num_internal_nodes = t
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !t.graph.node_weight(*x).unwrap().external)
            .count();

        assert_eq!(t.ibgp_roots.len(), num_internal_nodes);
        assert_eq!(t.ibgp_graph.edge_count(), 0);
    }

    #[test]
    fn ibgp_single_route_reflector() {
        let gml_filename: String = format!("{}/test_files/switch.gml", env!("CARGO_MANIFEST_DIR"));
        let mut t = ZooTopology::new(gml_filename, 42).unwrap();

        // check that the ibgp graph has the same nodes as graph, but has absolutely no edges
        assert_eq!(t.ibgp_graph.node_count(), t.graph.node_count());
        assert_eq!(t.ibgp_graph.edge_count(), 0);

        t.ibgp_single_route_reflector_named("Bern").unwrap();

        let num_internal_nodes = t
            .graph
            .node_indices()
            .into_iter()
            .filter(|x| !t.graph.node_weight(*x).unwrap().external)
            .count();

        assert_eq!(t.ibgp_roots.len(), 1);
        assert_eq!(t.ibgp_graph.edge_count(), num_internal_nodes - 1);

        let root = t.ibgp_roots.iter().cloned().next().unwrap();

        // check that everything is connected properly
        for node_idx in t.ibgp_graph.node_indices() {
            let node_data = t.graph.node_weight(node_idx).unwrap();
            if node_data.external {
                // assert that the node has no neighbor in the ibgp graph
                assert_eq!(t.ibgp_graph.neighbors_undirected(node_idx).next(), None);
            } else {
                // assert that either it has a single incoming edge, or is root
                if t.ibgp_roots.contains(&node_idx) {
                    // can have no incoming edge
                    assert_eq!(
                        t.ibgp_graph.neighbors_directed(node_idx, Direction::Incoming).next(),
                        None
                    );
                    // check that its name is Bern
                    assert_eq!(t.graph.node_weight(node_idx).unwrap().name, "Bern");
                } else {
                    // this route needs to have exactly one edge to the root
                    let mut parents_iter =
                        t.ibgp_graph.neighbors_directed(node_idx, Direction::Incoming);
                    assert_eq!(parents_iter.next(), Some(root));
                    assert!(parents_iter.next().is_none());
                }
            }
        }
    }

    #[test]
    fn advertise_prefix() {
        let gml_filename: String = format!("{}/test_files/switch.gml", env!("CARGO_MANIFEST_DIR"));
        let mut t = ZooTopology::new(gml_filename, 42).unwrap();
        t.ibgp_spanning_forest(4);

        // generate the network
        let mut net = t.get_net();
        net.set_config(&t.get_config().unwrap()).unwrap();
        t.advertise_prefixes(&mut net, 100, 1.0).unwrap();
        assert_eq!(net.get_known_prefixes().len(), 100);

        // check if all nodes know all 100 prefixes
        for router_id in net.get_routers() {
            for prefix in net.get_known_prefixes() {
                assert!(net.get_route(router_id, *prefix).is_ok())
            }
        }
    }
}