Commit f834af4d authored by Lluis Gifre Renom's avatar Lluis Gifre Renom
Browse files

Pre-merge code cleanup

parent eeb87ff2
Loading
Loading
Loading
Loading
+8 −10
Original line number Diff line number Diff line
@@ -13,17 +13,15 @@
# limitations under the License.


from flask import current_app, render_template, Blueprint, flash, session, redirect, url_for
from common.proto.context_pb2 import Empty, OpticalLink, LinkId, OpticalLinkList ,OpticalConfigList
from common.tools.context_queries.EndPoint import get_endpoint_names
from common.tools.context_queries.Link import get_link
from common.tools.context_queries.Topology import get_topology
from context.client.ContextClient import ContextClient
from device.client.DeviceClient import DeviceClient
from flask import render_template, Blueprint
#from common.proto.context_pb2 import Empty, OpticalConfigList
#from context.client.ContextClient import ContextClient
#from device.client.DeviceClient import DeviceClient

base_optical = Blueprint('base_optical', __name__, url_prefix='/base_optical')
device_client = DeviceClient()
context_client = ContextClient()
#device_client = DeviceClient()
#context_client = ContextClient()

@base_optical.get('/')
def home():
    # context_client.connect()
+2 −4
Original line number Diff line number Diff line
@@ -48,9 +48,7 @@ def process_descriptors(descriptors):
    descriptor_loader = DescriptorLoader(descriptors, num_workers=DESCRIPTOR_LOADER_NUM_WORKERS)
    results = descriptor_loader.process()
    for message,level in compose_notifications(results):
        
        if level == 'error': LOGGER.warning('ERROR message={:s}'.format(str(message)))
       
        flash(message, level)

@main.route('/', methods=['GET', 'POST'])
+33 −19
Original line number Diff line number Diff line
# Copyright 2022-2024 ETSI OSG/SDG TeraFlowSDN (TFS) (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.


from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length, NumberRange, ValidationError
from common.proto.context_pb2 import DeviceOperationalStatusEnum
from wtforms import StringField, SelectField, SubmitField

class UpdateDeviceForm(FlaskForm):
   power            = StringField('Power')
   frequency        = StringField("Frequency")
   operational_mode = StringField("Operational Mode")
   line_port        = SelectField("Line Port")
   
                        
   submit           = SubmitField('Update')

class AddTrancseiver(FlaskForm):
   transceiver = StringField("Transceiver")
   submit      = SubmitField('Add')

class UpdateInterfaceForm(FlaskForm):
   ip            = StringField("IP Address")
   prefix_length = StringField("Prefix Length")

DEVICE_STATUS = [
   ('', 'Select...'),
   ('DISABLED', 'DISABLED'),
   ('ENABLED', 'ENABLED')
]

class UpdateStatusForm(FlaskForm):

   status=SelectField("Device Status", choices=[('', 'Select...'), ('DISABLED', 'DISABLED'), ('ENABLED', 'ENABLED')])    
 No newline at end of file
   status = SelectField("Device Status", choices=DEVICE_STATUS)
+103 −150
Original line number Diff line number Diff line
@@ -12,11 +12,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import base64, json, logging #, re
from flask import request, redirect, render_template, Blueprint, flash, session, url_for, current_app ,make_response
from common.proto.context_pb2 import ( Empty
,DeviceId ,OpticalConfig, OpticalConfigId ,OpticalConfigList)

import json, logging
from flask import (
    request, redirect, render_template, Blueprint, flash, session, url_for,
    current_app, make_response
)
from common.proto.context_pb2 import (
    Empty, OpticalConfig, OpticalConfigId, OpticalConfigList
)
from context.client.ContextClient import ContextClient
from device.client.DeviceClient import DeviceClient
from service.client.ServiceClient import ServiceClient
@@ -39,7 +42,6 @@ DESCRIPTOR_LOADER_NUM_WORKERS = 10
@opticalconfig.get("/")
def home() :
    list_config = []
    deviceId= DeviceId()
    channels_num = 0
    if 'context_uuid' not in session or 'topology_uuid' not in session:
        flash("Please select a context!", "warning")
@@ -49,32 +51,20 @@ def home() :
   
    context_client.connect()
    opticalConfig_list : OpticalConfigList = context_client.GetOpticalConfig(Empty())
   

    for configs in opticalConfig_list.opticalconfigs:

        value = json.loads(configs.config) if type(configs.config)==str else configs.config
        config_type = value["type"]
        if ('channels' in value):
           
           
        if 'channels' in value:
            channels_num = len(value['channels']) 
            value["channels_number"] = channels_num
        # value['operationalMode']=value['operational-mode']
        # value['targetOutputPower']=value['target-output-power']
        value['opticalconfig_id']=configs.opticalconfig_id
        # value['line_port']=value["line-port"]
        
        list_config.append(value)

 
   
    context_client.close()

    return render_template(
        'opticalconfig/home.html', config=list_config)
    
    
    return render_template('opticalconfig/home.html', config=list_config)

@opticalconfig.route('<path:config_uuid>/detail',methods=['GET'])    
def show_details(config_uuid):
@@ -86,57 +76,48 @@ def show_details(config_uuid):
    response = context_client.SelectOpticalConfig(opticalconfigId)
    context_client.close()
    if (response and response.opticalconfig_id.opticalconfig_uuid !=''):
           
        opticalConfig = OpticalConfig()
        opticalConfig.CopyFrom(response)
            
        device_name = ""
        config = json.loads(opticalConfig.config)
            if ("device_name" in config):
        if "device_name" in config:
            device_name = config["device_name"]
            config_type = config["type"]

        config_type = config["type"]
        if config_type == 'optical-transponder':
            
            

            if 'channels' in config:
           
                for channel in config['channels'] :
                        new_config={}
                        new_config["name"]=channel['name']
                        new_config['operationalMode']=channel['operational-mode'] if 'operational-mode' in channel else ''
                        new_config['targetOutputPower']=channel['target-output-power'] if 'target-output-power' in channel else ''
                        new_config["frequency"]=channel['frequency'] if 'frequency' in channel else ''
                        new_config['line_port']=channel["line-port"] if 'line-port' in channel else ''
                        new_config["status"] = channel['status'] if 'status' in channel else ""
                    
                    new_config = {
                        "name"             : channel['name'],
                        'operationalMode'  : channel['operational-mode'] if 'operational-mode' in channel else '',
                        'targetOutputPower': channel['target-output-power'] if 'target-output-power' in channel else '',
                        "frequency"        : channel['frequency'] if 'frequency' in channel else '',
                        'line_port'        : channel["line-port"] if 'line-port' in channel else '',
                        "status"           : channel['status'] if 'status' in channel else "",
                    }
                    device_details.append(new_config)

        if config_type == 'optical-roadm':
            
             
            

            if 'channels' in config:
           
                for channel in config['channels'] :
                        new_config={}
                        new_config["band_name"]=channel['band_name'] if 'band_name' in channel else None
                        new_config['type']=channel['type'] if 'type' in channel else ''
                        new_config['src_port']=channel['src_port'] if 'src_port' in channel else ''
                        new_config['dest_port']=channel['dest_port'] if 'dest_port' in channel else ''
                        new_config["lower_frequency"]=channel['lower_frequency'] if 'lower_frequency' in channel else ''
                        new_config["upper_frequency"]=channel['upper_frequency'] if 'upper_frequency' in channel else ''
                        new_config["status"] = channel['status'] if 'status' in channel else ""
                        new_config['optical_band_parent']= channel['optical_band_parent'] if 'optical_band_parent' in channel else ''
                        new_config['channel_index']= channel['channel_index'] if 'channel_index' in channel else ''
                    
                    new_config = {
                        "band_name"           : channel['band_name'] if 'band_name' in channel else None,
                        'type'                : channel['type'] if 'type' in channel else '',
                        'src_port'            : channel['src_port'] if 'src_port' in channel else '',
                        'dest_port'           : channel['dest_port'] if 'dest_port' in channel else '',
                        "lower_frequency"     : channel['lower_frequency'] if 'lower_frequency' in channel else '',
                        "upper_frequency"     : channel['upper_frequency'] if 'upper_frequency' in channel else '',
                        "status"              : channel['status'] if 'status' in channel else "",
                        'optical_band_parent' : channel['optical_band_parent'] if 'optical_band_parent' in channel else '',
                        'channel_index'       : channel['channel_index'] if 'channel_index' in channel else '',
                    }
                    device_details.append(new_config)

        
        return render_template('opticalconfig/details.html', device=device_details,config_id=config_uuid,device_name=device_name,type=config_type)

    return render_template(
        'opticalconfig/details.html', device=device_details, config_id=config_uuid,
        device_name=device_name, type=config_type
    )


@opticalconfig.route('<path:opticalconfig_uuid>/delete', methods=['GET'])
@@ -156,11 +137,8 @@ def delete_opitcalconfig (opticalconfig_uuid) :

@opticalconfig.route('/update_opticalconfig', methods=['POST'])
def update_externally():
   
    if (request.method == 'POST'):
        device_list= []
        data = request.get_json()
  
        devices = data.get('devices')

        myResponse = []
@@ -170,9 +148,7 @@ def update_externally () :
            channel_name = f"channel-{port}"
            device_name = device.get("device_name")
        
        
            if (device_name):
                
            if device_name:
                opticalconfig_uuid = opticalconfig_get_uuid(device_name=device_name)
                opticalconfigId=OpticalConfigId()
                opticalconfigId.opticalconfig_uuid = opticalconfig_uuid
@@ -181,13 +157,11 @@ def update_externally () :
                context_client.close()
            
                if opticalconfig and opticalconfig.opticalconfig_id.opticalconfig_uuid != '' :
                
                    new_opticalconfig = OpticalConfig()
                    new_opticalconfig.CopyFrom(opticalconfig)
                    config = json.loads(opticalconfig.config)
                    channels = config['channels']
                    target_channel = next((item for item in channels if item["name"]['index'] == channel_name) , None)
                   
                    target_power = device.get( "target-output-power")
                    freq = device.get("frequency")
                    mode = device.get("operational-mode")
@@ -195,13 +169,10 @@ def update_externally () :

                    if target_channel:
                        if target_power is not None :
                        
                            target_channel["target-output-power"] =str(target_power)
                        if freq  is not None :
                        
                            target_channel["frequency"] = freq
                        if mode is not None :
                        
                            target_channel["operational-mode"] = mode
                        if status is not None :
                            target_channel["status"] = "ENABLED"
@@ -218,40 +189,28 @@ def update_externally () :

                            myResponse.append(f"device {device_name} port {port} is updated successfully")
                            status_code = 200
                        
                        
                        except Exception as e: # pylint: disable=broad-except
                          
                            myResponse.append(f"Problem updating the device. {e}")
                            status_code = 500 
                            break   
                        
                    else :
                       
                        myResponse.append(f"requested channel {channel_name} is not existed")
                        status_code = 400
                        break         
                    
                else :
                    
                    myResponse.append(f"requested device {device_name} is not existed")
                    status_code = 400
                    break              

       

        response=make_response(f'{myResponse}')
        response.status_code=status_code
        
        return response


        #return redirect(url_for('opticalconfig.show_details',config_uuid=opticalconfig_uuid))
        #return redirect(url_for('opticalconfig.home'))
    
@opticalconfig.route('<path:config_uuid>/<path:channel_name>/update', methods=['GET', 'POST'])
def update(config_uuid, channel_name):
    
    form = UpdateDeviceForm()

    opticalconfigId = OpticalConfigId()
@@ -273,17 +232,14 @@ def update(config_uuid,channel_name):
            form.line_port.choices = [("","")]

    for transceiver in config["transceivers"]['transceiver']:
        
        form.line_port.choices.append((transceiver,transceiver))
    # listing enum values

    # listing enum values
    if form.validate_on_submit():
       
        new_config["target-output-power"] =form.power.data if form.power.data != '' else  new_config['target-output-power']
        new_config["frequency"]=form.frequency.data if form.frequency.data != '' else new_config['frequency']
        new_config["operational-mode"]=form.operational_mode.data if form.operational_mode.data != '' else new_config['operational-mode']
        new_config["line-port"]=form.line_port.data if form.line_port.data != '' else new_config['line-port']

        opticalconfig.config =json.dumps(new_config)

        try:
@@ -307,6 +263,7 @@ def refresh_all ():
    device_client.close()
    return home()


@opticalconfig.route('<path:config_uuid>/add_transceiver', methods=['GET','POST'])
def add_transceiver (config_uuid):
    config={}
@@ -334,10 +291,8 @@ def add_transceiver (config_uuid):
    return render_template('opticalconfig/add_transceiver.html',form=addtrancseiver, submit_text='Add Trancseiver')         



@opticalconfig.route('<path:config_uuid>/<path:channel_name>/update_status', methods=['GET','POST'])
def update_status (config_uuid,channel_name):
    
    config = {}
    form = UpdateStatusForm()

@@ -361,7 +316,6 @@ def update_status (config_uuid,channel_name):
        opticlConfig.config=json.dumps(config)

        try:
      
            device_client.connect()
            device_client.ConfigureOpticalDevice(opticlConfig)
            device_client.close()
@@ -369,8 +323,7 @@ def update_status (config_uuid,channel_name):
            return redirect(url_for('opticalconfig.show_details',config_uuid=config_uuid))
        except Exception as e: # pylint: disable=broad-except
             flash(f'Problem updating the device. {e}', 'danger')  
    return render_template('opticalconfig/update_status.html',form=form , channel_name=channel_name, submit_text='Update Device Status')         
 
        
               
    
 No newline at end of file
    return render_template(
        'opticalconfig/update_status.html', form=form, channel_name=channel_name,
        submit_text='Update Device Status'
    )