Beispiel #1
0
def run(af, gobgpd_addr, *prefixes, **kw):
    table_args = dict()
    table_args["family"] = libgobgp.get_route_family(_AF_NAME[af])
    table_args["destinations"] = [
        gobgp_pb2.Destination(prefix=p) for p in prefixes
    ]
    if kw["rib_in_neighbor"] is not None:
        table_args["type"] = gobgp_pb2.ADJ_IN
        table_args["name"] = kw["rib_in_neighbor"]
    elif kw["rib_out_neighbor"] is not None:
        table_args["type"] = gobgp_pb2.ADJ_OUT
        table_args["name"] = kw["rib_out_neighbor"]
    else:
        table_args["type"] = gobgp_pb2.GLOBAL
    # grpc request
    channel = grpc.insecure_channel(gobgpd_addr + ':50051')
    try:
        stub = gobgp_pb2_grpc.GobgpApiStub(channel)
        response_table = stub.GetRib(
            gobgp_pb2.GetRibRequest(table=gobgp_pb2.Table(**table_args)),
            _TIMEOUT_SECONDS).table
    except ExpirationError:
        print >> sys.stderr, "grpc request timed out!"
    except RemoteError, e:
        print >> sys.stderr, "grpc stub method failed:", e.details
Beispiel #2
0
def run():
    channel = grpc.insecure_channel('192.168.10.1:50051')
    stub = gobgp_pb2_grpc.GobgpApiStub(channel)

    nlri = Any()
    nlri.Pack(
        attribute_pb2.IPAddressPrefix(
            prefix_len=24,
            prefix="192.168.10.0",
        ))
    origin = Any()
    origin.Pack(attribute_pb2.OriginAttribute(
        origin=2,  # INCOMPLETE
    ))
    next_hop = Any()
    next_hop.Pack(attribute_pb2.NextHopAttribute(next_hop="0.0.0.0", ))
    attributes = [origin, next_hop]

    stub.AddPath(
        gobgp_pb2.AddPathRequest(table_type=gobgp_pb2.GLOBAL,
                                 path=gobgp_pb2.Path(
                                     nlri=nlri,
                                     pattrs=attributes,
                                     family=gobgp_pb2.Family(
                                         afi=gobgp_pb2.Family.AFI_IP,
                                         safi=gobgp_pb2.Family.SAFI_UNICAST),
                                 )),
        _TIMEOUT_SECONDS,
    )
Beispiel #3
0
def run():
    channel = grpc.insecure_channel('localhost:50051')
    stub = gobgp_pb2_grpc.GobgpApiStub(channel)

    peers = stub.ListPeer(
        gobgp_pb2.ListPeerRequest(),
        _TIMEOUT_SECONDS,
    )

    for peer in peers:
        print(peer)
Beispiel #4
0
def run(gobgpd_addr):
    channel = grpc.insecure_channel(gobgpd_addr + ':50051')
    stub = gobgp_pb2_grpc.GobgpApiStub(channel)
    try:
        peers = stub.GetNeighbor(gobgp_pb2.GetNeighborRequest()).peers
        for peer in peers:
            print("BGP neighbor is %s, remote AS %d" % (peer.conf.neighbor_address, peer.conf.peer_as))
            print("  BGP version 4, remote router ID %s" % (peer.conf.id))
            print("  BGP state = %s, up for %s" % (peer.info.bgp_state, peer.timers.state.uptime))
            print("  BGP OutQ = %d, Flops = %d" % (peer.info.out_q, peer.info.flops))
            print("  Hold time is %d, keepalive interval is %d seconds" % (peer.timers.state.negotiated_hold_time, peer.timers.state.keepalive_interval))
            print("  Configured hold time is %d, keepalive interval is %d seconds" % (peer.timers.config.hold_time, peer.timers.config.keepalive_interval))
    except ExpirationError, e:
        print str(e)
        sys.exit(-1)
Beispiel #5
0
def run(prefix, af, gobgpd_addr, withdraw=False, **kw):
    route_family = libgobgp.get_route_family(_AF_NAME[af])
    joined_args = prefix + " " + " ".join(
        map(lambda x: "{} {}".format(*x), kw.items()))
    serialized_path = libgobgp.serialize_path(
        route_family,
        joined_args,
    ).contents
    # nlri
    nlri = unpack_buf(serialized_path.nlri)
    # pattrs
    pattrs = []
    for pattr_p in serialized_path.path_attributes.contents[:serialized_path.
                                                            path_attributes_len]:
        pattrs.append(unpack_buf(pattr_p.contents))
    # path dict
    path = dict([
        ("family", route_family),
        ("nlri", nlri),
        ("pattrs", pattrs),
    ])
    # grpc request
    channel = grpc.insecure_channel(gobgpd_addr + ':50051')
    try:
        stub = gobgp_pb2_grpc.GobgpApiStub(channel)
        if not withdraw:
            res = stub.AddPath(gobgp_pb2.AddPathRequest(path=path),
                               _TIMEOUT_SECONDS)
            # AddPathResponse uuid seems to have become empty since uuid became a member of Path structure.
            if res.uuid:
                print str(UUID(bytes=res.uuid))
        else:
            path["is_withdraw"] = True
            res = stub.DeletePath(gobgp_pb2.DeletePathRequest(path=path),
                                  _TIMEOUT_SECONDS)
    except ExpirationError:
        print >> sys.stderr, "grpc request timed out!"
    except:
        traceback.print_exc()
Beispiel #6
0
def run():
    channel = grpc.insecure_channel('localhost:50051')
    stub = gobgp_pb2_grpc.GobgpApiStub(channel)

    nlri = Any()
    nlri.Pack(attribute_pb2.IPAddressPrefix(
        prefix_len=24,
        prefix="10.0.0.0",
    ))
    origin = Any()
    origin.Pack(attribute_pb2.OriginAttribute(
        origin=2,  # INCOMPLETE
    ))
    as_segment = attribute_pb2.AsSegment(
        # type=2,  # "type" causes syntax error
        numbers=[100, 200],
    )
    as_segment.type = 2  # SEQ
    as_path = Any()
    as_path.Pack(attribute_pb2.AsPathAttribute(
        segments=[as_segment],
    ))
    next_hop = Any()
    next_hop.Pack(attribute_pb2.NextHopAttribute(
        next_hop="1.1.1.1",
    ))
    attributes = [origin, as_path, next_hop]

    stub.AddPath(
        gobgp_pb2.AddPathRequest(
            table_type=gobgp_pb2.GLOBAL,
            path=gobgp_pb2.Path(
                nlri=nlri,
                pattrs=attributes,
                family=gobgp_pb2.Family(afi=gobgp_pb2.Family.AFI_IP, safi=gobgp_pb2.Family.SAFI_UNICAST),
            )
        ),
        _TIMEOUT_SECONDS,
    )
Beispiel #7
0
import grpc
from google.protobuf.any_pb2 import Any
import gobgp_pb2
import gobgp_pb2_grpc
import attribute_pb2

channel = grpc.insecure_channel('localhost:50051')

stub = gobgp_pb2_grpc.GobgpApiStub(channel)
# stub.GetTable(gobgp_pb2.GetTableRequest())
# k = stub.ListPath(gobgp_pb2.ListPathRequest('ipv4'))

k = stub.ListPath(
    gobgp_pb2.ListPathRequest(family=gobgp_pb2.Family(
        afi=gobgp_pb2.Family.AFI_IP, safi=gobgp_pb2.Family.SAFI_UNICAST)))

z = k.next()

print(z.destination.ListFields())

l = z.destination.paths[0]

print(l.ListFields())
print(l.ListFields()[1][1][1].value)
Beispiel #8
0
def run(gobgpd_addr, timeout):
    # family
    family = _AF_NAME['LS']
    table_type = _TT["global"]
    name = None
    channel = grpc.insecure_channel(gobgpd_addr + ":50051")
    stub = gobgp_pb2_grpc.GobgpApiStub(channel)
    res = stub.ListPath(
        gobgp_pb2.ListPathRequest(
            table_type=table_type,
            name=name,
            family=family,
        ),
        timeout,
    )
    destinations = [d for d in res]
    for p in [p for d in destinations for p in d.destination.paths]:
        print_path(p)

    #print('this is the final lnetd_links')
    '''
  Links format 
  [{'source': '0002.0020.0200', 'target': '0003.0030.0300', 'l_ip': '10.22.33.22', 'r_ip': '10.22.33.33', 'metric': 10}]
  '''
    #print(lnetd_links)
    print('\nthis is the final routers\n')
    '''
  Router Format
  [{'igp_router_id': '0007.0070.0700', 'local_router_id': '10.7.7.7', 'name': 'fr-p7-mrs'}]
  '''
    #print(lnetd_routers)
    #generate nsap_ip name mapping

    map_nsap = {}
    for entry in lnetd_routers:
        map_nsap[entry['igp_router_id']] = entry['name']

    df_links = pd.DataFrame(lnetd_links)
    df_links['source'] = df_links.apply(lambda row: map_nsap[row['source']],
                                        axis=1)
    df_links['target'] = df_links.apply(lambda row: map_nsap[row['target']],
                                        axis=1)
    df_links.loc[:, 'l_ip_r_ip'] = pd.Series([
        tuple(sorted(each)) for each in list(
            zip(df_links.l_ip.values.tolist(), df_links.r_ip.values.tolist()))
    ])
    df_links['l_ip_r_ip'] = df_links['l_ip_r_ip'].astype(str)
    print('\nThis is the final lnetd_links ... writing to db now \n', df_links)
    try:
        disk_engine = create_engine('sqlite:////opt/lnetd/web_app/database.db')
        df_links.to_sql('rpc_links', disk_engine, if_exists='replace')
    except Exception as e:
        print(e)

    #generate final routers
    df_routers = pd.DataFrame(lnetd_routers)
    df_routers = df_routers.drop(['igp_router_id'], axis=1)
    df_routers = df_routers.rename(columns={'local_router_id': 'ip'})
    df_routers.loc[:, 'country'] = df_routers['name'].str[0:2]
    df_routers = df_routers.fillna(0)
    print('\nThis is the final lnetd_routers ... writing to db now \n',
          df_routers)
    try:
        disk_engine = create_engine('sqlite:////opt/lnetd/web_app/database.db')
        df_routers.to_sql('rpc_routers', disk_engine, if_exists='replace')
    except Exception as e:
        print(e)
Beispiel #9
0
def go_bgp_subnet(color, endpoint_device, target_device, sid_list, bsid_value, nh):
    """
    inject or delete an route with <ACME>-CIDR and <ACME>-SCRUBBING community
    NLRI
    ORIGIN
    AS_PATH
    LP
    EXTENDED COMMUNITIES
     RT
    TUNNEL ENCAP
     TLVs
      SR Policy
       SUB-TLVs
        Preference
        Binding-SID
        SEG-LIST
         WEIGHT
         SEGMENT(1..n)
    """
    channel = grpc.insecure_channel("localhost:50051")
    stub = gobgp_pb2_grpc.GobgpApiStub(channel)
    attributes = []
    segments = []
    # bgp-sr-te safi
    family = gobgp_pb2.Family(
        afi=gobgp_pb2.Family.AFI_IP, safi=gobgp_pb2.Family.SAFI_SR_POLICY
    )

    # sr-te policy nlri
    nlri = Any()
    nlri.Pack(
        attribute_pb2.SRPolicyNLRI(
            color=color,
            distinguisher=2,
            endpoint=bytes(map(int, endpoint_device.split("."))),
            length=96,
        )
    )

    # next-hop
    next_hop = Any()
    next_hop.Pack(
        attribute_pb2.NextHopAttribute(
            next_hop=nh,
        )
    )
    attributes.append(next_hop)

    # Origin
    origin = Any()
    origin.Pack(attribute_pb2.OriginAttribute(origin=0))
    attributes.append(origin)
    # Ext RT Communities
    rt = Any()
    rt.Pack(
        attribute_pb2.IPv4AddressSpecificExtended(
            address=target_device, local_admin=0, sub_type=0x02, is_transitive=False
        )
    )
    communities = Any()
    communities.Pack(
        attribute_pb2.ExtendedCommunitiesAttribute(
            communities=[rt],
        )
    )
    attributes.append(communities)
    # generic sid used for bsid
    sid = Any()
    sid.Pack(
        attribute_pb2.SRBindingSID(
            s_flag=False, i_flag=False, sid=(bsid_value).to_bytes(4, byteorder="big")
        )
    )
    # bsid
    bsid = Any()
    bsid.Pack(attribute_pb2.TunnelEncapSubTLVSRBindingSID(bsid=sid))

    # generic segment lbl
    for n in sid_list:
        segment = Any()
        segment.Pack(
            attribute_pb2.SegmentTypeA(
                flags=attribute_pb2.SegmentFlags(s_flag=False), label=n << 12
            )
        )
        segments.append(segment)
    # segment list
    seglist = Any()
    seglist.Pack(
        attribute_pb2.TunnelEncapSubTLVSRSegmentList(
            weight=attribute_pb2.SRWeight(flags=0, weight=12),
            segments=segments,
        )
    )
    # pref
    pref = Any()
    pref.Pack(attribute_pb2.TunnelEncapSubTLVSRPreference(flags=0, preference=11))
    # path name not used for now
    cpn = Any()
    cpn.Pack(
        attribute_pb2.TunnelEncapSubTLVSRCandidatePathName(
            candidate_path_name="test-path"
        )
    )
    # priority not used for now
    pri = Any()
    pri.Pack(attribute_pb2.TunnelEncapSubTLVSRPriority(priority=10))
    tun = Any()

    # generate tunnel
    tun.Pack(
        attribute_pb2.TunnelEncapAttribute(
            tlvs=[
                attribute_pb2.TunnelEncapTLV(
                    type=15,
                    tlvs=[
                        pref,
                        bsid,
                        seglist,
                        # cpn,
                        # pri,
                    ],
                )
            ]
        )
    )

    attributes.append(tun)

    stub.AddPath(
        gobgp_pb2.AddPathRequest(
            table_type=gobgp_pb2.GLOBAL,
            path=gobgp_pb2.Path(
                nlri=nlri,
                pattrs=attributes,
                family=family,
                best=True,
            ),
        ),
        _TIMEOUT_SECONDS,
    )