Skip to content
Snippets Groups Projects
Select Git revision
  • c127e8b0de0d2b0edaf1a07f7f9aa1d3beb3de52
  • master default
  • cnit_ofc26
  • feat/344-implement-a-new-firewall-agent-controllable-through-restconf-openconfig
  • feat/343-integration-of-mimir-deployment-in-production-environment
  • ofc_polimi
  • feat/305-cttc-enhanced-netconf-openconfig-sbi-driver-for-dscm-pluggables
  • feat/306-cttc-enhanced-restconf-based-openconfig-nbi-for-dscm-pluggables
  • feat/301-cttc-dscm-pluggables
  • CTTC-IMPLEMENT-NBI-CONNECTOR-NOS-ZTP
  • CTTC-TEST-SMARTNICS-6GMICROSDN-ZTP
  • develop protected
  • feat/327-tid-new-service-to-ipowdm-controller-to-manage-transceivers-configuration-on-external-agent
  • cnit_tapi
  • feat/330-tid-pcep-component
  • feat/tid-newer-pcep-component
  • feat/116-ubi-updates-in-telemetry-backend-to-support-p4-in-band-network-telemetry
  • feat/292-cttc-implement-integration-test-for-ryu-openflow
  • cnit-p2mp-premerge
  • feat/325-tid-nbi-e2e-to-manage-e2e-path-computation
  • feat/326-tid-external-management-of-devices-telemetry-nbi
  • feat/324-tid-nbi-ietf_l3vpn-deploy-fail
  • v5.0.0 protected
  • v4.0.0 protected
  • demo-dpiab-eucnc2024
  • v3.0.0 protected
  • v2.1.0 protected
  • v2.0.0 protected
  • v1.0.0 protected
29 results

CommonObjects.py

Blame
  • Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    Topology.py 5.40 KiB
    # 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.
    
    import datetime, logging
    from sqlalchemy.dialects.postgresql import insert
    from sqlalchemy.engine import Engine
    from sqlalchemy.orm import Session, sessionmaker
    from sqlalchemy_cockroachdb import run_transaction
    from typing import Dict, List, Optional, Tuple
    from common.proto.context_pb2 import ContextId, Topology, TopologyId
    from common.method_wrappers.ServiceExceptions import NotFoundException
    from common.tools.object_factory.Context import json_context_id
    from common.tools.object_factory.Topology import json_topology_id
    from .models.TopologyModel import TopologyModel
    from .uuids.Context import context_get_uuid
    from .uuids.Topology import topology_get_uuid
    
    LOGGER = logging.getLogger(__name__)
    
    def topology_list_ids(db_engine : Engine, request : ContextId) -> List[Dict]:
        context_uuid = context_get_uuid(request, allow_random=False)
        def callback(session : Session) -> List[Dict]:
            obj_list : List[TopologyModel] = session.query(TopologyModel).filter_by(context_uuid=context_uuid).all()
            return [obj.dump_id() for obj in obj_list]
        return run_transaction(sessionmaker(bind=db_engine), callback)
    
    def topology_list_objs(db_engine : Engine, request : ContextId) -> List[Dict]:
        context_uuid = context_get_uuid(request, allow_random=False)
        def callback(session : Session) -> List[Dict]:
            obj_list : List[TopologyModel] = session.query(TopologyModel).filter_by(context_uuid=context_uuid).all()
            return [obj.dump() for obj in obj_list]
        return run_transaction(sessionmaker(bind=db_engine), callback)
    
    def topology_get(db_engine : Engine, request : TopologyId) -> Dict:
        _,topology_uuid = topology_get_uuid(request, allow_random=False)
        def callback(session : Session) -> Optional[Dict]:
            obj : Optional[TopologyModel] = session.query(TopologyModel)\
                .filter_by(topology_uuid=topology_uuid).one_or_none()
            return None if obj is None else obj.dump()
        obj = run_transaction(sessionmaker(bind=db_engine), callback)
        if obj is None:
            context_uuid = context_get_uuid(request.context_id, allow_random=False)
            raw_topology_uuid = '{:s}/{:s}'.format(request.context_id.context_uuid.uuid, request.topology_uuid.uuid)
            raise NotFoundException('Topology', raw_topology_uuid, extra_details=[
                'context_uuid generated was: {:s}'.format(context_uuid),
                'topology_uuid generated was: {:s}'.format(topology_uuid),
            ])
        return obj
    
    def topology_set(db_engine : Engine, request : Topology) -> Tuple[Dict, bool]:
        topology_name = request.name
        if len(topology_name) == 0: topology_name = request.topology_id.topology_uuid.uuid
        context_uuid,topology_uuid = topology_get_uuid(request.topology_id, topology_name=topology_name, allow_random=True)
    
        # Ignore request.device_ids and request.link_ids. They are used for retrieving devices and links added into the
        # topology. Explicit addition into the topology is done automatically when creating the devices and links, based
        # on the topologies specified in the endpoints associated with the devices and links.
    
        if len(request.device_ids) > 0:   # pragma: no cover
            LOGGER.warning('Items in field "device_ids" ignored. This field is used for retrieval purposes only.')
    
        if len(request.link_ids) > 0:    # pragma: no cover
            LOGGER.warning('Items in field "link_ids" ignored. This field is used for retrieval purposes only.')
    
        now = datetime.datetime.utcnow()
        topology_data = [{
            'context_uuid' : context_uuid,
            'topology_uuid': topology_uuid,
            'topology_name': topology_name,
            'created_at'   : now,
            'updated_at'   : now,
        }]
    
        def callback(session : Session) -> bool:
            stmt = insert(TopologyModel).values(topology_data)
            stmt = stmt.on_conflict_do_update(
                index_elements=[TopologyModel.topology_uuid],
                set_=dict(
                    topology_name = stmt.excluded.topology_name,
                    updated_at    = stmt.excluded.updated_at,
                )
            )
            stmt = stmt.returning(TopologyModel.created_at, TopologyModel.updated_at)
            created_at,updated_at = session.execute(stmt).fetchone()
            return updated_at > created_at
        
        updated = run_transaction(sessionmaker(bind=db_engine), callback)
        return json_topology_id(topology_uuid, context_id=json_context_id(context_uuid)),updated
    
    def topology_delete(db_engine : Engine, request : TopologyId) -> Tuple[Dict, bool]:
        context_uuid,topology_uuid = topology_get_uuid(request, allow_random=False)
        def callback(session : Session) -> bool:
            num_deleted = session.query(TopologyModel).filter_by(topology_uuid=topology_uuid).delete()
            return num_deleted > 0
        deleted = run_transaction(sessionmaker(bind=db_engine), callback)
        return json_topology_id(topology_uuid, context_id=json_context_id(context_uuid)),deleted