dnmapper/backend/gobgp.py

66 lines
2.6 KiB
Python
Raw Normal View History

2020-05-31 22:10:26 +02:00
import grpc
from backend.gobgp_api import gobgp_pb2_grpc, attribute_pb2
from backend.gobgp_api.gobgp_pb2 import TableType, Family, ListPeerRequest, ListPathRequest
def get_bgp_data(gobgp_host):
_timeout = 10
channel = grpc.insecure_channel('{}:50051'.format(gobgp_host))
stub = gobgp_pb2_grpc.GobgpApiStub(channel)
data = []
peers = stub.ListPeer(ListPeerRequest(), _timeout)
for peer in peers:
entry = {
"local_id": peer.peer.state.router_id,
"local_as": peer.peer.conf.peer_as,
"peers": [], # we don't export any peers
"routes": [],
}
neigh = peer.peer.conf.neighbor_address
for af in [Family.Afi.AFI_IP, Family.Afi.AFI_IP6]:
req = ListPathRequest(
name=neigh,
table_type=TableType.ADJ_IN,
family=Family(afi=af, safi=Family.Safi.SAFI_UNICAST),
sort_type=ListPathRequest.SortType.PREFIX)
rib = stub.ListPath(req)
for dest in rib:
prefix = dest.destination.prefix
for path in dest.destination.paths:
as_path = []
next_hop = "<unknown>" # currently here to prevent error from NOT NULL constraint
# parse attrs
for pattr in path.pattrs:
if pattr.type_url == "type.googleapis.com/gobgpapi.NextHopAttribute":
nh = attribute_pb2.NextHopAttribute()
nh.ParseFromString(pattr.value)
next_hop = nh.next_hop
elif pattr.type_url == "type.googleapis.com/gobgpapi.AsPathAttribute":
asp = attribute_pb2.AsPathAttribute()
asp.ParseFromString(pattr.value)
for seg in asp.segments:
if seg.type == 2:
as_path = seg.numbers
elif pattr.type_url == "type.googleapis.com/gobgpapi.MpReachNLRIAttribute":
mpreach = attribute_pb2.MpReachNLRIAttribute()
mpreach.ParseFromString(pattr.value)
next_hop = mpreach.next_hops[0]
if not as_path:
continue
route = {
"prefix": prefix,
"path": as_path,
"nexthop": next_hop,
}
entry["routes"].append(route)
2020-05-31 22:10:26 +02:00
data.append(entry)
return data