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 | @Task(fastapi={"methods": ["GET"], "schema": NetboxFastApiArgs.model_json_schema()})
def get_connections(
self,
job: Job,
devices: list[str],
instance: Union[None, str] = None,
dry_run: bool = False,
cables: bool = False,
cache: Union[bool, str] = None,
include_virtual: bool = True,
interface_regex: Union[None, str] = None,
) -> Result:
"""
Retrieve interface connection details for specified devices from Netbox.
This task retrieves these connections:
- Physical interfaces connections
- Child/virtual interfaces connections using parent interface connections details
- Lag interfaces connections using member ports connections details
- Lag child interfaces connections using member ports connections details
- Console port and console server ports connections
- Connections to provider networks for physical, child/virtual and lag interfaces
Args:
job: NorFab Job object containing relevant metadata
devices (list): List of device names to retrieve connections for.
instance (str, optional): Netbox instance name for the GraphQL query.
dry_run (bool, optional): If True, perform a dry run without making actual changes.
cables (bool, optional): if True includes interfaces' directly attached cables details
include_virtual (bool, optional): if True include connections for virtual and LAG interfaces
interface_regex (str, optional): Regex patter to match interfaces, console ports and
console server ports by name, case insensitive.
Returns:
dict: A dictionary containing connection details for each device:
```
{
"netbox-worker-1.2": {
"r1": {
"Console": {
"breakout": false,
"remote_device": "termserv1",
"remote_interface": "ConsoleServerPort1",
"remote_termination_type": "consoleserverport",
"termination_type": "consoleport"
},
"eth1": {
"breakout": false,
"remote_device": "r2",
"remote_interface": "eth8",
"remote_termination_type": "interface",
"termination_type": "interface"
}
}
}
}
```
Raises:
Exception: If there is an error in the GraphQL query or data retrieval process.
"""
instance = instance or self.default_instance
ret = Result(
task=f"{self.name}:get_connections",
result={d: {} for d in devices},
resources=[instance],
)
# form lists of fields to request from netbox
cable_fields = """
cable {
type
status
tenant {name}
label
tags {name}
length
length_unit
custom_fields
}
"""
interfaces_fields = [
"name",
"type",
"device {name}",
"""
member_interfaces {
name
connected_endpoints {
__typename
... on ProviderNetworkType {name}
... on InterfaceType {name, device {name}, child_interfaces {name}, lag {name child_interfaces {name}}}
}
}
""",
"""
parent {
name
type
member_interfaces {
name
connected_endpoints {
__typename
... on ProviderNetworkType {name}
... on InterfaceType {name, device {name}, child_interfaces {name}, lag {name child_interfaces {name}}}
}
}
connected_endpoints {
__typename
... on ProviderNetworkType {name}
... on InterfaceType {name, device {name}, child_interfaces {name}, lag {name child_interfaces {name}}}
}
}
""",
"""
connected_endpoints {
__typename
... on ProviderNetworkType {name}
... on InterfaceType {name, device {name}, child_interfaces {name}, lag {name child_interfaces {name}}}
}
""",
]
interfaces_fields.append(
"""
link_peers {
__typename
... on InterfaceType {name device {name}}
... on FrontPortType {name device {name}}
... on RearPortType {name device {name}}
}
"""
)
console_ports_fields = [
"name",
"device {name}",
"type",
"""connected_endpoints {
__typename
... on ConsoleServerPortType {name device {name}}
}""",
"""link_peers {
__typename
... on ConsoleServerPortType {name device {name}}
... on FrontPortType {name device {name}}
... on RearPortType {name device {name}}
}""",
]
console_server_ports_fields = [
"name",
"device {name}",
"type",
"""connected_endpoints {
__typename
... on ConsolePortType {name device {name}}
}""",
"""link_peers {
__typename
... on ConsolePortType {name device {name}}
... on FrontPortType {name device {name}}
... on RearPortType {name device {name}}
}""",
]
# check if need to include cables info
if cables is True:
interfaces_fields.append(cable_fields)
console_ports_fields.append(cable_fields)
console_server_ports_fields.append(cable_fields)
# form query dictionary with aliases to get data from Netbox
dlist = str(devices).replace("'", '"') # swap quotes
if self.nb_version[instance] >= (4, 3, 0):
if interface_regex:
filters = (
"{device: {name: {in_list: "
+ dlist
+ "}}, "
+ "name: {i_regex: "
+ f'"{interface_regex}"'
+ "}}"
)
else:
filters = "{device: {name: {in_list: " + dlist + "}}}"
elif (4, 2, 0) <= self.nb_version[instance] < (4, 3, 0):
if interface_regex:
filters = (
"{device: "
+ dlist
+ ", name: {i_regex: "
+ f'"{interface_regex}"'
+ "}}"
)
else:
filters = {"device": devices}
queries = {
"interface": {
"obj": "interface_list",
"filters": filters,
"fields": interfaces_fields,
},
"consoleport": {
"obj": "console_port_list",
"filters": filters,
"fields": console_ports_fields,
},
"consoleserverport": {
"obj": "console_server_port_list",
"filters": filters,
"fields": console_server_ports_fields,
},
}
# retrieve full list of devices interface with all cables
query_result = self.graphql(
job=job, queries=queries, instance=instance, dry_run=dry_run
)
# return dry run result
if dry_run:
return query_result
all_ports = query_result.result
if not all_ports:
return ret
# extract physical interfaces connections
for port_type, ports in all_ports.items():
for port in ports:
# skip ports that have no remote device connected
endpoints = port["connected_endpoints"]
if not endpoints or not all(i for i in endpoints):
continue
# extract required parameters
cable = port.get("cable", {})
device_name = port["device"]["name"]
port_name = port["name"]
link_peers = port["link_peers"]
remote_termination_type = endpoints[0]["__typename"].lower()
remote_termination_type = remote_termination_type.replace("type", "")
# form initial connection dictionary
connection = {
"breakout": len(endpoints) > 1,
"remote_termination_type": remote_termination_type,
"termination_type": port_type,
}
# add remote connection details
if remote_termination_type == "providernetwork":
connection["remote_device"] = None
connection["remote_interface"] = None
connection["provider"] = endpoints[0]["name"]
else:
remote_interface = endpoints[0]["name"]
if len(endpoints) > 1:
remote_interface = list(sorted([i["name"] for i in endpoints]))
connection["remote_interface"] = remote_interface
connection["remote_device"] = endpoints[0]["device"]["name"]
# add cable and its peer details
if cables:
peer_termination_type = link_peers[0]["__typename"].lower()
peer_termination_type = peer_termination_type.replace("type", "")
cable["peer_termination_type"] = peer_termination_type
cable["peer_device"] = link_peers[0].get("device", {}).get("name")
cable["peer_interface"] = link_peers[0].get("name")
if len(link_peers) > 1: # handle breakout cable
cable["peer_interface"] = [i["name"] for i in link_peers]
connection["cable"] = cable
# add physical connection to the results
ret.result[device_name][port_name] = connection
# extract virtual interfaces connections
for port_type, ports in all_ports.items():
for port in ports:
# add child virtual interfaces connections
if (
not include_virtual
or port["type"] != "virtual"
or not port["parent"]
):
continue
device_name = port["device"]["name"]
interface_name = port["name"]
parent = port["parent"]
connection = {
"remote_device": None,
"remote_interface": None,
"remote_termination_type": "virtual",
"termination_type": "virtual",
}
# find connection endpoint
if parent["type"] == "lag":
try:
endpoint = parent["member_interfaces"][0][
"connected_endpoints"
][0]
except:
continue
elif parent["connected_endpoints"]:
try:
endpoint = parent["connected_endpoints"][0]
except:
continue
connection["remote_device"] = endpoint["device"]["name"]
remote_termination_type = endpoint["__typename"].lower()
remote_termination_type = remote_termination_type.replace("type", "")
# collect virtual interfaces facing provider
if remote_termination_type == "providernetwork":
connection["provider"] = endpoint["name"]
# find matching remote virtual interface for LAG subif
elif "." in interface_name and parent["type"] == "lag":
subif_id = interface_name.split(".")[1]
for remote_child in endpoint["lag"]["child_interfaces"]:
if remote_child["name"].endswith(f".{subif_id}"):
connection["remote_interface"] = remote_child["name"]
break
# no matching subinterface found, associate child interface with remote interface
else:
connection["remote_interface"] = endpoint["lag"]["name"]
connection["remote_termination_type"] = "lag"
# find matching remote virtual interface for physical interface subif
elif "." in interface_name:
subif_id = interface_name.split(".")[1]
for remote_child in endpoint["child_interfaces"]:
if remote_child["name"].endswith(f".{subif_id}"):
connection["remote_interface"] = remote_child["name"]
break
# no matching subinterface found, associate child interface with remote interface
else:
connection["remote_interface"] = endpoint["name"]
connection["remote_termination_type"] = remote_termination_type
# add virtual interface connection to results
ret.result[device_name][interface_name] = connection
# extract LAG interfaces connections
for port_type, ports in all_ports.items():
for port in ports:
if not include_virtual or port["type"] != "lag":
continue
device_name = port["device"]["name"]
interface_name = port["name"]
connection = {
"remote_device": None,
"remote_interface": None,
"remote_termination_type": "lag",
"termination_type": "lag",
}
try:
endpoint = port["member_interfaces"][0]["connected_endpoints"][0]
except:
continue
remote_termination_type = endpoint["__typename"].lower()
remote_termination_type = remote_termination_type.replace("type", "")
# collect lag interfaces facing provider
if remote_termination_type == "providernetwork":
connection["provider"] = endpoint["name"]
# find remote lag interface
elif endpoint["lag"]:
connection["remote_interface"] = endpoint["lag"]["name"]
connection["remote_device"] = endpoint["device"]["name"]
# add lag interface connection to results
ret.result[device_name][interface_name] = connection
return ret
|