Skip to content
Snippets Groups Projects
PathCompServiceServicerImpl.py 5.33 KiB
Newer Older
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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.

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
import grpc, json, logging, requests, uuid
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
from typing import List
from common.proto.context_pb2 import Connection, Empty, EndPointId
from common.proto.pathcomp_pb2 import PathCompReply, PathCompRequest
from common.proto.pathcomp_pb2_grpc import PathCompServiceServicer
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
from common.rpc_method_wrapper.Decorator import create_metrics, safe_and_metered_rpc_method
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
from common.tools.grpc.Tools import grpc_message_to_json, grpc_message_to_json_string
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
from context.client.ContextClient import ContextClient
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
from pathcomp.frontend.Config import BACKEND_HOST, BACKEND_PORT, BACKEND_URL
from pathcomp.frontend.service.tools.ComposeRequest import compose_device, compose_link, compose_service
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed

LOGGER = logging.getLogger(__name__)

SERVICE_NAME = 'PathComp'
METHOD_NAMES = ['Compute']
METRICS = create_metrics(SERVICE_NAME, METHOD_NAMES)

class PathCompServiceServicerImpl(PathCompServiceServicer):
    def __init__(self) -> None:
        LOGGER.debug('Creating Servicer...')
        LOGGER.debug('Servicer Created')

    @safe_and_metered_rpc_method(METRICS, LOGGER)
    def Compute(self, request : PathCompRequest, context : grpc.ServicerContext) -> PathCompReply:
        LOGGER.info('[Compute] begin ; request = {:s}'.format(grpc_message_to_json_string(request)))
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        algorithm = request.WhichOneof('algorithm')
        if algorithm == 'shortest_path':
            # no attributes
            pass
        elif algorithm == 'k_shortest_path':
            k_inspection = request.k_shortest_path.k_inspection
            k_return = request.k_shortest_path.k_return
        else:
            raise NotImplementedError('Unsupported Algorithm: {:s}'.format(str(algorithm)))

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        context_client = ContextClient()

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        algorithm = {'id': 'KSP', 'sync': False, 'k_paths': k_return}
        service_list = [
            compose_service(grpc_service, algorithm)
            for grpc_service in request.services
        ]

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        # TODO: consider filtering resources

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        #grpc_contexts = context_client.ListContexts(Empty())
        #for grpc_context in grpc_contexts.contexts:
        #    # TODO: add context to request
        #    grpc_topologies = context_client.ListTopologies(grpc_context.context_id)
        #    for grpc_topology in grpc_topologies.topologies:    #pylint: disable=unused-variable
        #        # TODO: add topology to request
        #        pass

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        grpc_devices = context_client.ListDevices(Empty())
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        device_list = [
            compose_device(grpc_device)
            for grpc_device in grpc_devices.devices
        ]

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        grpc_links = context_client.ListLinks(Empty())
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        link_list = [
            compose_link(grpc_link)
            for grpc_link in grpc_links.links
        ]

        request = {
            'serviceList': service_list,
            'deviceList' : device_list,
            'linkList'   : link_list,
        }

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        #with open('pc-req.json', 'w', encoding='UTF-8') as f:
        #    f.write(json.dumps(request, sort_keys=True, indent=4))

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        backend_url = BACKEND_URL.format(BACKEND_HOST, BACKEND_PORT)
        reply = requests.post(backend_url, json=request)
        if reply.status_code not in {requests.codes.ok}:
            raise Exception('Backend error({:s}) for request({:s})'.format(
                str(reply.content.decode('UTF-8')), json.dumps(request, sort_keys=True)))
        LOGGER.info('status_code={:s} reply={:s}'.format(
            str(reply.status_code), str(reply.content.decode('UTF-8'))))


Lluis Gifre Renom's avatar
Lluis Gifre Renom committed

        reply = PathCompReply()
        # TODO: compose reply populating reply.services and reply.connections

        for service in request.services:
            # TODO: implement support for multi-point services
            service_endpoint_ids = service.service_endpoint_ids
            if len(service_endpoint_ids) != 2: raise NotImplementedError('Service must have 2 endpoints')
            a_endpoint_id, z_endpoint_id = service_endpoint_ids[0], service_endpoint_ids[-1]

            connection_uuid = str(uuid.uuid4())
            connection_path_hops : List[EndPointId] = []
            connection_path_hops.extend([
                grpc_message_to_json(a_endpoint_id),
                grpc_message_to_json(z_endpoint_id),
            ])
            connection = Connection(**{
                'connection_id': {'connection_uuid': {'uuid': connection_uuid}},
                'service_id': grpc_message_to_json(service.service_id),
                'path_hops_endpoint_ids': connection_path_hops,
                'sub_service_ids': [],
            })
            reply.connections.append(connection)    #pylint: disable=no-member
            reply.services.append(service)          #pylint: disable=no-member

        LOGGER.info('[Compute] end ; reply = {:s}'.format(grpc_message_to_json_string(reply)))
        return reply