BgplsServiceServicerImpl.py 10.1 KB
Newer Older
Pablo Armingol's avatar
Pablo Armingol committed
# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import grpc, json, logging
Pablo Armingol's avatar
Pablo Armingol committed
from typing import Optional,List, Tuple, Union
Pablo Armingol's avatar
Pablo Armingol committed
from bgpls_speaker.service.tools.DiscoveredDBManager import  DiscoveredDBManager, GetContextDevices
from bgpls_speaker.service.tools.GrpcServer import GrpcServer
from common.method_wrappers.Decorator import MetricsPool, safe_and_metered_rpc_method
from common.method_wrappers.ServiceExceptions import AlreadyExistsException, InvalidArgumentException
from common.proto.context_pb2 import (DeviceId, Empty, EndPointId, Link, LinkId, Service, ServiceId, ServiceStatusEnum, ServiceTypeEnum, TopologyId,ContextId,Topology
    ,Device,DeviceDriverEnum, Uuid)
from common.proto.pathcomp_pb2 import PathCompRequest
from common.proto.service_pb2_grpc import ServiceServiceServicer
from common.tools.grpc.Tools import grpc_message_to_json, grpc_message_to_json_string
from context.client.ContextClient import ContextClient
from pathcomp.frontend.client.PathCompClient import PathCompClient
from common.proto.bgpls_pb2 import (BgplsSpeaker,BgplsSpeakerId, DiscoveredDeviceList,DiscoveredDevice,
                                    DiscoveredLink,DiscoveredLinkList,NodeDescriptors,BgplsSpeakerList)
from common.proto.bgpls_pb2_grpc import BgplsServiceServicer

Pablo Armingol's avatar
Pablo Armingol committed
def json_to_list(json_str : str) -> List[Union[str, Tuple[str, str]]]:
    try:
        data = json.loads(json_str)
    except: # pylint: disable=bare-except
        return [('item', str(json_str))]

    if isinstance(data, dict):
        return [('kv', (key, value)) for key, value in data.items()]
    elif isinstance(data, list):
        return [('item', ', '.join(data))]
    else:
        return [('item', str(data))]
    
Pablo Armingol's avatar
Pablo Armingol committed
LOGGER = logging.getLogger(__name__)

METRICS_POOL = MetricsPool('Service', 'RPC')

class BgplsServiceServicerImpl(BgplsServiceServicer):
    def __init__(self,discoveredDB : DiscoveredDBManager,
                 speakerServer : GrpcServer) -> None:
        LOGGER.debug('Creating Servicer...')
        self.speaker_handler_factory = 1
        self.speaker_server=speakerServer
        self.discoveredDB=discoveredDB
        LOGGER.debug('Servicer Created')
    
    @safe_and_metered_rpc_method(METRICS_POOL, LOGGER)
    def ListDiscoveredDevices(self, request : Empty, context : grpc.ServicerContext) -> DiscoveredDeviceList:
        """
        Get devices discovered from bgpls protocol
        """
        device_names=self.discoveredDB.GetNodeNamesFromDiscoveredDB()
        nodes = self.discoveredDB.GetNodesFromDiscoveredDB()
        devices = [DiscoveredDevice(nodeName=node.node_name,igpID=node.igp_id,learntFrom=node.learnt_from) for node in nodes]
        return DiscoveredDeviceList(discovereddevices=devices)

    @safe_and_metered_rpc_method(METRICS_POOL, LOGGER)
    def ListDiscoveredLinks(self, request : Empty, context : grpc.ServicerContext) -> DiscoveredLinkList:
        """
        Get links discovered from bgpls protocol
        """
        self.discoveredDB.UpdateNodeNameInLink()
        links = self.discoveredDB.GetLinksFromDiscoveredDB()
        links_info=[]
        for link in links:
Pablo Armingol's avatar
Pablo Armingol committed
            local=NodeDescriptors(igp_id=link.local_id,nodeName=link.local_id)
            remote=NodeDescriptors(igp_id=link.remote_id,nodeName=link.remote_id)
Pablo Armingol's avatar
Pablo Armingol committed
            links_info.append(DiscoveredLink(local=local,remote=remote,learntFrom=link.learnt_from,
                                             local_ipv4=link.local_ipv4_id,remote_ipv4=link.remote_ipv4_id))
Pablo Armingol's avatar
Pablo Armingol committed
        return DiscoveredLinkList(discoveredlinks=links_info)
    
    @safe_and_metered_rpc_method(METRICS_POOL, LOGGER)
    def AddBgplsSpeaker(self, request : BgplsSpeaker, context : grpc.ServicerContext) -> BgplsSpeakerId:
        """
        Creates a new connection with an speaker with the given ip address, port and as.
        Returns de id of the speaker created (to kill proccess¿)
        """
        LOGGER.debug("(AddBgplsSpeaker) Create speaker instance %s",request)

        speaker_id=self.speaker_server.connectToJavaBgpls(request.address,request.port,request.asNumber)
        return BgplsSpeakerId(id=speaker_id)
    
    @safe_and_metered_rpc_method(METRICS_POOL, LOGGER)
    def ListBgplsSpeakers(self, request : Empty, context : grpc.ServicerContext) -> BgplsSpeakerId:
        """
        Returns a list of the IDs of the BGP-LS speakers with open connections. 
        """
        speaker_list=[]
        bgpls_speaker_list=[]
        speaker_list=self.speaker_server.getSpeakerListIds()
        for speaker in speaker_list:
            bgpls_speaker_list.append(BgplsSpeakerId(id=speaker))
        return BgplsSpeakerList(speakers=bgpls_speaker_list)
    
    @safe_and_metered_rpc_method(METRICS_POOL, LOGGER)
    def DisconnectFromSpeaker(self, request : BgplsSpeaker, context : grpc.ServicerContext) -> bool:
        """
        Disconencts from the BGP-LS speaker given its ipv4 address.
        """
        speaker_id=self.speaker_server.getSpeakerIdFromIpAddr(request.address)
        self.speaker_server.terminateRunnerById(speaker_id)
        return Empty()

    @safe_and_metered_rpc_method(METRICS_POOL, LOGGER)
    def GetSpeakerInfoFromId(self, request : BgplsSpeakerId, context : grpc.ServicerContext) -> BgplsSpeaker:
        """
        Get the address, port and as number of the speaker given its id.
        """
        address,as_number,port=self.speaker_server.getSpeakerFromId(request.id)
        return BgplsSpeaker(address=address,port=port,asNumber=as_number)
    
    @safe_and_metered_rpc_method(METRICS_POOL, LOGGER)
    def NotifyAddNodeToContext(self, request : DiscoveredDevice, context : grpc.ServicerContext) :
        """
        When a node is added to context via bgpls module this function checks if there are other nodes in the
        topology connected by links discovered via bgpls. Then, if the link exist adds it to the context.
        TODO: get endpoints from pce module
        """
        node_name=request.nodeName
Pablo Armingol's avatar
Pablo Armingol committed
        node_igp=self.discoveredDB.GetIgpIdFromNodeName(node_name)
Pablo Armingol's avatar
Pablo Armingol committed
        LOGGER.debug("(NotifyAddNodeToContext) Find links to nodes ")
Pablo Armingol's avatar
Pablo Armingol committed
        nodes_conected=self.discoveredDB.FindConnectedNodes(node_igp)
Pablo Armingol's avatar
Pablo Armingol committed
        # Check if nodes are in context
        context_client=ContextClient()
        context_client.connect()
        # devices=context_client.ListDevices(Empty())
        device_names,devices_ips=GetContextDevices(context_client)
        LOGGER.debug("(NotifyAddNodeToContext) Devices in context: %s", device_names)
Pablo Armingol's avatar
Pablo Armingol committed
        LOGGER.debug("(NotifyAddNodeToContext) Nodes conected in context: %s", nodes_conected)
Pablo Armingol's avatar
Pablo Armingol committed
        nodes_conected_in_context=list(set(nodes_conected) & set(device_names))
        LOGGER.debug("(NotifyAddNodeToContext) nodes_conected_in_context: %s", nodes_conected_in_context)
        # TODO: next to function
        for remote_node in nodes_conected_in_context:

            # TODO: get endpoints connected to remote ip (pce¿)
            end_point1="eth-1/0/20"
            end_point2="eth-1/0/20"
            end_point_uuid1=Uuid(uuid=end_point1)
            end_point_uuid2=Uuid(uuid=end_point2)
Pablo Armingol's avatar
Pablo Armingol committed
            
Pablo Armingol's avatar
Pablo Armingol committed
            link_name_src_dest=node_name+"/"+end_point1+"=="+remote_node+"/"+end_point2
            device_uuid_src=DeviceId(device_uuid=Uuid(uuid=node_name))
Pablo Armingol's avatar
Pablo Armingol committed
            device_src=context_client.GetDevice(device_uuid_src)
Pablo Armingol's avatar
Pablo Armingol committed

            link_name_dest_src=remote_node+"/"+end_point2+"=="+node_name+"/"+end_point1
            device_uuid_dest=DeviceId(device_uuid=Uuid(uuid=remote_node))
Pablo Armingol's avatar
Pablo Armingol committed
            device_dest=context_client.GetDevice(device_uuid_dest)

            self.getEndpointFromIpInterface(device_src,link.local_ipv4_id)
            self.getEndpointFromIpInterface(device_dest,link.remote_ipv4_id)
            # LOGGER.debug("(NotifyAddNodeToContext) Source: %s Destination: %s", device_src,device_dest)

Pablo Armingol's avatar
Pablo Armingol committed
            end_point_id1=EndPointId(endpoint_uuid=end_point_uuid1,device_id=device_uuid_src)
            end_point_id2=EndPointId(endpoint_uuid=end_point_uuid2,device_id=device_uuid_dest)

            end_point_ids_src_dest=[end_point_id1,end_point_id2]
            end_point_ids_dest_src=[end_point_id2,end_point_id1]

            link_id_src=context_client.SetLink(Link(link_id=LinkId(link_uuid=Uuid(uuid=link_name_src_dest)),
                                                    link_endpoint_ids=end_point_ids_src_dest))
            
            link_id_dst=context_client.SetLink(Link(link_id=LinkId(link_uuid=Uuid(uuid=link_name_dest_src)),
                                                    link_endpoint_ids=end_point_ids_dest_src))

            LOGGER.debug("(NotifyAddNodeToContext) Link set id src--->dst: %s", link_id_src)
        context_client.close()
        return Empty()
Pablo Armingol's avatar
Pablo Armingol committed

    def getEndpointFromIpInterface(self,device,ipv4):
        """
        Get TFS endpoint from interface IPv4.
        """
        for config in device.device_config.config_rules:
            if config.WhichOneof('config_rule') == 'custom':
                for item_type, item in json_to_list(config.custom.resource_value):
                    if item_type == 'kv':
                        # LOGGER.debug("(getEndpointFromIpInterface) item: %s",item)
                        endpoint=item
                LOGGER.debug("(getEndpointFromIpInterface) config: %s",config.custom.resource_key)
                if "/interface" in config.custom.resource_key:
                    interface=config.custom.resource_key.split("/interface")[1].strip("[]")
                    LOGGER.debug("(getEndpointFromIpInterface) interface: %s",interface)
                    if ipv4 in config.custom.resource_value:
                        LOGGER.debug("(getEndpointFromIpInterface) value: %s",config.custom.resource_value)
        return endpoint