Skip to content
Snippets Groups Projects
Commit f834af4d authored by Lluis Gifre Renom's avatar Lluis Gifre Renom
Browse files

Pre-merge code cleanup

parent eeb87ff2
No related branches found
No related tags found
2 merge requests!294Release TeraFlowSDN 4.0,!284Resolve: "(CNIT) Multi-Granular Optical Nodes and Optical Transpoders management"
...@@ -13,17 +13,15 @@ ...@@ -13,17 +13,15 @@
# limitations under the License. # limitations under the License.
from flask import current_app, render_template, Blueprint, flash, session, redirect, url_for from flask import render_template, Blueprint
from common.proto.context_pb2 import Empty, OpticalLink, LinkId, OpticalLinkList ,OpticalConfigList #from common.proto.context_pb2 import Empty, OpticalConfigList
from common.tools.context_queries.EndPoint import get_endpoint_names #from context.client.ContextClient import ContextClient
from common.tools.context_queries.Link import get_link #from device.client.DeviceClient import DeviceClient
from common.tools.context_queries.Topology import get_topology
from context.client.ContextClient import ContextClient
from device.client.DeviceClient import DeviceClient
base_optical = Blueprint('base_optical', __name__, url_prefix='/base_optical') base_optical = Blueprint('base_optical', __name__, url_prefix='/base_optical')
device_client = DeviceClient() #device_client = DeviceClient()
context_client = ContextClient() #context_client = ContextClient()
@base_optical.get('/') @base_optical.get('/')
def home(): def home():
# context_client.connect() # context_client.connect()
...@@ -32,4 +30,4 @@ def home(): ...@@ -32,4 +30,4 @@ def home():
# device_client.connect() # device_client.connect()
# device_client.GetDeviceConfiguration(opticalConfig_list) # device_client.GetDeviceConfiguration(opticalConfig_list)
# device_client.close() # device_client.close()
return render_template("base_optical/home.html") return render_template("base_optical/home.html")
\ No newline at end of file
...@@ -48,9 +48,7 @@ def process_descriptors(descriptors): ...@@ -48,9 +48,7 @@ def process_descriptors(descriptors):
descriptor_loader = DescriptorLoader(descriptors, num_workers=DESCRIPTOR_LOADER_NUM_WORKERS) descriptor_loader = DescriptorLoader(descriptors, num_workers=DESCRIPTOR_LOADER_NUM_WORKERS)
results = descriptor_loader.process() results = descriptor_loader.process()
for message,level in compose_notifications(results): for message,level in compose_notifications(results):
if level == 'error': LOGGER.warning('ERROR message={:s}'.format(str(message))) if level == 'error': LOGGER.warning('ERROR message={:s}'.format(str(message)))
flash(message, level) flash(message, level)
@main.route('/', methods=['GET', 'POST']) @main.route('/', methods=['GET', 'POST'])
...@@ -169,10 +167,10 @@ def topology(): ...@@ -169,10 +167,10 @@ def topology():
'target': link.link_endpoint_ids[1].device_id.device_uuid.uuid, 'target': link.link_endpoint_ids[1].device_id.device_uuid.uuid,
}) })
return jsonify({'devices': devices, 'links': links ,'optical_links':optical_links}) return jsonify({'devices': devices, 'links': links, 'optical_links': optical_links})
except: # pylint: disable=bare-except except: # pylint: disable=bare-except
LOGGER.exception('Error retrieving topology') LOGGER.exception('Error retrieving topology')
return jsonify({'devices': [], 'links': [],'optical_links':[]}) return jsonify({'devices': [], 'links': [], 'optical_links': []})
finally: finally:
context_client.close() context_client.close()
......
# 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 flask_wtf import FlaskForm
from wtforms import StringField, SelectField, TextAreaField, SubmitField from wtforms import StringField, SelectField, SubmitField
from wtforms.validators import DataRequired, Length, NumberRange, ValidationError
from common.proto.context_pb2 import DeviceOperationalStatusEnum
class UpdateDeviceForm(FlaskForm): class UpdateDeviceForm(FlaskForm):
power = StringField('Power') power = StringField('Power')
frequency= StringField("Frequency") frequency = StringField("Frequency")
operational_mode=StringField("Operational Mode") operational_mode = StringField("Operational Mode")
line_port=SelectField("Line Port") line_port = SelectField("Line Port")
submit = SubmitField('Update')
submit = SubmitField('Update')
class AddTrancseiver (FlaskForm): class AddTrancseiver(FlaskForm):
transceiver = StringField("Transceiver") transceiver = StringField("Transceiver")
submit = SubmitField('Add') submit = SubmitField('Add')
class UpdateInterfaceForm (FlaskForm):
ip=StringField("IP Address")
prefix_length=StringField("Prefix Length")
class UpdateStatusForm (FlaskForm): class UpdateInterfaceForm(FlaskForm):
ip = StringField("IP Address")
prefix_length = StringField("Prefix Length")
status=SelectField("Device Status", choices=[('', 'Select...'), ('DISABLED', 'DISABLED'), ('ENABLED', 'ENABLED')]) DEVICE_STATUS = [
\ No newline at end of file ('', 'Select...'),
('DISABLED', 'DISABLED'),
('ENABLED', 'ENABLED')
]
class UpdateStatusForm(FlaskForm):
status = SelectField("Device Status", choices=DEVICE_STATUS)
...@@ -12,11 +12,14 @@ ...@@ -12,11 +12,14 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import base64, json, logging #, re import json, logging
from flask import request, redirect, render_template, Blueprint, flash, session, url_for, current_app ,make_response from flask import (
from common.proto.context_pb2 import ( Empty request, redirect, render_template, Blueprint, flash, session, url_for,
,DeviceId ,OpticalConfig, OpticalConfigId ,OpticalConfigList) current_app, make_response
)
from common.proto.context_pb2 import (
Empty, OpticalConfig, OpticalConfigId, OpticalConfigList
)
from context.client.ContextClient import ContextClient from context.client.ContextClient import ContextClient
from device.client.DeviceClient import DeviceClient from device.client.DeviceClient import DeviceClient
from service.client.ServiceClient import ServiceClient from service.client.ServiceClient import ServiceClient
...@@ -38,8 +41,7 @@ DESCRIPTOR_LOADER_NUM_WORKERS = 10 ...@@ -38,8 +41,7 @@ DESCRIPTOR_LOADER_NUM_WORKERS = 10
@opticalconfig.get("/") @opticalconfig.get("/")
def home() : def home() :
list_config=[] list_config = []
deviceId= DeviceId()
channels_num = 0 channels_num = 0
if 'context_uuid' not in session or 'topology_uuid' not in session: if 'context_uuid' not in session or 'topology_uuid' not in session:
flash("Please select a context!", "warning") flash("Please select a context!", "warning")
...@@ -48,165 +50,134 @@ def home() : ...@@ -48,165 +50,134 @@ def home() :
topology_uuid = session['topology_uuid'] topology_uuid = session['topology_uuid']
context_client.connect() context_client.connect()
opticalConfig_list:OpticalConfigList = context_client.GetOpticalConfig(Empty()) opticalConfig_list : OpticalConfigList = context_client.GetOpticalConfig(Empty())
for configs in opticalConfig_list.opticalconfigs: for configs in opticalConfig_list.opticalconfigs:
value = json.loads(configs.config) if type(configs.config)==str else configs.config
value=json.loads(configs.config) if type(configs.config)==str else configs.config
config_type = value["type"] config_type = value["type"]
if ('channels' in value): if 'channels' in value:
channels_num = len(value['channels'])
value["channels_number"] = channels_num
channels_num=len(value['channels'])
value["channels_number"]=channels_num
# value['operationalMode']=value['operational-mode'] # value['operationalMode']=value['operational-mode']
# value['targetOutputPower']=value['target-output-power'] # value['targetOutputPower']=value['target-output-power']
value['opticalconfig_id']=configs.opticalconfig_id value['opticalconfig_id']=configs.opticalconfig_id
# value['line_port']=value["line-port"] # value['line_port']=value["line-port"]
list_config.append(value) list_config.append(value)
context_client.close() 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']) @opticalconfig.route('<path:config_uuid>/detail',methods=['GET'])
def show_details(config_uuid): def show_details(config_uuid):
opticalconfigId=OpticalConfigId() opticalconfigId = OpticalConfigId()
opticalconfigId.opticalconfig_uuid=config_uuid opticalconfigId.opticalconfig_uuid = config_uuid
device_details=[] device_details = []
context_client.connect() context_client.connect()
response = context_client.SelectOpticalConfig(opticalconfigId) response = context_client.SelectOpticalConfig(opticalconfigId)
context_client.close() context_client.close()
if (response and response.opticalconfig_id.opticalconfig_uuid !=''): if (response and response.opticalconfig_id.opticalconfig_uuid !=''):
opticalConfig = OpticalConfig()
opticalConfig = OpticalConfig() opticalConfig.CopyFrom(response)
opticalConfig.CopyFrom(response)
device_name=""
config =json.loads(opticalConfig.config)
if ("device_name" in config):
device_name= config["device_name"]
config_type = config["type"]
if config_type == 'optical-transponder':
device_name = ""
config = json.loads(opticalConfig.config)
if "device_name" in config:
device_name = config["device_name"]
if 'channels' in config: config_type = config["type"]
if config_type == 'optical-transponder':
for channel in config['channels'] : if 'channels' in config:
new_config={} for channel in config['channels'] :
new_config["name"]=channel['name'] new_config = {
new_config['operationalMode']=channel['operational-mode'] if 'operational-mode' in channel else '' "name" : channel['name'],
new_config['targetOutputPower']=channel['target-output-power'] if 'target-output-power' in channel else '' 'operationalMode' : channel['operational-mode'] if 'operational-mode' in channel else '',
new_config["frequency"]=channel['frequency'] if 'frequency' in channel else '' 'targetOutputPower': channel['target-output-power'] if 'target-output-power' in channel else '',
new_config['line_port']=channel["line-port"] if 'line-port' in channel else '' "frequency" : channel['frequency'] if 'frequency' in channel else '',
new_config["status"] = channel['status'] if 'status' 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) }
device_details.append(new_config)
if config_type == 'optical-roadm':
if 'channels' in config: if config_type == 'optical-roadm':
if 'channels' in config:
for channel in config['channels'] : for channel in config['channels'] :
new_config={} new_config = {
new_config["band_name"]=channel['band_name'] if 'band_name' in channel else None "band_name" : channel['band_name'] if 'band_name' in channel else None,
new_config['type']=channel['type'] if 'type' in channel else '' 'type' : channel['type'] if 'type' in channel else '',
new_config['src_port']=channel['src_port'] if 'src_port' in channel else '' 'src_port' : channel['src_port'] if 'src_port' in channel else '',
new_config['dest_port']=channel['dest_port'] if 'dest_port' in channel else '' 'dest_port' : channel['dest_port'] if 'dest_port' in channel else '',
new_config["lower_frequency"]=channel['lower_frequency'] if 'lower_frequency' in channel else '' "lower_frequency" : channel['lower_frequency'] if 'lower_frequency' in channel else '',
new_config["upper_frequency"]=channel['upper_frequency'] if 'upper_frequency' in channel else '' "upper_frequency" : channel['upper_frequency'] if 'upper_frequency' in channel else '',
new_config["status"] = channel['status'] if 'status' in channel else "" "status" : channel['status'] if 'status' in channel else "",
new_config['optical_band_parent']= channel['optical_band_parent'] if 'optical_band_parent' in channel else '' '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 '' 'channel_index' : channel['channel_index'] if 'channel_index' in channel else '',
}
device_details.append(new_config) 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']) @opticalconfig.route('<path:opticalconfig_uuid>/delete', methods=['GET'])
def delete_opitcalconfig (opticalconfig_uuid) : def delete_opitcalconfig (opticalconfig_uuid) :
try : try :
opticalconfigId=OpticalConfigId() opticalconfigId = OpticalConfigId()
opticalconfigId.opticalconfig_uuid=opticalconfig_uuid opticalconfigId.opticalconfig_uuid = opticalconfig_uuid
context_client.connect() context_client.connect()
context_client.DeleteOpticalConfig(opticalconfigId) context_client.DeleteOpticalConfig(opticalconfigId)
context_client.close() context_client.close()
flash(f'OpticalConfig "{opticalconfig_uuid}" deleted successfully!', 'success') flash(f'OpticalConfig "{opticalconfig_uuid}" deleted successfully!', 'success')
except Exception as e: # pylint: disable=broad-except except Exception as e: # pylint: disable=broad-except
flash(f'Problem deleting optical config {opticalconfig_uuid}', 'danger') flash(f'Problem deleting optical config {opticalconfig_uuid}', 'danger')
current_app.logger.exception(e) current_app.logger.exception(e)
return redirect(url_for('opticalconfig.home')) return redirect(url_for('opticalconfig.home'))
@opticalconfig.route('/update_opticalconfig', methods=['POST']) @opticalconfig.route('/update_opticalconfig', methods=['POST'])
def update_externally () : def update_externally():
if (request.method == 'POST'): if (request.method == 'POST'):
device_list= []
data = request.get_json() data = request.get_json()
devices = data.get('devices')
devices=data.get('devices')
myResponse =[] myResponse = []
status_code='' status_code = ''
for device in devices : for device in devices :
port = device.get("port") port = device.get("port")
channel_name= f"channel-{port}" channel_name = f"channel-{port}"
device_name=device.get("device_name") device_name = device.get("device_name")
if (device_name): if device_name:
opticalconfig_uuid = opticalconfig_get_uuid(device_name=device_name) opticalconfig_uuid = opticalconfig_get_uuid(device_name=device_name)
opticalconfigId=OpticalConfigId() opticalconfigId=OpticalConfigId()
opticalconfigId.opticalconfig_uuid=opticalconfig_uuid opticalconfigId.opticalconfig_uuid = opticalconfig_uuid
context_client.connect() context_client.connect()
opticalconfig = context_client.SelectOpticalConfig(opticalconfigId) opticalconfig = context_client.SelectOpticalConfig(opticalconfigId)
context_client.close() context_client.close()
if opticalconfig and opticalconfig.opticalconfig_id.opticalconfig_uuid != '' : if opticalconfig and opticalconfig.opticalconfig_id.opticalconfig_uuid != '' :
new_opticalconfig = OpticalConfig() new_opticalconfig = OpticalConfig()
new_opticalconfig.CopyFrom(opticalconfig) new_opticalconfig.CopyFrom(opticalconfig)
config =json.loads(opticalconfig.config) config = json.loads(opticalconfig.config)
channels= config['channels'] channels = config['channels']
target_channel =next((item for item in channels if item["name"]['index'] == channel_name) , None) target_channel = next((item for item in channels if item["name"]['index'] == channel_name) , None)
target_power = device.get( "target-output-power")
target_power=device.get( "target-output-power")
freq = device.get("frequency") freq = device.get("frequency")
mode = device.get("operational-mode") mode = device.get("operational-mode")
status= device.get("status","ENABLED") status = device.get("status","ENABLED")
if target_channel: if target_channel:
if target_power is not None : if target_power is not None :
target_channel["target-output-power"] =str(target_power) target_channel["target-output-power"] =str(target_power)
if freq is not None : if freq is not None :
target_channel["frequency"] = freq
target_channel["frequency"] =freq
if mode is not None : if mode is not None :
target_channel["operational-mode"] = mode
target_channel["operational-mode"] =mode
if status is not None : if status is not None :
target_channel["status"]="ENABLED" target_channel["status"] = "ENABLED"
#del target_channel['name'] #del target_channel['name']
config["new_config"]=target_channel config["new_config"]=target_channel
config["new_config"]["channel_name"]=channel_name config["new_config"]["channel_name"]=channel_name
config["flow"]=[(port,'0')] config["flow"]=[(port,'0')]
opticalconfig.config =json.dumps(config) opticalconfig.config =json.dumps(config)
...@@ -215,47 +186,35 @@ def update_externally () : ...@@ -215,47 +186,35 @@ def update_externally () :
device_client.connect() device_client.connect()
device_client.ConfigureOpticalDevice(opticalconfig) device_client.ConfigureOpticalDevice(opticalconfig)
device_client.close() device_client.close()
myResponse.append(f"device {device_name} port {port} is updated successfully") myResponse.append(f"device {device_name} port {port} is updated successfully")
status_code = 200 status_code = 200
except Exception as e: # pylint: disable=broad-except except Exception as e: # pylint: disable=broad-except
myResponse.append(f"Problem updating the device. {e}") myResponse.append(f"Problem updating the device. {e}")
status_code = 500 status_code = 500
break break
else : else :
myResponse.append(f"requested channel {channel_name} is not existed") myResponse.append(f"requested channel {channel_name} is not existed")
status_code = 400 status_code = 400
break break
else : else :
myResponse.append(f"requested device {device_name} is not existed") myResponse.append(f"requested device {device_name} is not existed")
status_code = 400 status_code = 400
break break
response=make_response(f'{myResponse}') response=make_response(f'{myResponse}')
response.status_code=status_code response.status_code=status_code
return response return response
#return redirect(url_for('opticalconfig.show_details',config_uuid=opticalconfig_uuid)) #return redirect(url_for('opticalconfig.show_details',config_uuid=opticalconfig_uuid))
#return redirect(url_for('opticalconfig.home')) #return redirect(url_for('opticalconfig.home'))
@opticalconfig.route('<path:config_uuid>/<path:channel_name>/update', methods=['GET', 'POST']) @opticalconfig.route('<path:config_uuid>/<path:channel_name>/update', methods=['GET', 'POST'])
def update(config_uuid,channel_name): def update(config_uuid, channel_name):
form = UpdateDeviceForm() form = UpdateDeviceForm()
opticalconfigId=OpticalConfigId() opticalconfigId = OpticalConfigId()
opticalconfigId.opticalconfig_uuid=config_uuid opticalconfigId.opticalconfig_uuid = config_uuid
context_client.connect() context_client.connect()
response = context_client.SelectOpticalConfig(opticalconfigId) response = context_client.SelectOpticalConfig(opticalconfigId)
context_client.close() context_client.close()
...@@ -271,21 +230,18 @@ def update(config_uuid,channel_name): ...@@ -271,21 +230,18 @@ def update(config_uuid,channel_name):
form.operational_mode.default=channel["operational-mode"] form.operational_mode.default=channel["operational-mode"]
form.power.default=channel["target-output-power"] form.power.default=channel["target-output-power"]
form.line_port.choices = [("","")] form.line_port.choices = [("","")]
for transceiver in config["transceivers"]['transceiver']: for transceiver in config["transceivers"]['transceiver']:
form.line_port.choices.append((transceiver,transceiver)) form.line_port.choices.append((transceiver,transceiver))
# listing enum values
# listing enum values
if form.validate_on_submit(): 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["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["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["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'] new_config["line-port"]=form.line_port.data if form.line_port.data != '' else new_config['line-port']
opticalconfig.config =json.dumps(new_config) opticalconfig.config =json.dumps(new_config)
try: try:
device_client.connect() device_client.connect()
device_client.ConfigureOpticalDevice(opticalconfig) device_client.ConfigureOpticalDevice(opticalconfig)
...@@ -306,7 +262,8 @@ def refresh_all (): ...@@ -306,7 +262,8 @@ def refresh_all ():
device_client.GetDeviceConfiguration(opticalConfig_list) device_client.GetDeviceConfiguration(opticalConfig_list)
device_client.close() device_client.close()
return home() return home()
@opticalconfig.route('<path:config_uuid>/add_transceiver', methods=['GET','POST']) @opticalconfig.route('<path:config_uuid>/add_transceiver', methods=['GET','POST'])
def add_transceiver (config_uuid): def add_transceiver (config_uuid):
config={} config={}
...@@ -332,14 +289,12 @@ def add_transceiver (config_uuid): ...@@ -332,14 +289,12 @@ def add_transceiver (config_uuid):
except Exception as e: # pylint: disable=broad-except except Exception as e: # pylint: disable=broad-except
flash(f'Problem updating the device. {e}', 'danger') flash(f'Problem updating the device. {e}', 'danger')
return render_template('opticalconfig/add_transceiver.html',form=addtrancseiver, submit_text='Add Trancseiver') 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']) @opticalconfig.route('<path:config_uuid>/<path:channel_name>/update_status', methods=['GET','POST'])
def update_status (config_uuid,channel_name): def update_status (config_uuid,channel_name):
config = {}
config={} form = UpdateStatusForm()
form=UpdateStatusForm()
opticalconfigId=OpticalConfigId() opticalconfigId=OpticalConfigId()
opticalconfigId.opticalconfig_uuid=config_uuid opticalconfigId.opticalconfig_uuid=config_uuid
...@@ -359,9 +314,8 @@ def update_status (config_uuid,channel_name): ...@@ -359,9 +314,8 @@ def update_status (config_uuid,channel_name):
config["flow"]=[(port,'0')] config["flow"]=[(port,'0')]
config["new_config"]=new_config config["new_config"]=new_config
opticlConfig.config=json.dumps(config) opticlConfig.config=json.dumps(config)
try: try:
device_client.connect() device_client.connect()
device_client.ConfigureOpticalDevice(opticlConfig) device_client.ConfigureOpticalDevice(opticlConfig)
device_client.close() device_client.close()
...@@ -369,8 +323,7 @@ def update_status (config_uuid,channel_name): ...@@ -369,8 +323,7 @@ def update_status (config_uuid,channel_name):
return redirect(url_for('opticalconfig.show_details',config_uuid=config_uuid)) return redirect(url_for('opticalconfig.show_details',config_uuid=config_uuid))
except Exception as e: # pylint: disable=broad-except except Exception as e: # pylint: disable=broad-except
flash(f'Problem updating the device. {e}', 'danger') 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') return render_template(
'opticalconfig/update_status.html', form=form, channel_name=channel_name,
submit_text='Update Device Status'
)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment