Skip to content
Snippets Groups Projects
OpticalConfig.py 5.65 KiB
Newer Older
# 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.

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
import json, logging
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.engine import Engine
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy_cockroachdb import run_transaction
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
from common.proto.context_pb2 import OpticalConfig, OpticalConfigId
from .models.OpticalConfigModel import OpticalConfigModel , OpticalChannelModel
from context.service.database.uuids.OpticalConfig import channel_get_uuid
LOGGER = logging.getLogger(__name__)

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
def get_opticalconfig(db_engine : Engine):
    def callback(session:Session):
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        optical_configs = list()
        results = session.query(OpticalConfigModel).all()
        for obj in results:
            LOGGER.info(f"opticaln config obj from context {obj.dump()}")
     
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
            optical_config = OpticalConfig()
            optical_config.config = json.dumps(obj.dump())
            optical_config.opticalconfig_id.opticalconfig_uuid = obj.dump_id()["opticalconfig_uuid"]
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
            optical_configs.append(optical_config)
        return optical_configs
    obj = run_transaction(sessionmaker(bind=db_engine), callback)
    return obj

Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
def set_opticalconfig(db_engine : Engine, request : OpticalConfig):
    LOGGER.info(f"request {request} ")
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
    opticalconfig_id = OpticalConfigId()
    opticalconfig_id.opticalconfig_uuid = request.opticalconfig_id.opticalconfig_uuid
    OpticalConfig_data = []
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
    if request.config:
        channels = []
        transceivers = []
        config = json.loads(request.config)
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        if 'transceivers' in config and len(config['transceivers']['transceiver']) > 0:
            transceivers = [transceiver for transceiver in config['transceivers']['transceiver']]
            
        if 'channels' in config and len(config['channels']) > 0:
            #channels = [channel['name']['index'] for channel in config['channels']]
            for channel_params in config['channels']:
                 channels.append(
                                {
                                    "channel_uuid":channel_get_uuid(channel_params['name']['index']),
                                    "opticalconfig_uuid": request.opticalconfig_id.opticalconfig_uuid,
                                    "channel_name"          : channel_params['name']['index'],
                                    "frequency"         : int(channel_params["frequency"]) if "frequency" in channel_params  else 0,
                                    "operational_mode"  : int(channel_params["operational-mode"]) if "operational-mode" in channel_params else 0,
                                    "target_output_power"      : channel_params["target-output-power"] if "target-output-power" in channel_params else '',
                                 } 
                             )
                  
        OpticalConfig_data.append(
           {
                                    "opticalconfig_uuid": request.opticalconfig_id.opticalconfig_uuid,
                                    "transcievers"      : transceivers,
                                    "interfaces"        : json.dumps(config["interfaces"]["interface"]),
                                    "channel_namespace" : config["channel_namespace"],
                                    "endpoints"         : [json.dumps(endpoint) for endpoint in config["endpoints"]],}
                                   
        )
            
       
    LOGGER.info(f"optical config to set {OpticalConfig_data} ")
    LOGGER.info(f"channels {channels}")
    def callback(session:Session)->bool:
        stmt = insert(OpticalConfigModel).values(OpticalConfig_data)
        
        stmt = stmt.on_conflict_do_update(
            index_elements=[OpticalConfigModel.opticalconfig_uuid],
            set_=dict(
                channel_namespace=stmt.excluded.channel_namespace
            )
        )
        stmt = stmt.returning(OpticalConfigModel.opticalconfig_uuid)
        opticalconfig_id = session.execute(stmt).fetchone()
        if (len(channels)>0) :
            
                stmt = insert(OpticalChannelModel).values(channels)
        
                stmt = stmt.on_conflict_do_nothing(
                    index_elements=[OpticalChannelModel.channel_uuid , OpticalConfigModel.opticalconfig_uuid],
                    
                )
                stmt = stmt.returning(OpticalChannelModel.channel_uuid)
                opticalChannel_id = session.execute(stmt).fetchone()
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
    opticalconfig_id = run_transaction(sessionmaker(bind=db_engine), callback)
    return {'opticalconfig_uuid': opticalconfig_id}

def select_opticalconfig(db_engine:Engine,request:OpticalConfigId):
    def callback(session : Session) -> OpticalConfig:
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
        result = OpticalConfig()
        stmt = session.query(OpticalConfigModel)
        stmt = stmt.filter_by(opticalconfig_uuid=request.opticalconfig_uuid)
        obj = stmt.first()
        if obj is not None:
            result.config = json.dumps(obj.dump())
            result.opticalconfig_id.opticalconfig_uuid = obj.opticalconfig_uuid
        return result
Lluis Gifre Renom's avatar
Lluis Gifre Renom committed
    return run_transaction(sessionmaker(bind=db_engine, expire_on_commit=False), callback)