コード例 #1
0
def prefix_gen(dest_table, prefix, api_user, prefix_type=None):
    """
    Generate prefix based on table
    """
    if dest_table == 'inet.0':
        if prefix_type == 'bgp_lu':
            destpfx = prpd.RoutePrefix(labeled_inet=prpd.IpAddress(
                addr_string=prefix["dest_prefix"]))
        else:
            destpfx = prpd.RoutePrefix(inet=prpd.IpAddress(
                addr_string=prefix["dest_prefix"]))
    elif dest_table == 'inet6.0':
        if prefix_type == 'bgp_lu':
            destpfx = prpd.RoutePrefix(labeled_inet6=prpd.IpAddress(
                addr_string=prefix["dest_prefix"]))
        else:
            destpfx = prpd.RoutePrefix(inet6=prpd.IpAddress(
                addr_string=prefix["dest_prefix"]))
    elif dest_table == "bgp.l3vpn.0" or dest_table == "bgp.l3vpn-inet6.0":
        destpfx = bgpvpnprefix(dest_table, prefix, api_user)
    elif dest_table == "bgp.inetsrte.0" or dest_table == "bgp.inet6srte.0":
        destpfx = bgpsrteprefix(dest_table, prefix, api_user)
    elif dest_table == "inetflow.0" or dest_table == "inet6flow.0":
        destpfx = bgpflowprefix(dest_table, prefix, api_user)
    else:
        destpfx = None
    return destpfx
コード例 #2
0
def rib_route_remove(dev, channel_id, **kwargs):
    """
    delete already added static routes using execute_prpd_api.
    ** ONLY THE ROUTES ADDED BY A UNIQUE client_id CAN BE REMOVED
    """
    dest_prefix_iterator = prpd.dest_prefix_limiter(**kwargs)

    if 'table' in kwargs:
        table = kwargs.get('table')

    if 'prefix_len' in kwargs:
        prefix_len = kwargs.get('prefix_len')

    result = []
    for i in dest_prefix_iterator:
        dest_prefix = i

        rtkeys = []

        for index in range(0, len(dest_prefix)):
            #Building the Key for RIB Route Params

            if 'inet6' in table:
                destprefix = prpd.NetworkAddress(inet6=prpd.IpAddress(
                    addr_string=dest_prefix[index]))
            else:
                if 'mpls' in table:
                    destprefix = prpd.NetworkAddress(mpls=prpd.MplsAddress(
                        label=int(dest_prefix[index])))
                else:
                    destprefix = prpd.NetworkAddress(inet=prpd.IpAddress(
                        addr_string=dest_prefix[index]))

            tablename = prpd.RouteTable(name=prpd.RouteTableName(name=table))

            route_match_field = prpd.RouteMatch(dest_prefix=destprefix,
                                                dest_prefix_len=prefix_len,
                                                table=tablename)

            if 'cookie' in kwargs:
                if isinstance(kwargs["cookie"], int):
                    route_match_field.cookie = kwargs.get('cookie')

            rtkeys.append(route_match_field)

        remreq = prpd.RouteDeleteRequest(keys=rtkeys)
        result.append(
            prpd.process_api(dev, channel_id, "RouteDelete",
                             [remreq, "jnx_Rib"], kwargs.get("timeout", None)))

    return result
コード例 #3
0
ファイル: bgp_2.py プロジェクト: SrijaGupta/file
def bgpsrteprefix(dest_table, prefix, api_user):
    """
    Generate bgp srte prefix
    """
    if 'dest_prefix' in prefix:
        pfx = prefix.get('dest_prefix')
    elif api_user != 'test':
        raise Exception(
            "Mandatory parameter 'prefix' absent for bgp srte route")
    else:
        pfx = None
    if 'sr_color' in prefix:
        srcolor = prefix.get('sr_color')
        srcolor = int(srcolor)
    elif api_user != 'test':
        raise Exception(
            "Mandatory parameter 'sr_color' absent for bgp srte route")
    else:
        srcolor = None

    if 'sr_distinguisher' in prefix:
        srdistinguisher = prefix.get('sr_distinguisher')
        srdistinguisher = int(srdistinguisher)
    elif api_user != 'test':
        raise Exception(
            "Mandatory parameter 'sr_distinguisher' absent for bgp srte route")
    else:
        srdistinguisher = None

    srteaddr = prpd.SRTEAddress()
    if pfx is not None and api_user != 'test':
        sraddr = prpd.IpAddress(addr_string=(pfx))
        srteaddr.destination.CopyFrom(sraddr)
    if srcolor is None and api_user == 'test':
        srteaddr.sr_color = prpd.SRTEColor()
    else:
        srteaddr.sr_color.CopyFrom(prpd.SRTEColor(color=srcolor))
    if srdistinguisher is None and api_user == 'test':
        srteaddr.sr_distinguisher = prpd.SRTEDistinguisher()
    else:
        srteaddr.sr_distinguisher.CopyFrom(
            prpd.SRTEDistinguisher(distinguisher=srdistinguisher))
    if dest_table == "bgp.inetsrte.0":
        srteprefix = prpd.RoutePrefix(inet_srte_policy=srteaddr)
    elif dest_table == "bgp.inet6srte.0":
        srteprefix = prpd.RoutePrefix(inet6_srte_policy=srteaddr)
    return srteprefix
コード例 #4
0
ファイル: bgp_2.py プロジェクト: SrijaGupta/file
def bgpvpnprefix(dest_table, prefix, api_user):
    """
    Generate bgp vpn prefix
    """
    if 'dest_prefix' in prefix:
        dprefix = prefix.get('dest_prefix')
    elif api_user != 'test':
        raise Exception("Mandatory parameter 'dest_prefix' absent")
    else:
        dprefix = None

    if 'rd_type' in prefix:
        rdtype = prefix.get('rd_type')
        rdtype = int(rdtype)
    elif api_user != 'test':
        raise Exception(
            "Mandatory parameter 'rd_type' absent for bgp vpn route ")
    else:
        rdtype = None

    if 'as_number' in prefix:
        asnum = prefix.get('as_number')
        asnum = int(asnum)
    elif api_user != 'test':
        raise Exception(
            "Mandatory parameter 'as_number' absent for bgp vpn route")
    else:
        asnum = None

    if 'assigned_number' in prefix:
        asgnd_number = prefix.get('assigned_number')
        asgnd_number = int(asgnd_number)
    elif api_user != 'test':
        raise Exception(
            "Mandatory parameter 'assigned_number' absent for bgp vpn route")
    else:
        asgnd_number = None

    if 'ipaddress' in prefix and rdtype == 1:
        ipaddress = prefix.get('ipaddress')
    elif api_user != 'test' and rdtype == 1:
        raise Exception(
            "Mandatory parameter 'ipaddress' absent for bgp vpn route")
    else:
        ipaddress = None

    if rdtype is None and api_user == 'test':
        bgprd = prpd.RouteDistinguisher()
    else:
        if rdtype == 0:
            if asnum is None or asgnd_number is None and api_user == 'test':
                bgprd = prpd.RouteDistinguisher(rd0=prpd.RdType0())
            else:
                bgprd = prpd.RouteDistinguisher(rd0=prpd.RdType0(
                    as_number=asnum, assigned_number=asgnd_number))
        if rdtype == 1:
            if ipaddress is None or asgnd_number is None and api_user == 'test':
                bgprd = prpd.RouteDistinguisher(rd1=prpd.RdType1())
            else:
                bgprd = prpd.RouteDistinguisher(
                    rd1=prpd.RdType1(ip_address=prpd.IpAddress(
                        addr_string=ipaddress),
                                     assigned_number=asgnd_number))
        if rdtype == 2:
            if asnum is None or asgnd_number is None and api_user == 'test':
                bgprd = prpd.RouteDistinguisher(rd2=prpd.RdType2())
            else:
                bgprd = prpd.RouteDistinguisher(rd2=prpd.RdType2(
                    as_number=asnum, assigned_number=asgnd_number))
        vpn_address = prpd.L3vpnAddress(
            rd=bgprd, vpn_addr=prpd.IpAddress(addr_string=dprefix))
        if dest_table == "bgp.l3vpn.0":
            vpnpfx = prpd.RoutePrefix(inetvpn=vpn_address)
        if dest_table == "bgp.l3vpn-inet6.0":
            vpnpfx = prpd.RoutePrefix(inet6vpn=vpn_address)
    return vpnpfx
コード例 #5
0
ファイル: bgp_2.py プロジェクト: SrijaGupta/file
def bgp_generate_update_req(**kwargs):  # pylint: disable=too-many-locals,too-many-branches,too-many-statements
    """
    Generate the update request for bgp route add/modify/update
    """

    if 'api_user' in kwargs:
        api_user = kwargs.get('api_user', 'default')
    else:
        api_user = None

    if 'next_hop' in kwargs:
        next_hop = kwargs.get('next_hop')
        if isinstance(next_hop, str):
            next_hop_list = [next_hop]
        elif isinstance(next_hop, list):
            next_hop_list = next_hop
    elif api_user != 'test':
        raise Exception("Next hop is mandatory parameter.")
    else:
        next_hop_list = None

    if 'multi_nh' in kwargs:
        multi_nh = kwargs.get('multi_nh')
    else:
        multi_nh = None

    if 'table' in kwargs:
        table = kwargs.get('table')
    elif api_user != 'test':
        raise Exception("Mandatory parameter 'table' absent")
    else:
        table = None

    if 'dest_prefix' in kwargs:
        dest_prefix = kwargs.get('dest_prefix')
        if isinstance(dest_prefix, str):
            dest_prefix = [dest_prefix]
        elif isinstance(dest_prefix, list):
            dest_prefix = dest_prefix
        elif isinstance(dest_prefix, dict):
            dest_prefix = [dest_prefix]
    elif api_user != 'test':
        raise Exception("Mandatory parameter 'dest_prefix' absent")
    else:
        dest_prefix = None

    if 'prefix_len' in kwargs:
        if isinstance(kwargs["prefix_len"], int):
            prefix_len = kwargs.get('prefix_len')
            if table == 'inet6.0':
                if prefix_len > 128 and api_user != 'test':
                    raise Exception("Prefix length should be <= 128 for inet6")
            elif table == 'inet.0':
                if prefix_len > 32 and api_user != 'test':
                    raise Exception("Prefix length should be <= 32 for inet")
        elif api_user != 'test':
            raise Exception("Please enter integer value for prefix_len")
    elif api_user != 'test':
        raise Exception("Mandatory parameter 'prefix_len' absent")
    else:
        prefix_len = None


#Building the Nexthop for the RIB Route Params

    if 'communities' in kwargs:
        community = kwargs.get('communities')
        if isinstance(community, str):
            community_list = [
                community,
            ]
        elif isinstance(community, list):
            community_list = community
    elif api_user == 'test':
        community_list = prpd.Communities(communities=None)
    else:
        community_list = None

    if 'cluster_id' in kwargs:
        clusterid = kwargs.get('cluster_id')
        num_clusterid = prpd.ip_to_uint32(clusterid)
        cluster = wrappers_pb2.UInt32Value(value=num_clusterid)
    else:
        cluster = None

    if 'originator_id' in kwargs:
        originatorid = kwargs.get('originator_id')
        num_originatorid = prpd.ip_to_uint32(originatorid)
        originator = wrappers_pb2.UInt32Value(value=num_originatorid)
    else:
        originator = None

    if 'route_preference' in kwargs:
        route_preference = kwargs.get('route_preference')
        route_preference = int(route_preference)
        route_pref = wrappers_pb2.UInt32Value(value=route_preference)
    else:
        route_pref = None

    if 'local_preference' in kwargs:
        local_preference = kwargs.get('local_preference')
        local_preference = int(local_preference)
        local_pref = wrappers_pb2.UInt32Value(value=local_preference)
    else:
        local_pref = None

    if 'med' in kwargs:
        med = kwargs.get('med')
        med = int(med)
        bgpmd = wrappers_pb2.UInt32Value(value=med)
    else:
        bgpmd = None

    if 'aspath' in kwargs:
        aspath = kwargs.get('aspath')
        as_path = prpd.AsPath(aspath=aspath)
    elif api_user == 'test':
        as_path = prpd.AsPath(aspath=None)
    else:
        as_path = None

    if 'vpn_label' in kwargs:
        vpnlabel = kwargs.get('vpn_label')
        vpnlabel = int(vpnlabel)
    elif table is 'bgp.l3vpn.0' or table is 'bgp.l3vpn-inet6.0' and api_user != 'test':
        raise Exception("Mandatory parameter 'label' absent")
    else:
        vpnlabel = None

    if 'route_type' in kwargs:
        rt_type = kwargs.get('route_type')
        rt_type = int(rt_type)
    else:
        rt_type = None

    if 'path_cookie' in kwargs:
        pathcookie = kwargs.get('path_cookie')
        pathcookie = int(pathcookie)
    else:
        pathcookie = None

    if 'routedata' in kwargs and isinstance(kwargs['routedata'], dict):
        routedata = kwargs.get('routedata')
    elif table == 'bgp.inetsrte.0' or table == 'bgp.inet6srte.0' and api_user != 'test' and table == 'inetflow.0' and table == 'inet6flow.0':
        raise Exception("Mandatory parameter 'routedata' is absent")
    else:
        routedata = None

    if 'dpref_attr' in kwargs and isinstance(kwargs['dpref_attr'], dict):
        dpref_attr = kwargs["dpref_attr"]
    else:
        dpref_attr = {}

    routelist = list()

    for destprefix in dest_prefix:
        routeparams = prpd.RouteEntry()
        if destprefix is not None and table is not None and prefix_len is not None and api_user != 'test':
            if isinstance(
                    dpref_attr, dict
            ) and api_user != 'test' and 'table' in destprefix and dpref_attr is not None:
                dest_table = destprefix['table']
            else:
                dest_table = table
            dpref_attr["dest_prefix"] = destprefix
            dprefix = prefix_gen(dest_table, dpref_attr, api_user)
            routeparams.key.dest_prefix.CopyFrom(dprefix)
        if table is not None and api_user != 'test':
            table_name = prpd.RouteTable(name=prpd.RouteTableName(name=table))
            routeparams.key.table.CopyFrom(table_name)
        if prefix_len is not None and api_user != 'test':
            routeparams.key.dest_prefix_len = prefix_len
        if next_hop_list is not None and api_user != 'test':
            nhlist = []
            if multi_nh is not None:
                for bgpnh in next_hop_list:
                    nhlist.append(prpd.IpAddress(addr_string=bgpnh))
            elif len(dest_prefix) == len(next_hop_list):
                nhlist.append(prpd.IpAddress(addr_string=next_hop_list.pop(0)))
            else:
                nhlist.append(prpd.IpAddress(addr_string=next_hop_list[0]))
            routeparams.protocol_nexthops.extend(nhlist)
        if routedata is not None and api_user != 'test':
            routeparams.addr_family_data.CopyFrom(
                routedatagen(routedata, table, api_user))
        if local_pref is not None and api_user != 'test':
            routeparams.local_preference.CopyFrom(local_pref)
        if route_pref is not None and api_user != 'test':
            routeparams.route_preference.CopyFrom(route_pref)
        if bgpmd is not None and api_user != 'test':
            routeparams.med.CopyFrom(bgpmd)
        if as_path is not None and api_user != 'test':
            routeparams.aspath.CopyFrom(as_path)
        if community_list is not None and api_user != 'test':
            cm_list = []
            len_comm = len(community_list)
            for i in range(0, len_comm):
                comm = prpd.Community(community=community_list[i])
                cm_list.append(comm)
            c_list = prpd.Communities(communities=cm_list)
            routeparams.key.communities.CopyFrom(c_list)
        if cluster is not None and api_user != 'test':
            routeparams.cluster_id.CopyFrom(cluster)
        if originator is not None and api_user != 'test':
            routeparams.originator_id.CopyFrom(originator)
        if vpnlabel is not None and api_user != 'test':
            routeparams.label = vpnlabel
        if rt_type is not None and api_user != 'test':
            routeparams.route_type = rt_type
        if pathcookie is not None and api_user != 'test':
            routeparams.key.cookie = pathcookie
        routelist.append(routeparams)
    updreq = prpd.RouteUpdateRequest(routes=routelist)
    return updreq
コード例 #6
0
def generate_session_key(**kwargs):
    """
    Session Key Generate Request
    """

    localaddr_list = []
    remoteaddr_list = []
    interface_list = []

    if 'remote_address' in kwargs:
        if isinstance(kwargs["remote_address"], str):
            remoteaddr_list = [kwargs["remote_address"], ]
        elif isinstance(kwargs["remote_address"], list):
            remoteaddr_list = kwargs["remote_address"]
    else:
        raise Exception("Mandatory parameter 'remote_address' absent")


    if 'local_address' in kwargs:
        if isinstance(kwargs["local_address"], str):
            localaddr_list = [kwargs["local_address"], ]
        elif isinstance(kwargs["local_address"], list):
            localaddr_list = kwargs["local_address"]


    if 'interface_name' in kwargs:
        if isinstance(kwargs["interface_name"], str):
            interface_list = [kwargs["interface_name"], ]
        elif isinstance(kwargs["interface_name"], list):
            interface_list = kwargs["interface_name"]


    len_remote = len(remoteaddr_list)
    list_of_session = []

    for index in range(0, len_remote):
        session_key_add = prpd.SessionKey()

        if 'local_discriminator' in kwargs:
            if isinstance(kwargs["local_discriminator"], int):
                session_key_add.local_discriminator = kwargs.get('local_discriminator')
            else:
                raise Exception("Please enter integer value for local_discriminator")


        if 'remote_discriminator' in kwargs:
            if isinstance(kwargs["remote_discriminator"], int):
                session_key_add.remote_discriminator = kwargs.get('remote_discriminator')
            else:
                raise Exception("Please enter integer value for remote_discriminator")

        if 'cookie' in kwargs:
            if isinstance(kwargs["cookie"], int):
                session_key_add.cookie = kwargs.get('cookie')
            else:
                raise Exception("Please enter integer value for cookie")

        if 'session_id' in kwargs:
            if isinstance(kwargs["session_id"], int):
                session_key_add.session_id = kwargs.get('session_id')
            else:
                raise Exception("Please enter integer value for session_id")

        len_local = len(localaddr_list)
        len_int = len(interface_list)
        ip_type = prpd.netaddr.IPAddress(remoteaddr_list[index])
        family = ip_type.version
        if family == 6:
            session_key_add.remote_address.CopyFrom(prpd.NetworkAddress(inet6=prpd.IpAddress(addr_string=remoteaddr_list[index])))
            if index < len_local:
                session_key_add.local_address.CopyFrom(prpd.NetworkAddress(inet6=prpd.IpAddress(addr_string=localaddr_list[index])))
        else:
            session_key_add.remote_address.CopyFrom(prpd.NetworkAddress(inet=prpd.IpAddress(addr_string=remoteaddr_list[index])))
            if index < len_local:
                session_key_add.local_address.CopyFrom(prpd.NetworkAddress(inet=prpd.IpAddress(addr_string=localaddr_list[index])))

        if index < len_int:
            session_key_add.interface_name = str(interface_list[index])


        list_of_session.append(session_key_add)

    return list_of_session
コード例 #7
0
def rib_generate_update_req(**kwargs): # pylint: disable=too-many-branches
    """
    Update request method common for add/modify/update
    """

    if 'table' in kwargs:
        table = kwargs.get('table')
    else:
        raise Exception("Mandatory parameter 'table' absent")

    if 'dest_prefix' in kwargs:
        dest_prefix = kwargs.get('dest_prefix')
        if isinstance(kwargs["dest_prefix"], str):
            dest_prefix = [kwargs["dest_prefix"], ]
        elif isinstance(kwargs["dest_prefix"], list):
            dest_prefix = kwargs["dest_prefix"]
    else:
        raise Exception("Mandatory parameter 'destination_prefix' absent")

    if 'prefix_len' in kwargs:
        if isinstance(kwargs["prefix_len"], int):
            prefix_len = kwargs.get('prefix_len')
            if 'inet6' in table:
                if prefix_len > 128:
                    raise Exception("Prefix length should be <= 128 for inet6")
            elif 'inet.0' in table:
                if prefix_len > 32:
                    raise Exception("Prefix length should be <= 32 for inet")
            else:
                if prefix_len > 52:
                    raise Exception("Prefix length should be <= 52 for inet")
        else:
            raise Exception("Please enter integer value for prefix_len")
    else:
        raise Exception("Mandatory parameter 'prefix_length' absent")

    ecmp = kwargs.get("ecmp", False)


    if 'next_hop' in kwargs:
        if isinstance(kwargs["next_hop"], str):
            next_hop_list = [kwargs["next_hop"], ]
        elif isinstance(kwargs["next_hop"], list):
            next_hop_list = kwargs["next_hop"]
            if isinstance(next_hop_list[0], list):
                for i in range(0, len(next_hop_list)):
                    if len(next_hop_list[i]) > 513 and ecmp is True:
                        raise Exception("Next hop is limit exceeded with more than 512 nexthops for ecmp")
            elif len(next_hop_list) > 513 and ecmp is True:
                raise Exception("Next hop is limit exceeded with more than 512 nexthops for ecmp")
    else:
        raise Exception("Next hop is mandatory parameter.")

    #Removed deepcopy for enabling next_hop_list rotation via pop()
    #next_hop_list = prpd.deepcopy(next_hop_list)

    routelist = list()


    for index in range(0, len(dest_prefix)):

        #Building the Key for RIB Route Params
        if 'inet6' in table:
            destprefix = prpd.NetworkAddress(inet6=prpd.IpAddress(addr_string=dest_prefix[index]))
        else:
            if 'mpls' in table:
                destprefix = prpd.NetworkAddress(mpls=prpd.MplsAddress(label=int(dest_prefix[index])))
            else:
                destprefix = prpd.NetworkAddress(inet=prpd.IpAddress(addr_string=dest_prefix[index]))

        route_table = prpd.RouteTable(rtt_name=prpd.RouteTableName(name=table))

        route_match_field = prpd.RouteMatchFields(dest_prefix=destprefix, dest_prefix_len=prefix_len, table=route_table)

        if 'cookie' in kwargs:
            if isinstance(kwargs["cookie"], int):
                route_match_field.cookie = kwargs.get('cookie')

        # Update: Below code is handled in rib_nexthop
        # Calculating nexthop for below scenarios
        # ecmp is None
        # Only single nexthop is provided
#         if len(next_hop_list) >= 1 and ecmp is not True:
#
#
#             single_nh = []
#             single_nh.append(next_hop_list.pop(0))
#             next_hop_list.append(single_nh[0])
#
#             nh_list = rib_nexthop(single_nh, **kwargs)

#         elif len(next_hop_list) == 1 and ecmp is not True:
#
#             single_nh = []
#             single_nh.append(next_hop_list.pop(0))
#             next_hop_list.append(single_nh[0])
#
#             nh_list = rib_nexthop(single_nh, **kwargs)

#         elif ecmp == True and skip_rib_nexthop == False:

        nh_list = rib_nexthop(**kwargs)
                #skip_rib_nexthop = True
                # Commented above line to provide support for unique label stack
                # for each prefix

        routeparams = prpd.RouteEntry()

        attributes = 0
        # Added second if loop as pylint throws error for too many conditions in single if
        if 'preferences0' in kwargs or 'preferences1' in kwargs or 'colors0' in kwargs or 'no_advertise' in kwargs:

            rtattr = prpd.RouteAttributes()
            if 'preferences0' in kwargs:
                rtattr.preferences[0].CopyFrom(route_attribute(kwargs.get('preferences0')))

            if 'preferences1' in kwargs:
                rtattr.preferences[1].CopyFrom(route_attribute(kwargs.get('preferences1')))

            if 'colors0' in kwargs:
                rtattr.colors[0].CopyFrom(route_attribute(kwargs.get('colors0')))

            if 'no_advertise' in kwargs:
                rtattr.no_advertise = kwargs.get('no_advertise')
            attributes = 1


        if 'colors1' in kwargs or 'tags0' in kwargs or 'tags1' in kwargs or attributes == 1:

            if attributes == 0:
                rtattr = prpd.RouteAttributes()

            if 'colors1' in kwargs:
                rtattr.colors[1].CopyFrom(route_attribute(kwargs.get('colors1')))

            if 'tags0' in kwargs:
                rtattr.tags[0].CopyFrom(route_attribute(kwargs.get('tags0')))

            if 'tags1' in kwargs:
                rtattr.tags[1].CopyFrom(route_attribute(kwargs.get('tags1')))

            routeparams.attributes.CopyFrom(rtattr)

        routeparams.key.CopyFrom(route_match_field)
        routeparams.nexthop.CopyFrom(nh_list)

        routelist.append(routeparams)

    updreq = prpd.RouteUpdateRequest(routes=routelist)

    return updreq
コード例 #8
0
def rib_nexthop(**kwargs):# pylint: disable=too-many-branches

    """
    Module to generate label structure for add/modify/update functions

    Module either gets next_hop_list <= 513 when ecmp=True
    or gets 1 element for non ecmp scenario
    """

    if 'next_hop_interface' in kwargs:
        if isinstance(kwargs["next_hop_interface"], list):
            next_hop_interface_list = kwargs["next_hop_interface"]
        else:
            next_hop_interface_list = [kwargs["next_hop_interface"], ]
    else:
        next_hop_interface_list = []

    if 'label' in kwargs:
        if isinstance(kwargs["label"], (list)):
            label_list = kwargs["label"]
        else:
            label_list = [kwargs["label"], ]
    else:
        label_list = []


    if 'opcode' in kwargs:
        if isinstance(kwargs["opcode"], list):
            opcode_list = kwargs["opcode"]
        else:
            opcode_list = [kwargs["opcode"], ]
    else:
        opcode = []

    if 'weight' in kwargs:
        if isinstance(kwargs["weight"], list):
            weight_list = kwargs["weight"]
        else:
            weight_list = [kwargs["weight"], ]
    else:
        weight_list = []

    if 'bandwidth' in kwargs:
        if isinstance(kwargs["bandwidth"], list):
            bandwidth_list = kwargs["bandwidth"]
        else:
            bandwidth_list = [kwargs["bandwidth"], ]
    else:
        bandwidth_list = []

    stack_labels = kwargs.get('stack_labels', None)

    if 'next_hop' in kwargs:
        if isinstance(kwargs["next_hop"], str):
            next_hop_list = [kwargs["next_hop"], ]
        elif isinstance(kwargs["next_hop"], list):
            next_hop_list = kwargs["next_hop"]
    else:
        next_hop_list = []

    ecmp = kwargs.get("ecmp", False)

    nhlist = []
    nhlistoflists = False
    next_hop_innerlist = []
    next_hop_interface_innerlist = []
    weight_innerlist = []
    bandwidth_innerlist = []

    if isinstance(next_hop_list[0], list) and ecmp is True:# pylint: disable=too-many-branches
        nhlistoflists = True
        next_hop_innerlist = next_hop_list.pop(0)
        next_hop_list.append(next_hop_innerlist)
        nh_list_length = len(next_hop_innerlist)
    elif isinstance(next_hop_list[0], str) and ecmp is True:
        next_hop_innerlist = next_hop_list
        nh_list_length = len(next_hop_list)
    elif isinstance(next_hop_list[0], str) and ecmp is False:
        next_hop_innerlist.append(next_hop_list.pop(0))
        next_hop_list.extend(next_hop_innerlist)
        nh_list_length = 1
    elif isinstance(next_hop_list[0], list) and ecmp is False:
        next_hop_new_list = [item for sublist in next_hop_list for item in sublist]
        next_hop_innerlist.append(next_hop_new_list.pop(0))
        next_hop_new_list.extend(next_hop_innerlist)
        kwargs.pop("next_hop")
        kwargs.update(next_hop=next_hop_new_list)
        next_hop_list = next_hop_new_list
        nh_list_length = 1

    if len(next_hop_interface_list) > 0:
        next_hop_interface_exists = True
        if isinstance(next_hop_interface_list[0], list) and ecmp is True and nhlistoflists is True:# pylint: disable=too-many-branches
            next_hop_interface_innerlist = next_hop_interface_list.pop(0)
            next_hop_interface_list.append(next_hop_interface_innerlist)
        elif isinstance(next_hop_interface_list[0], str) and ecmp is True:
            next_hop_interface_innerlist = next_hop_interface_list
        elif isinstance(next_hop_interface_list[0], str) and ecmp is False:
            next_hop_interface_innerlist.append(next_hop_interface_list.pop(0))
            next_hop_interface_list.extend(next_hop_interface_innerlist)
        elif isinstance(next_hop_interface_list[0], list) and ecmp is False:
            next_hop_interface_new_list = [item for sublist in next_hop_interface_list for item in sublist]
            next_hop_interface_innerlist.append(next_hop_interface_new_list.pop(0))
            next_hop_interface_new_list.extend(next_hop_interface_innerlist)
            kwargs.pop("next_hop_interface")
            kwargs.update(next_hop_interface=next_hop_interface_new_list)
            next_hop_interface_list = next_hop_interface_new_list
    else:
        next_hop_interface_exists = False

    if len(weight_list) > 0:
        weight_exists = True
        if isinstance(weight_list[0], list) and ecmp is True and nhlistoflists is True:# pylint: disable=too-many-branches
            weight_innerlist = weight_list.pop(0)
            weight_list.append(weight_innerlist)
        elif (isinstance(weight_list[0], str) or isinstance(weight_list[0], int)) and ecmp is True:
            weight_innerlist = weight_list
        elif (isinstance(weight_list[0], str) or isinstance(weight_list[0], int)) and ecmp is False:
            weight_innerlist.append(weight_list.pop(0))
            weight_list.extend(weight_innerlist)
        elif isinstance(weight_list[0], list) and ecmp is False:
            weight_new_list = [item for sublist in weight_list for item in sublist]
            weight_innerlist.append(weight_new_list.pop(0))
            weight_new_list.extend(weight_innerlist)
            kwargs.pop("weight")
            kwargs.update(weight=weight_new_list)
            weight_list = weight_new_list
    else:
        weight_exists = False

    if len(bandwidth_list) > 0:
        bandwidth_exists = True
        if isinstance(bandwidth_list[0], list) and ecmp is True and nhlistoflists is True:# pylint: disable=too-many-branches
            bandwidth_innerlist = bandwidth_list.pop(0)
            bandwidth_list.append(bandwidth_innerlist)
        elif (isinstance(bandwidth_list[0], str) or isinstance(bandwidth_list[0], int)) and ecmp is True:
            bandwidth_innerlist = bandwidth_list
        elif (isinstance(bandwidth_list[0], str) or isinstance(bandwidth_list[0], int)) and ecmp is False:
            bandwidth_innerlist.append(bandwidth_list.pop(0))
            bandwidth_list.extend(bandwidth_list)
        elif isinstance(bandwidth_list[0], list) and ecmp is False:
            bandwidth_new_list = [item for sublist in bandwidth_list for item in sublist]
            bandwidth_innerlist.append(bandwidth_new_list.pop(0))
            bandwidth_new_list.extend(bandwidth_innerlist)
            kwargs.pop("bandwidth")
            kwargs.update(bandwidth=bandwidth_new_list)
            bandwidth_list = bandwidth_new_list
    else:
        bandwidth_exists = False


    for i in range(0, nh_list_length):# pylint: disable=too-many-nested-blocks

        next_hop = prpd.RouteGateway()

        ip_type = prpd.netaddr.IPAddress(next_hop_innerlist[i])
        ip_type.version

        next_hop_ip = next_hop_innerlist[i]

        if ip_type.version == 4:
            gateway = prpd.NetworkAddress(inet=prpd.IpAddress(addr_string=next_hop_ip))
        else:
            gateway = prpd.NetworkAddress(inet6=prpd.IpAddress(addr_string=next_hop_ip))


        if 'opcode' in kwargs:
            lblstkentrylist = list()

            if stack_labels is None:
                opcode = opcode_list.pop(0)
                opcode_list.append(opcode)
                if opcode.upper() == "POP":
                    lblstkentrylist.append(rib_labels("POP", 0))
                else:
                    element = label_list.pop(0)
                    label_list.append(element)
                    lblstkentrylist.append(rib_labels(opcode, element))
            else:
                if isinstance(label_list[0], list):

                    #labels = prpd.deepcopy(label_list.pop(0))
                    labels = label_list.pop(0)
                    label_list.append(labels)

                else:
                    labels = label_list

                for opcode in opcode_list:
                    if opcode.upper() == "POP":
                        lblstkentrylist.append(rib_labels("POP", 0))
                    else:
                        if not label_list:
                            logging.error("Label list is mandatory if opcode is used")
#                           if hasattr(builtins, 't'):
#                               raise TobyException("Label list is mandatory if opcode is used")
                        else:
                            opcode_length = len(opcode_list) - sum('pop' in single_opcode.lower() for single_opcode in opcode_list)

                            if opcode_length != len(labels):

                                logging.error("\n\
                                length Label-list != length opcode-list (POP is ignored)\n\
                                Label 0 is assigned internally for POP opcode \n\
                                Do not provide label value if opcode is POP \n\
                                Only provide label values for PUSH and SWAP operations")

#                                 if hasattr(builtins, 't'):
#                                     raise TobyException("Label list != opcode list (POP is ignored)")

                        element = labels.pop(0)
                        labels.append(element)
                        lblstkentrylist.append(rib_labels(opcode, element))

            lblstack = prpd.LabelStack(entries=lblstkentrylist)

            next_hop.label_stack.CopyFrom(lblstack)

        if next_hop_interface_exists:
            dest_intf_list_element = next_hop_interface_innerlist.pop(0)
            next_hop.interface_name = dest_intf_list_element
            next_hop_interface_innerlist.append(dest_intf_list_element)

        next_hop.gateway_address.CopyFrom(gateway)

        if weight_exists:
            weight_current = weight_innerlist.pop(0)
            if isinstance(weight_current, int):
                next_hop.weight = weight_current
            if isinstance(weight_current, str):
                next_hop.weight = weight_translate(weight_current)
            weight_innerlist.append(weight_current)

        if bandwidth_exists:
            bandwidth_element = bandwidth_innerlist.pop(0)
            next_hop.bandwidth = int(bandwidth_element)
            bandwidth_innerlist.append(bandwidth_element)

        nhlist.append(next_hop)


    return  prpd.RouteNexthop(gateways=nhlist)
コード例 #9
0
def rib_route_get(dev, channel_id, **kwargs):
    """
    To fetch routes present in the rib
    """

    # To handle same variable name across rib and bgp for destination_prefix,prefix_length
    dest_prefix_iterator = prpd.dest_prefix_limiter(**kwargs)

    if 'table' in kwargs:
        table = kwargs.get('table')

    else:
        raise Exception("Mandatory parameter 'table' absent")


    if 'prefix_len' in kwargs:

        if isinstance(kwargs["prefix_len"], int):
            prefix_len = kwargs.get('prefix_len')
            if 'inet6' in table:
                if prefix_len > 128:
                    raise Exception("Prefix length should be <= 128 for inet6")
            else:
                if prefix_len > 32:
                    raise Exception("Prefix length should be <= 32 for inet")
        else:
            raise Exception("Please enter integer value for prefix_len")

    else:
        raise Exception("Mandatory parameter 'prefix_len' absent")


    count = kwargs.get('route_count', 1000)


    if 'dest_prefix' in kwargs:
        dest_prefix = kwargs.get('dest_prefix')
    else:
        raise Exception("Mandatory parameter 'destination_prefix' absent")

    route_match_type = kwargs.get('route_match_type', prpd.BEST)


    if 'inet6' in table:
        destprefix = prpd.NetworkAddress(inet6=prpd.IpAddress(addr_string=dest_prefix))
    else:
        destprefix = prpd.NetworkAddress(inet=prpd.IpAddress(addr_string=dest_prefix))

    tablename = prpd.RouteTable(rtt_name=prpd.RouteTableName(name=table))

    route_match_field = prpd.RouteMatchFields(dest_prefix=destprefix, dest_prefix_len=prefix_len, table=tablename)


    if 'cookie' in kwargs:
        route_match_field.cookie = kwargs.get('cookie')

    #Defining the RouteGetRequest Structure
    getreq = prpd.RouteGetRequest(key=route_match_field, match_type=route_match_type, route_count=count)

    if 'active_routes' in kwargs:
        if kwargs['active_routes'].upper() == 'TRUE':
            getreq.active_only = True

    if 'tags0' in kwargs or 'tags1' in kwargs:
        rtattr = prpd.RouteExtendedMatchFields()

        if 'tags0' in kwargs:
            rtattr.tags[0].CopyFrom(route_attribute(kwargs.get('tags0')))

        if 'tags1' in kwargs:
            rtattr.tags[1].CopyFrom(route_attribute(kwargs.get('tags1')))

        getreq.extended_match.CopyFrom(rtattr)

    getreply = prpd.process_api(dev, channel_id, "RouteGet", [getreq, "Rib"], kwargs.get("timeout", None))


    return  getreply