forked from opsmill/infrahub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfrastructure_edge.py
2176 lines (1844 loc) · 81.8 KB
/
infrastructure_edge.py
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
import copy
import logging
import time
import uuid
from collections import defaultdict
from enum import Enum
from ipaddress import IPv4Network, IPv6Network
from typing import Optional, cast
from infrahub_sdk import InfrahubClient
from infrahub_sdk.batch import InfrahubBatch
from infrahub_sdk.protocols import (
CoreAccount,
CoreAccountGroup,
CoreIPAddressPool,
CoreIPPrefixPool,
CoreStandardGroup,
IpamNamespace,
)
from infrahub_sdk.protocols_base import CoreNode
from infrahub_sdk.store import NodeStore
from infrahub_sdk.uuidt import UUIDT
from protocols import (
InfraAutonomousSystem,
InfraBGPSession,
InfraCircuit,
InfraCircuitEndpoint,
InfraDevice,
InfraInterfaceL2,
InfraInterfaceL3,
InfraLagInterfaceL2,
InfraMlagDomain,
InfraMlagInterfaceL2,
InfraPlatform,
InfraVLAN,
IpamIPAddress,
IpamIPPrefix,
LocationCountry,
LocationSite,
OrganizationProvider,
)
from pydantic import BaseModel, ConfigDict, Field
PROFILES = {
"small": {"num_sites": 2, "num_device_per_site": 6, "has_bgp_mesh": False, "has_branch": False},
"medium": {"num_sites": 5, "num_device_per_site": 6, "has_bgp_mesh": True, "has_branch": True},
"large": {"num_sites": 10, "num_device_per_site": 26, "has_bgp_mesh": False, "has_branch": False},
"x-large": {"num_sites": 50, "num_device_per_site": 52, "has_bgp_mesh": False, "has_branch": False},
"xx-large": {"num_sites": 100, "num_device_per_site": 102, "has_bgp_mesh": False, "has_branch": False},
"ultimate": {"num_sites": 200, "num_device_per_site": 204, "has_bgp_mesh": True, "has_branch": True},
}
class ConfigError(Exception):
pass
# Define the global configuration object
class GlobalConfig:
def __init__(self) -> None:
self.default_profile_name = "medium"
self.num_sites = None
self.num_device_per_site = None
self.has_bgp_mesh = False
self.has_branch = False
def __set_config(self, num_sites: int, num_device_per_site: int, has_bgp_mesh: bool, has_branch: bool) -> None:
# TODO: I guess it could be defined in the attribute itself?
# Ensure that num_site is between boudaries
if 2 <= int(num_sites) <= 200:
self.num_sites = int(num_sites)
else:
raise ConfigError(f"Value for `num_sites` ({num_sites}) should be between 2 and 200.")
# Ensure that num_device_per_site is between boudaries
if 6 <= int(num_device_per_site) <= 204:
self.num_device_per_site = int(num_device_per_site)
else:
raise ConfigError(f"Value for `num_device_per_site` ({num_device_per_site}) should be between 6 and 204.")
self.has_bgp_mesh = has_bgp_mesh
self.has_branch = has_branch
def load_config(
self,
profile: str = None,
num_sites: int = None,
num_device_per_site: int = None,
has_bgp_mesh: bool = None,
has_branch: bool = None,
) -> None:
if profile:
# Warn user that we are going to ignore his input
if num_sites or num_device_per_site or has_bgp_mesh or has_branch:
raise ConfigError("You can't set additional config items if you've already provided a profile.")
# Make sure profile exists
if profile not in PROFILES:
raise ConfigError(
f"Value for profile ({profile}) doesn't exist, please pick one among {PROFILES.keys()}."
)
# Load prebuilt profile
profile_obj: dict = PROFILES[profile]
self.__set_config(
profile_obj["num_sites"],
profile_obj["num_device_per_site"],
profile_obj["has_bgp_mesh"],
profile_obj["has_branch"],
)
else:
# Load from manual arguments, if provided
# If user only provides a part of the arguments e.g. only `number of site`
# we fall back on medium profile by default
default_profile: dict = PROFILES[self.default_profile_name]
self.__set_config(
num_sites=num_sites if num_sites is not None else default_profile["num_sites"],
num_device_per_site=num_device_per_site
if num_device_per_site is not None
else default_profile["num_device_per_site"],
has_bgp_mesh=has_bgp_mesh if has_bgp_mesh is not None else default_profile["has_bgp_mesh"],
has_branch=has_branch if has_branch is not None else default_profile["has_branch"],
)
def __repr__(self) -> str:
return f"Config(Sites: {self.num_sites}, Devices per site: {self.num_device_per_site}, BGP mesh: {self.has_bgp_mesh}, Additional branches: {self.has_branch})"
def translate_str_to_bool(key: str, value: str) -> bool:
if value == "True":
return True
if value == "False":
return False
raise TypeError(f"Value for {key} should be 'True' or 'False'")
# pylint: skip-file
class Account(BaseModel):
name: str
password: str
account_type: str
role: str
class Asn(BaseModel):
asn: int
organization: str
@property
def name(self) -> str:
return f"AS{self.asn}"
class BgpPeerGroup(BaseModel):
name: str
import_policies: str
export_policies: str
local_as: str
remote_as: Optional[str] = Field(default=None)
class Device(BaseModel):
name: str
status: str
type: str
profile: str
role: str
tags: list[str]
platform: str
_idx: int
@property
def l2_interface_names(self) -> list[str]:
INTERFACE_L2_NAMES = {
"7280R3": ["Ethernet11", "Ethernet12"],
"ASR1002-HX": ["Ethernet11", "Ethernet12"],
"MX204": ["et-0/0/3"],
"7010TX-48": [f"Ethernet{idx}" for idx in range(1, 49)],
}
return INTERFACE_L2_NAMES.get(self.type, [])
@property
def l3_interface_names(self) -> list[str]:
INTERFACE_L3_NAMES = {
"7280R3": [
"Ethernet1",
"Ethernet2",
"Ethernet3",
"Ethernet4",
"Ethernet5",
"Ethernet6",
"Ethernet7",
"Ethernet8",
"Ethernet9",
"Ethernet10",
],
"ASR1002-HX": [
"Ethernet1",
"Ethernet2",
"Ethernet3",
"Ethernet4",
"Ethernet5",
"Ethernet6",
"Ethernet7",
"Ethernet8",
"Ethernet9",
"Ethernet10",
],
"7010TX-48": [],
"MX204": ["et-0/0/0", "et-0/0/1", "et-0/0/2"],
}
return INTERFACE_L3_NAMES.get(self.type, [])
class Group(BaseModel):
name: str
label: str
class InterfaceProfile(BaseModel):
name: str
mtu: int
kind: str
@property
def profile_kind(self) -> str:
return f"Profile{self.kind}"
class P2pNetwork(BaseModel):
site1: str
site2: str
edge: int
circuit: str
pool: Optional[IpamIPPrefix] = None
model_config = ConfigDict(arbitrary_types_allowed=True)
@property
def identifier(self) -> str:
return f"{self.site1_device}__{self.site2_device}"
@property
def site1_device(self) -> str:
return f"{self.site1}-edge{self.edge}"
@property
def site2_device(self) -> str:
return f"{self.site2}-edge{self.edge}"
@property
def provider_name(self) -> str:
if self.edge == 1:
return "Lumen"
return "Zayo"
def get_pool(self) -> IpamIPPrefix:
if self.pool:
return self.pool
raise Exception("the variable pool hasn't been initilized yet")
class Platform(BaseModel):
name: str
nornir_platform: str
napalm_driver: str
netmiko_device_type: str
ansible_network_os: str
class Organization(BaseModel):
name: str
type: str
@property
def kind(self) -> str:
return f"Organization{self.type.title()}"
class Site(BaseModel):
name: str
country: str
city: str
contact: str
class Vlan(BaseModel):
id: int
role: str
CONTINENT_COUNTRIES = {
"North America": ["United States of America", "Canada"],
"South America": ["Mexico", "Brazil"],
"Africa": ["Morocco", "Senegal"],
"Europe": ["France", "Spain", "Italy"],
"Asia": ["Japan", "China"],
"Oceania": ["Australia", "New Zealand"],
}
SITES = [
Site(name="atl", country="United States of America", city="Atlanta", contact="Bailey Li"),
Site(name="ord", country="United States of America", city="Chicago", contact="Kayden Kennedy"),
Site(name="jfk", country="United States of America", city="New York", contact="Micaela Marsh"),
Site(name="den", country="United States of America", city="Denver", contact="Francesca Wilcox"),
Site(name="dfw", country="United States of America", city="Dallas", contact="Carmelo Moran"),
Site(name="iad", country="United States of America", city="Washington D.C.", contact="Avery Jimenez"),
Site(name="sea", country="United States of America", city="Seattle", contact="Charlotte Little"),
Site(name="sfo", country="United States of America", city="San Francisco", contact="Taliyah Sampson"),
Site(name="iah", country="United States of America", city="Houston", contact="Fernanda Solomon"),
Site(name="mco", country="United States of America", city="Orlando", contact="Arthur Rose"),
]
PLATFORMS = (
Platform(
name="Cisco IOS",
nornir_platform="ios",
napalm_driver="ios",
netmiko_device_type="cisco_ios",
ansible_network_os="ios",
),
Platform(
name="Cisco NXOS SSH",
nornir_platform="nxos_ssh",
napalm_driver="nxos_ssh",
netmiko_device_type="cisco_nxos",
ansible_network_os="nxos",
),
Platform(
name="Juniper JunOS",
nornir_platform="junos",
napalm_driver="junos",
netmiko_device_type="juniper_junos",
ansible_network_os="junos",
),
Platform(
name="Arista EOS",
nornir_platform="eos",
napalm_driver="eos",
netmiko_device_type="arista_eos",
ansible_network_os="eos",
),
)
class DevicePatternName(str, Enum):
LEAF = "LEAF"
CORE = "CORE"
EDGE = "EDGE"
DEVICE_PATTERNS = {
DevicePatternName.LEAF: Device(
name="leaf",
status="active",
type="7010TX-48",
profile="profile1",
role="leaf",
tags=["red", "green"],
platform="Cisco IOS",
),
DevicePatternName.CORE: Device(
name="core",
status="active",
type="MX204",
profile="profile1",
role="core",
tags=["blue"],
platform="Juniper JunOS",
),
DevicePatternName.EDGE: Device(
name="edge",
status="active",
type="7280R3",
profile="profile1",
role="edge",
tags=["red", "green"],
platform="Arista EOS",
),
}
DEVICE_STATUSES = ["active", "provisioning", "drained"]
class SiteDesign:
def __init__(self, number_of_device: int) -> None:
"""Takes the number of devices that need to be created on a given site.
This method will decide how many device of each type to create and return all those objects as a list."""
if number_of_device > 0:
self.number_of_device = number_of_device
else:
raise ValueError("number_of_device must be non-negative")
# There is a special case where there are 6 device...
if number_of_device == 6:
# Two of each
self.num_edge_device = 2
self.num_core_device = 2
self.num_leaf_device = 2
# Otherwise we try to compute something that makes a little bit of sense...
else:
# First we decide how many edge device we will spin
# The rule is the following:
# - between 0 -> 50 = 2 edges
# - then we add 2 edges every 50 devices
num_edge_device: int = 2
num_edge_device += (self.number_of_device // 50) * 2
self.num_edge_device = num_edge_device
# Second goes core device, we take one third of the remaining device allocation
self.num_core_device: int = (self.number_of_device - self.num_edge_device) // 3
# Finally we allocate what's remaining as leaf
self.num_leaf_device: int = self.number_of_device - self.num_edge_device - self.num_core_device
def device_generator(self, number: int, device_pattern_name: DevicePatternName) -> list[Device]:
"""Generate a list of devices following the pattern provided."""
result: list[Device] = []
for i in range(1, number + 1):
# Take the pattern as baseline
current_device: Device = copy.copy(DEVICE_PATTERNS[device_pattern_name])
# Start the tweaking
current_device.name += str(i)
current_device._idx = i
# Add it to the list
result.append(current_device)
# Return devices
return result
def implement(self) -> list[Device]:
# Build the list of device
result: list[Device] = []
# Generate the list and return it
result.extend(self.device_generator(self.num_edge_device, DevicePatternName.EDGE))
result.extend(self.device_generator(self.num_core_device, DevicePatternName.CORE))
result.extend(self.device_generator(self.num_leaf_device, DevicePatternName.LEAF))
return result
def __repr__(self) -> str:
return f"SiteDesign(Edge device: {self.num_edge_device}, Core device: {self.num_core_device}, Leaf device: {self.num_leaf_device})"
NETWORKS_SUPERNET = IPv4Network("10.0.0.0/8")
NETWORKS_SUPERNET_IPV6 = IPv6Network("2001:DB8::/100")
MANAGEMENT_NETWORKS = IPv4Network("172.16.0.0/16")
# Here with current logic we allocate 3 /29 per edge device
# We have max 10 edges on a single site, max 200 sites
# 3*10*200 = 6000 -> we need to be able to fit 6000 /29
# Thus we need a /16
NETWORKS_POOL_EXTERNAL_SUPERNET = IPv4Network("203.111.0.0/16")
ACTIVE_STATUS = "active"
BACKBONE_ROLE = "backbone"
def site_generator(nbr_site: int = 2) -> list[Site]:
"""Generate a list of site names by iterating over the list of SITES defined above and by increasing the id.
site_names_generator(nbr_site=5)
result >> ["atl1", "ord1", "jfk1", "den1", "dfw1"]
site_names_generator(nbr_site=12)
result >> ["atl1", "ord1", "jfk1", "den1", "dfw1", "iad1", "bkk1", "sfo1", "iah1", "mco1", "atl2", "ord2"]
"""
sites: list[Site] = []
# Calculate how many loop over the entire list we need to make
# and how many site we need to generate on the last loop
nbr_loop = (int(nbr_site / len(SITES))) + 1
nbr_last_loop = nbr_site % len(SITES) or len(SITES)
for idx in range(1, 1 + nbr_loop):
nbr_this_loop = len(SITES)
if idx == nbr_loop:
nbr_this_loop = nbr_last_loop
sites.extend(
[
Site(name=f"{site.name}{idx}", country=site.country, city=site.city, contact=site.contact)
for site in SITES[:nbr_this_loop]
]
)
return sites
INTERFACE_MGMT_NAME = {
"7280R3": "Management0",
"7010TX-48": "Management0",
"ASR1002-HX": "Management0",
"MX204": "MGMT",
}
LAG_INTERFACE_L2 = {
"7280R3": [{"name": "port-channel1", "lacp": "Active", "members": ["Ethernet11", "Ethernet12"]}],
"7010TX-48": [
{
"name": "port-channel1",
"description": "MLAG peer link",
"lacp": "Active",
"members": ["Ethernet1", "Ethernet2"],
},
{
"name": "port-channel2",
"description": "MLAG to Server",
"lacp": "Active",
"members": ["Ethernet5", "Ethernet6"],
},
],
}
INTERFACE_L3_ROLES_MAPPING = {
"edge": [
"peer",
"peer",
"backbone",
"backbone",
"upstream",
"upstream",
"spare",
"spare",
"peering",
"spare",
"spare",
"spare",
],
"core": [
"backbone",
"backbone",
"backbone",
"spare",
],
"leaf": [],
}
INTERFACE_L2_ROLES_MAPPING = {
"leaf": [
"peer",
"peer",
],
}
LAG_INTERFACE_L2_ROLES_MAPPING: dict[str, dict[str, str]] = {
"leaf": {"port-channel1": "peer", "port-channel2": "server"}
}
INTERFACE_L2_MODE_MAPPING = {"peer": "Trunk (ALL)"}
MLAG_DOMAINS = {"leaf": {"domain_id": 1, "peer_interfaces": ["port-channel1", "port-channel1"]}}
MLAG_INTERFACE_L2 = {
"leaf": [
{
"mlag_id": 2,
"mlag_domain": 1,
"members": ["port-channel2", "port-channel2"],
}
]
}
TAGS = ["blue", "green", "red"]
ORGANIZATIONS = (
Organization(name="Arelion", type="provider"),
Organization(name="Colt Technology Services", type="provider"),
Organization(name="Verizon Business", type="provider"),
Organization(name="GTT Communications", type="provider"),
Organization(name="Hurricane Electric", type="provider"),
Organization(name="Lumen", type="provider"),
Organization(name="Zayo", type="provider"),
Organization(name="Equinix", type="provider"),
Organization(name="Interxion", type="provider"),
Organization(name="PCCW Global", type="provider"),
Organization(name="Orange S.A", type="provider"),
Organization(name="Tata Communications", type="provider"),
Organization(name="Sprint", type="provider"),
Organization(name="NTT America", type="provider"),
Organization(name="Cogent Communications", type="provider"),
Organization(name="Comcast Cable Communication", type="provider"),
Organization(name="Telecom Italia Sparkle", type="provider"),
Organization(name="AT&T Services", type="provider"),
Organization(name="Duff", type="tenant"),
Organization(name="Juniper", type="manufacturer"),
Organization(name="Cisco", type="manufacturer"),
Organization(name="Arista", type="manufacturer"),
)
ASNS = (
Asn(asn=1299, organization="Arelion"),
Asn(asn=64496, organization="Duff"),
Asn(asn=8220, organization="Colt Technology Services"),
Asn(asn=701, organization="Verizon Business"),
Asn(asn=3257, organization="GTT Communications"),
Asn(asn=6939, organization="Hurricane Electric"),
Asn(asn=3356, organization="Lumen"),
Asn(asn=6461, organization="Zayo"),
Asn(asn=24115, organization="Equinix"),
Asn(asn=20710, organization="Interxion"),
Asn(asn=3491, organization="PCCW Global"),
Asn(asn=5511, organization="Orange S.A"),
Asn(asn=6453, organization="Tata Communications"),
Asn(asn=1239, organization="Sprint"),
Asn(asn=2914, organization="NTT America"),
Asn(asn=174, organization="Cogent Communications"),
Asn(asn=7922, organization="Comcast Cable Communication"),
Asn(asn=6762, organization="Telecom Italia Sparkle"),
Asn(asn=7018, organization="AT&T Services"),
)
INTERFACE_OBJS: dict[str, list[InfraInterfaceL3]] = defaultdict(list)
ACCOUNTS = (
Account(name="pop-builder", account_type="Script", password="Password123", role="read-write"),
Account(name="CRM Synchronization", account_type="Script", password="Password123", role="read-write"),
Account(name="Jack Bauer", account_type="User", password="Password123", role="read-only"),
Account(name="Chloe O'Brian", account_type="User", password="Password123", role="read-write"),
Account(name="David Palmer", account_type="User", password="Password123", role="read-write"),
Account(name="Operation Team", account_type="User", password="Password123", role="read-only"),
Account(name="Engineering Team", account_type="User", password="Password123", role="read-write"),
Account(name="Architecture Team", account_type="User", password="Password123", role="read-only"),
)
GROUPS = (
Group(name="edge_router", label="Edge Router"),
Group(name="core_router", label="Core Router"),
Group(name="cisco_devices", label="Cisco Devices"),
Group(name="arista_devices", label="Arista Devices"),
Group(name="upstream_interfaces", label="Upstream Interfaces"),
Group(name="backbone_interfaces", label="Backbone Interfaces"),
Group(name="maintenance_circuits", label="Circuits in Maintenance"),
Group(name="provisioning_circuits", label="Circuits in Provisioning"),
Group(name="backbone_services", label="Backbone Services"),
)
BGP_PEER_GROUPS = (
BgpPeerGroup(
name="POP_INTERNAL",
import_policies="IMPORT_INTRA_POP",
export_policies="EXPORT_INTRA_POP",
local_as="Duff",
remote_as="Duff",
),
BgpPeerGroup(
name="POP_GLOBAL",
import_policies="IMPORT_POP_GLOBAL",
export_policies="EXPORT_POP_GLOBLA",
local_as="Duff",
remote_as=None,
),
BgpPeerGroup(
name="UPSTREAM_DEFAULT",
import_policies="IMPORT_UPSTREAM",
export_policies="EXPORT_PUBLIC_PREFIX",
local_as="Duff",
remote_as=None,
),
BgpPeerGroup(
name="UPSTREAM_ARELION",
import_policies="IMPORT_UPSTREAM",
export_policies="EXPORT_PUBLIC_PREFIX",
local_as="Duff",
remote_as="Arelion",
),
BgpPeerGroup(
name="IX_DEFAULT",
import_policies="IMPORT_IX",
export_policies="EXPORT_PUBLIC_PREFIX",
local_as="Duff",
remote_as=None,
),
)
INTERFACE_PROFILES = (
InterfaceProfile(name="upstream_profile", mtu=1515, kind="InfraInterfaceL3"),
InterfaceProfile(name="backbone_profile", mtu=9216, kind="InfraInterfaceL3"),
)
VLANS = (
Vlan(id=200, role="server"),
Vlan(id=400, role="management"),
)
store = NodeStore()
async def find_and_connect_interfaces(
batch: InfrahubBatch,
log: logging.Logger,
interface_kind: InfraInterfaceL2 | InfraInterfaceL3,
first_device_name: str,
first_interface_name: str,
second_device_name: str,
second_interface_name: str,
) -> None:
# Connecting first interface to second interface
first_interface = store.get(kind=interface_kind, key=first_interface_name)
second_interface = store.get(kind=interface_kind, key=second_interface_name)
first_interface.description.value = f"Connected to {second_device_name}::{second_interface.name.value}"
first_interface.connected_endpoint = second_interface
batch.add(task=first_interface.save, node=first_interface)
# Adjust description on second interface
second_interface.description.value = f"Connected to {first_device_name}::{first_interface.name.value}"
batch.add(task=second_interface.save, node=second_interface)
log.info(
f" - Connected '{first_device_name}::{first_interface_name}' <> '{second_device_name}::{second_interface_name}'"
)
async def apply_interface_profiles(client: InfrahubClient, log: logging.Logger, branch: str) -> None:
# ------------------------------------------
# Add profile on interfaces upstream/backbone
# ------------------------------------------
log.info("Starting to apply profiles to interfaces")
upstream_interfaces = await client.filters(branch=branch, kind=InfraInterfaceL3, role__value="upstream")
backbone_interfaces = await client.filters(branch=branch, kind=InfraInterfaceL3, role__value="backbone")
upstream_profile = store.get(key="upstream_profile", kind="ProfileInfraInterfaceL3", raise_when_missing=True)
backbone_profile = store.get(key="backbone_profile", kind="ProfileInfraInterfaceL3", raise_when_missing=True)
batch = await client.create_batch()
for interface in upstream_interfaces:
batch.add(
task=interface.add_relationships,
node=interface,
relation_to_update="profiles",
related_nodes=[upstream_profile.id],
)
for interface in backbone_interfaces:
batch.add(
task=interface.add_relationships,
node=interface,
relation_to_update="profiles",
related_nodes=[backbone_profile.id],
)
async for _, response in batch.execute():
log.debug(f"{response} - Creation Completed")
log.info("Done applying profiles to interfaces")
async def create_backbone_connectivity(
client: InfrahubClient, log: logging.Logger, branch: str, num_sites: int
) -> None:
# --------------------------------------------------
# CREATE Backbone Links & Circuits
# --------------------------------------------------
log.info("Creating Backbone Links & Circuits")
account_pop = store.get("pop-builder", kind=CoreAccount, raise_when_missing=True)
interconnection_pool = store.get("interconnection_pool", kind=CoreAccount, raise_when_missing=True)
networks: list[P2pNetwork] = []
if num_sites > 1:
networks.append(P2pNetwork(site1="atl1", site2="ord1", edge=1, circuit="DUFF-1543451"))
networks.append(P2pNetwork(site1="atl1", site2="ord1", edge=2, circuit="DUFF-8263953"))
if num_sites > 2:
networks.append(P2pNetwork(site1="atl1", site2="jfk1", edge=1, circuit="DUFF-6535773"))
networks.append(P2pNetwork(site1="atl1", site2="jfk1", edge=2, circuit="DUFF-7324064"))
networks.append(P2pNetwork(site1="jfk1", site2="ord1", edge=1, circuit="DUFF-5826854"))
networks.append(P2pNetwork(site1="jfk1", site2="ord1", edge=2, circuit="DUFF-4867430"))
for network in networks:
network.pool = await client.allocate_next_ip_prefix(
resource_pool=interconnection_pool, kind=IpamIPPrefix, branch=branch, identifier=network.identifier
)
log.info("- Done allocating addresses")
for backbone_link in networks:
intf1 = INTERFACE_OBJS[backbone_link.site1_device].pop(0)
intf2 = INTERFACE_OBJS[backbone_link.site2_device].pop(0)
backbone_link_ips = backbone_link.get_pool().prefix.value.hosts()
provider = store.get(kind="OrganizationProvider", key=backbone_link.provider_name)
obj = await client.create(
branch=branch,
kind=InfraCircuit,
description=f"Backbone {backbone_link.site1} <-> {backbone_link.site2}",
circuit_id=backbone_link.circuit,
vendor_id=f"{backbone_link.provider_name.upper()}-{UUIDT().short()}",
provider=provider,
status=ACTIVE_STATUS,
role=BACKBONE_ROLE,
)
await obj.save()
log.info(f"- Created {obj._schema.kind} - {backbone_link.provider_name} [{obj.vendor_id.value}]")
# Create Circuit Endpoints
endpoint1 = await client.create(
branch=branch,
kind=InfraCircuitEndpoint,
description=f"Endpoint {backbone_link.circuit} to {backbone_link.site1_device}",
site=backbone_link.site1,
circuit=obj,
connected_endpoint=intf1,
)
await endpoint1.save()
endpoint2 = await client.create(
branch=branch,
kind=InfraCircuitEndpoint,
description=f"Endpoint {backbone_link.circuit} to {backbone_link.site2_device}",
site=backbone_link.site2,
circuit=obj,
connected_endpoint=intf2,
)
await endpoint2.save()
# Create IP Address
intf11_address = f"{str(next(backbone_link_ips))}/31"
intf21_address = f"{str(next(backbone_link_ips))}/31"
intf11_ip = await client.create(
branch=branch,
kind=IpamIPAddress,
interface={"id": intf1.id, "source": account_pop.id},
address={"value": intf11_address, "source": account_pop.id},
)
await intf11_ip.save()
intf21_ip = await client.create(
branch=branch,
kind=IpamIPAddress,
interface={"id": intf2.id, "source": account_pop.id},
address={"value": intf21_address, "source": account_pop.id},
)
await intf21_ip.save()
# Update Interface
intf11 = await client.get(branch=branch, kind=InfraInterfaceL3, id=intf1.id)
intf11.description.value = f"Backbone: Connected to {backbone_link.site2_device} via {backbone_link.circuit}"
await intf11.save()
intf21 = await client.get(branch=branch, kind=InfraInterfaceL3, id=intf2.id)
intf21.description.value = f"Backbone: Connected to {backbone_link.site1_device} via {backbone_link.circuit}"
await intf21.save()
log.info(
f" - Connected '{backbone_link.site1_device}::{intf1.name.value}' <> '{backbone_link.site2_device}::{intf2.name.value}'"
)
async def create_bgp_mesh(client: InfrahubClient, log: logging.Logger, branch: str, sites: list[Site]) -> None:
# --------------------------------------------------
# CREATE Full Mesh iBGP SESSION between all the Edge devices
# --------------------------------------------------
log.info("Creating Full Mesh iBGP SESSION between all the Edge devices")
batch = await client.create_batch()
num_sites = len(sites)
internal_as = store.get(kind=InfraAutonomousSystem, key="Duff", raise_when_missing=True)
for site1 in sites:
for site2 in sites:
if site1 == site2:
continue
for idx1 in range(1, min(3, num_sites)):
for idx2 in range(1, min(3, num_sites)):
device1 = f"{site1.name}-edge{idx1}"
device2 = f"{site2.name}-edge{idx2}"
loopback1 = store.get(key=f"{device1}-loopback", kind=InfraInterfaceL3, raise_when_missing=True)
loopback2 = store.get(key=f"{device2}-loopback", kind=InfraInterfaceL3, raise_when_missing=True)
peer_group_name = "POP_GLOBAL"
obj = await client.create(
branch=branch,
kind="InfraBGPSession",
type="INTERNAL",
local_as=internal_as.id,
local_ip=loopback1.id,
remote_as=internal_as.id,
remote_ip=loopback2.id,
peer_group=store.get(key=peer_group_name, raise_when_missing=True).id,
device=store.get(kind=InfraDevice, key=device1, raise_when_missing=True).id,
status=ACTIVE_STATUS,
role=BACKBONE_ROLE,
)
batch.add(task=obj.save, node=obj)
async for node, _ in batch.execute():
if node._schema.default_filter:
accessor = f"{node._schema.default_filter.split('__')[0]}"
log.info(f"{node._schema.kind} {getattr(node, accessor).value} - Creation Completed")
else:
log.info(f"{node} - Creation Completed")
async def generate_site_vlans(
client: InfrahubClient, log: logging.Logger, branch: str, site: Site, site_id: int
) -> None:
account_pop = store.get("pop-builder", kind=CoreAccount, raise_when_missing=True)
group_eng = store.get("Engineering Team", kind=CoreAccount, raise_when_missing=True)
group_ops = store.get("Operation Team", kind=CoreAccount, raise_when_missing=True)
for vlan in VLANS:
vlan_name = f"{site.name}_{vlan.role}"
obj = await client.create(
branch=branch,
kind=InfraVLAN,
site={"id": site_id, "source": account_pop.id, "is_protected": True},
name={"value": vlan_name, "is_protected": True, "source": account_pop.id},
vlan_id={"value": vlan.id, "is_protected": True, "owner": group_eng.id, "source": account_pop.id},
status={"value": ACTIVE_STATUS, "owner": group_ops.id},
role={"value": vlan.role, "source": account_pop.id, "is_protected": True, "owner": group_eng.id},
)
await obj.save()
store.set(key=vlan_name, node=obj)
async def generate_site_mlag_domain(client: InfrahubClient, log: logging.Logger, branch: str, site: Site) -> None:
# --------------------------------------------------
# Set up MLAG domains
# --------------------------------------------------
for role, domain in MLAG_DOMAINS.items():
devices = [
store.get(kind=InfraDevice, key=f"{site.name}-{role}1"),
store.get(kind=InfraDevice, key=f"{site.name}-{role}2"),
]
name = f"{site.name}-{role}-12"
peer_interfaces = [
store.get(kind=InfraLagInterfaceL2, key=f"{device_obj.name.value}-lagl2-{domain['peer_interfaces'][idx]}") # type: ignore[index]
for idx, device_obj in enumerate(devices)
]
mlag_domain = await client.create(
kind=InfraMlagDomain,
name=name,
domain_id=domain["domain_id"],
devices=devices,
peer_interfaces=peer_interfaces,
)
await mlag_domain.save()
store.set(key=f"mlag-domain-{name}", node=mlag_domain)
# --------------------------------------------------
# Set up MLAG Interfaces
# --------------------------------------------------
for role, mlags in MLAG_INTERFACE_L2.items():
devices = [
store.get(kind=InfraDevice, key=f"{site.name}-{role}1"),
store.get(kind=InfraDevice, key=f"{site.name}-{role}2"),
]
for mlag in mlags:
members = [
store.get(kind=InfraLagInterfaceL2, key=f"{device_obj.name.value}-lagl2-{mlag['members'][idx]}") # type: ignore[index]
for idx, device_obj in enumerate(devices)
]
mlag_domain = store.get(kind=InfraMlagDomain, key=f"mlag-domain-{site.name}-{role}-12")
mlag_interface = await client.create(
kind=InfraMlagInterfaceL2, mlag_domain=mlag_domain, mlag_id=mlag["mlag_id"], members=members
)
await mlag_interface.save()
async def generate_site(
client: InfrahubClient,
log: logging.Logger,
branch: str,
site: Site,
interconnection_pool: CoreNode,
loopback_pool: CoreNode,
management_pool: CoreNode,
external_pool: CoreNode,
site_design: SiteDesign,
) -> str:
group_eng = store.get("Engineering Team", kind=CoreAccount)
group_ops = store.get("Operation Team", kind=CoreAccount)
account_pop = store.get("pop-builder", kind=CoreAccount)
account_crm = store.get("CRM Synchronization", kind=CoreAccount)
internal_as = store.get(kind=InfraAutonomousSystem, key="Duff")
country = store.get(kind=LocationCountry, key=site.country)
# --------------------------------------------------
# Create the Site
# --------------------------------------------------
site_obj = await client.create(
branch=branch,