Commit 86e0096e authored by Lluis Gifre Renom's avatar Lluis Gifre Renom
Browse files

Remove old code

parent d70ef6ca
Loading
Loading
Loading
Loading

src/context/old_code/Tools.py

deleted100644 → 0
+0 −70
Original line number Diff line number Diff line
import grpc, logging
from typing import Dict, List, Set, Tuple
from common.Checkers import chk_string
from common.Constants import DEFAULT_CONTEXT_UUID, DEFAULT_TOPOLOGY_UUID
from common.exceptions.ServiceException import ServiceException
from context.proto.context_pb2 import Link, LinkId
from context.service.database.api.Database import Database
from context.service.database.api.context.topology.device.Endpoint import Endpoint
from context.service.database.checkers.EndpointIdCheckers import check_endpoint_id
from context.service.database.checkers.DeviceCheckers import check_device_endpoint_exists
from context.service.database.checkers.LinkCheckers import check_link_exists, check_link_not_exists

def _check_link_exists(method_name : str, database : Database, link_id : str):
    if method_name in ['AddLink']:
        check_link_not_exists(database, DEFAULT_CONTEXT_UUID, DEFAULT_TOPOLOGY_UUID, link_id)
    elif method_name in ['DeleteLink']:
        check_link_exists(database, DEFAULT_CONTEXT_UUID, DEFAULT_TOPOLOGY_UUID, link_id)
    else:                                       # pragma: no cover (test requires malforming the code)
        msg = 'Unexpected condition [_check_link_exists(method_name={}, link_id={})]'
        msg = msg.format(str(method_name), str(link_id))
        raise ServiceException(grpc.StatusCode.UNIMPLEMENTED, msg)

def check_link_request(
    method_name : str, request : Link, database : Database, logger : logging.Logger
    ) -> Tuple[str, List[Endpoint]]:

    # ----- Parse attributes -------------------------------------------------------------------------------------------
    try:
        link_id = chk_string('link.link_id.link_id.uuid',
                             request.link_id.link_id.uuid,
                             allow_empty=False)
    except Exception as e:
        logger.exception('Invalid arguments:')
        raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, str(e))

    # ----- Check if link exists in database ---------------------------------------------------------------------------
    _check_link_exists(method_name, database, link_id)

    # ----- Parse endpoints and check if they exist in the database as device endpoints --------------------------------
    add_topology_devices_endpoints : Dict[str, Dict[str, Set[str]]] = {}
    db_endpoints : List[Endpoint] = []
    for endpoint_number,endpoint_id in enumerate(request.endpointList):
        parent_name = 'Endpoint(#{}) of Context({})/Topology({})/Link({})'
        parent_name = parent_name.format(endpoint_number, DEFAULT_CONTEXT_UUID, DEFAULT_TOPOLOGY_UUID, link_id)

        _, ep_device_id, ep_port_id = check_endpoint_id(
            logger, endpoint_number, parent_name, endpoint_id, add_topology_devices_endpoints)

        db_endpoint = check_device_endpoint_exists(
            database, parent_name, DEFAULT_CONTEXT_UUID, DEFAULT_TOPOLOGY_UUID, ep_device_id, ep_port_id)
        db_endpoints.append(db_endpoint)

    return link_id, db_endpoints

def check_link_id_request(
    method_name : str, request : LinkId, database : Database, logger : logging.Logger) -> str:

    # ----- Parse attributes -------------------------------------------------------------------------------------------
    try:
        link_id = chk_string('link_id.link_id.uuid',
                             request.link_id.uuid,
                             allow_empty=False)
    except Exception as e:
        logger.exception('Invalid arguments:')
        raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, str(e))

    # ----- Check if link exists in database ---------------------------------------------------------------------------
    _check_link_exists(method_name, database, link_id)

    return link_id
+0 −50
Original line number Diff line number Diff line
import grpc
from common.exceptions.ServiceException import ServiceException
from context.service.database.api.Database import Database
from context.service.database.api.context.topology.device.Endpoint import Endpoint

def check_device_exists(database : Database, context_id : str, topology_id : str, device_id : str):
    db_context = database.context(context_id).create()
    db_topology = db_context.topology(topology_id).create()
    if db_topology.devices.contains(device_id): return
    msg = 'Context({})/Topology({})/Device({}) does not exist in the database.'
    msg = msg.format(context_id, topology_id, device_id)
    raise ServiceException(grpc.StatusCode.NOT_FOUND, msg)

def check_device_not_exists(database : Database, context_id : str, topology_id : str, device_id : str):
    db_context = database.context(context_id).create()
    db_topology = db_context.topology(topology_id).create()
    if not db_topology.devices.contains(device_id): return
    msg = 'Context({})/Topology({})/Device({}) already exists in the database.'
    msg = msg.format(context_id, topology_id, device_id)
    raise ServiceException(grpc.StatusCode.ALREADY_EXISTS, msg)

def check_device_endpoint_exists(
    database : Database, parent_name : str,
    context_id : str, topology_id : str, device_id : str, port_id : str) -> Endpoint:

    # Implicit validation: parent.context == endpoint.context, and parent.context created automatically
    if not database.contexts.contains(context_id):          # pragma: no cover
        msg = 'Context({}) in {} does not exist in the database.'
        msg = msg.format(context_id, parent_name)
        raise ServiceException(grpc.StatusCode.NOT_FOUND, msg)
    db_context = database.context(context_id)

    if not db_context.topologies.contains(topology_id):
        msg = 'Context({})/Topology({}) in {} does not exist in the database.'
        msg = msg.format(context_id, topology_id, parent_name)
        raise ServiceException(grpc.StatusCode.NOT_FOUND, msg)
    db_topology = db_context.topology(topology_id)

    if not db_topology.devices.contains(device_id):
        msg = 'Context({})/Topology({})/Device({}) in {} does not exist in the database.'
        msg = msg.format(context_id, topology_id, device_id, parent_name)
        raise ServiceException(grpc.StatusCode.NOT_FOUND, msg)
    db_device = db_topology.device(device_id)

    if not db_device.endpoints.contains(port_id):
        msg = 'Context({})/Topology({})/Device({})/Port({}) in {} does not exist in the database.'
        msg = msg.format(context_id, topology_id, device_id, port_id, parent_name)
        raise ServiceException(grpc.StatusCode.NOT_FOUND, msg)

    return db_device.endpoint(port_id)
+0 −86
Original line number Diff line number Diff line
import grpc, logging
from typing import Dict, Set, Tuple, Union
from common.Checkers import chk_string
from common.Constants import DEFAULT_CONTEXT_UUID, DEFAULT_TOPOLOGY_UUID
from common.exceptions.ServiceException import ServiceException

def check_endpoint_id(
    logger : logging.Logger, endpoint_number : int, parent_name : str, endpoint_id : 'EndpointId',
    add_topology_devices_endpoints : Dict[str, Dict[str, Set[str]]],
    predefined_context_id : str = DEFAULT_CONTEXT_UUID,
    acceptable_context_ids : Set[str] = set([DEFAULT_CONTEXT_UUID]),
    predefined_topology_id : str = DEFAULT_TOPOLOGY_UUID,
    acceptable_topology_ids : Set[str] = set([DEFAULT_TOPOLOGY_UUID]),
    predefined_device_id : Union[str, None] = None, acceptable_device_ids : Set[str] = set(),
    prevent_same_device_multiple_times : bool = True) -> Tuple[str, str, str]:

    try:
        ep_context_id  = chk_string('endpoint_id[#{}].topoId.contextId.contextUuid.uuid'.format(endpoint_number),
                                    endpoint_id.topoId.contextId.contextUuid.uuid,
                                    allow_empty=True)
        ep_topology_id = chk_string('endpoint_id[#{}].topoId.topoId.uuid'.format(endpoint_number),
                                    endpoint_id.topoId.topoId.uuid,
                                    allow_empty=True)
        ep_device_id   = chk_string('endpoint_id[#{}].dev_id.device_id.uuid'.format(endpoint_number),
                                    endpoint_id.dev_id.device_id.uuid,
                                    allow_empty=(predefined_device_id is not None))
        ep_port_id     = chk_string('endpoint_id[#{}].port_id.uuid'.format(endpoint_number),
                                    endpoint_id.port_id.uuid,
                                    allow_empty=False)
    except Exception as e:
        logger.exception('Invalid arguments:')
        raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, str(e))

    if len(ep_context_id) == 0:
        # Assumption: if no context is specified for an endpoint_id, use predefined context
        ep_context_id = predefined_context_id
    elif (len(acceptable_context_ids) > 0) and (ep_context_id not in acceptable_context_ids):
        # Assumption: parent and endpoints should belong to the same context
        msg = ' '.join([
            'Context({}) in {} mismatches acceptable Contexts({}).',
            'Optionally, leave field empty to use predefined Context({}).',
        ])
        msg = msg.format(
            ep_context_id, parent_name, str(acceptable_context_ids), predefined_context_id)
        raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, msg)

    if len(ep_topology_id) == 0:
        # Assumption: if no topology is specified for an endpoint_id, use predefined topology
        ep_topology_id = predefined_topology_id
    elif (len(acceptable_topology_ids) > 0) and (ep_topology_id not in acceptable_topology_ids):
        msg = ' '.join([
            'Context({})/Topology({}) in {} mismatches acceptable Topologies({}).',
            'Optionally, leave field empty to use predefined Topology({}).',
        ])
        msg = msg.format(
            ep_context_id, ep_topology_id, parent_name, str(acceptable_topology_ids), predefined_topology_id)
        raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, msg)

    if (predefined_device_id is not None) and (len(ep_device_id) == 0):
        # Assumption: if no device is specified for an endpoint_id, use predefined device, if available
        ep_device_id = predefined_device_id
    elif (len(acceptable_device_ids) > 0) and (ep_device_id not in acceptable_device_ids):
        msg = ' '.join([
            'Context({})/Topology({})/Device({}) in {} mismatches acceptable Devices({}).',
            'Optionally, leave field empty to use predefined Device({}).',
        ])
        msg = msg.format(
            ep_context_id, ep_topology_id, ep_device_id, parent_name, str(acceptable_device_ids), predefined_device_id)
        raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, msg)

    add_devices = add_topology_devices_endpoints.setdefault(ep_topology_id, dict())
    if prevent_same_device_multiple_times and (ep_device_id in add_devices):
        msg = 'Duplicated Context({})/Topology({})/Device({}) in {}.'
        msg = msg.format(ep_context_id, ep_topology_id, ep_device_id, parent_name)
        raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, msg)

    add_device_and_endpoints = add_devices.setdefault(ep_device_id, set())

    # Implicit validation: same device cannot appear 2 times in the list of endpoints
    if ep_port_id in add_device_and_endpoints:                                # pragma: no cover
        msg = 'Duplicated Context({})/Topology({})/Device({})/Port({}) in {}.'
        msg = msg.format(ep_context_id, ep_topology_id, ep_device_id, ep_port_id, parent_name)
        raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, msg)

    add_device_and_endpoints.add(ep_port_id)
    return ep_topology_id, ep_device_id, ep_port_id
+0 −24
Original line number Diff line number Diff line
import grpc
from enum import Enum
from common.exceptions.ServiceException import ServiceException

def check_enum(enum_name, method_name, value, to_enum_method, accepted_values_dict) -> Enum:
    _value = to_enum_method(value)
    if _value is None:                          # pragma: no cover (gRPC prevents unsupported values)
        msg = 'Unsupported {}({}).'
        msg = msg.format(enum_name, value)
        raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, msg)

    accepted_values = accepted_values_dict.get(method_name)
    if accepted_values is None:                 # pragma: no cover (test requires malforming the code)
        msg = '{} acceptable values not specified for Method({}).'
        msg = msg.format(enum_name, method_name)
        raise ServiceException(grpc.StatusCode.INTERNAL, msg)

    if len(accepted_values) == 0: return _value
    if _value in accepted_values: return _value

    msg = 'Method({}) does not accept {}({}). Permitted values for Method({}) are {}({}).'
    accepted_values_list = sorted(map(lambda v: v.name, accepted_values))
    msg = msg.format(method_name, enum_name, _value.name, method_name, enum_name, accepted_values_list)
    raise ServiceException(grpc.StatusCode.INVALID_ARGUMENT, msg)
+0 −19
Original line number Diff line number Diff line
import grpc
from common.exceptions.ServiceException import ServiceException
from context.service.database.api.Database import Database

def check_link_exists(database : Database, context_id : str, topology_id : str, link_id : str):
    db_context = database.context(context_id).create()
    db_topology = db_context.topology(topology_id).create()
    if db_topology.links.contains(link_id): return
    msg = 'Context({})/Topology({})/Link({}) does not exist in the database.'
    msg = msg.format(context_id, topology_id, link_id)
    raise ServiceException(grpc.StatusCode.NOT_FOUND, msg)

def check_link_not_exists(database : Database, context_id : str, topology_id : str, link_id : str):
    db_context = database.context(context_id).create()
    db_topology = db_context.topology(topology_id).create()
    if not db_topology.links.contains(link_id): return
    msg = 'Context({})/Topology({})/Link({}) already exists in the database.'
    msg = msg.format(context_id, topology_id, link_id)
    raise ServiceException(grpc.StatusCode.ALREADY_EXISTS, msg)
Loading