Commit 832b180a authored by Lluis Gifre Renom's avatar Lluis Gifre Renom
Browse files

Optical Controller component:

- Fix logging framework
- Minor code fixes
- Factorized RSA:init_graph() method
parent e9863e69
Loading
Loading
Loading
Loading
+22 −11
Original line number Diff line number Diff line
@@ -30,6 +30,15 @@ global links_dict
rsa = None


logging.basicConfig(level=logging.DEBUG)

LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)

def print(*args) -> None:
    LOGGER.info(' '.join([str(a) for a in args]))


app = Flask(__name__)
api = Api(app, version='1.0', title='Optical controller API',
          description='Rest API to configure OC Optical devices in TFS')
@@ -329,7 +338,8 @@ class GetFlows(Resource):
                print(rsa.db_flows)
            return rsa.db_flows, 200
        except:
            return "Error", 404
            LOGGER.exception('Error while getting lightpaths')
            return 'Error', 404

@optical.route('/GetOpticalBands')
@optical.response(200, 'Success')
@@ -342,7 +352,8 @@ class GetBands(Resource):
                print(rsa.optical_bands)
            return rsa.optical_bands, 200
        except:
            return "Error", 404
            LOGGER.exception('Error while getting optical bands')
            return 'Error', 404


@optical.route('/GetOpticalBand/<int:ob_id>')
@@ -397,7 +408,8 @@ class GetFlows(Resource):
                print(links)
            return links, 200
        except:
            return "Error", 404
            LOGGER.exception('Error while getting links')
            return 'Error', 404
        
                
@optical.route('/GetTopology/<path:context_id>/<path:topology_id>',methods=['GET'])
@@ -481,12 +493,11 @@ class GetTopology(Resource):
            if debug:
                print(f'rsa.init_link_slots2() {rsa}')
                print(rsa.init_link_slots2())
        
        
            return  "ok" ,200
        except Exception as e:
            print(f"err {e}")
            return "Error", 400
            return 'OK', 200
        except Exception:
            LOGGER.exception('Error while processing topology data')
            #print(f'err {e}')
            return 'Error', 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=10060, debug=True)
+58 −41
Original line number Diff line number Diff line
@@ -13,12 +13,12 @@
# limitations under the License.

import logging
from typing import Dict, Tuple
from opticalcontroller.dijkstra import *
from opticalcontroller.tools import *
from opticalcontroller.variables import *


logging.basicConfig(level=logging.DEBUG)
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)

@@ -31,11 +31,13 @@ class RSA():
        self.nodes_dict = nodes
        self.links_dict = links
        self.g = None
        self.node_key__to__node_name : Dict[str, Dict] = dict()
        self.link_key__to__src_dst_node_names : Dict[str, Tuple[str, str]] = dict()

        self.flow_id = 0
        self.opt_band_id = 0
        self.db_flows = {}
        self.initGraph2()
        self.init_graph()
        self.c_slot_number = 0
        self.l_slot_number = 0
        self.s_slot_number = 0
@@ -97,45 +99,52 @@ class RSA():
                break
        return "{},{},{}".format(self.c_slot_number, self.l_slot_number, self.s_slot_number)

    def initGraph(self):
    def init_graph(self):
        self.node_key__to__node_name.clear()
        self.link_key__to__src_dst_node_names.clear()
        self.g = Graph()
        for n in self.nodes_dict:
            self.g.add_vertex(n)
        for l in self.links_dict["optical_links"]:
            #if debug:
            #    print(l)
            [s, d] = l["optical_link"]["name"].split('-')
            ps = l["optical_link"]["details"]["source"]
            pd = l["optical_link"]["details"]["target"]
            self.g.add_edge(s, d, ps, pd, 1)

        print("INFO: Graph initiated.")
        if debug:
            self.g.printGraph()
        for node_name, node_data in self.nodes_dict.items():
            MSG = '[RSA:init_graph] processing node: name={:s}, data={:s}'
            LOGGER.debug(MSG.format(str(node_name), str(node_data)))

    def initGraph2(self):
            node_id = node_data['id']
            self.node_key__to__node_name[node_id] = node_name
            self.node_key__to__node_name[node_name] = node_name
            self.g.add_vertex(node_name)

        self.g = Graph()
        for link in self.links_dict['optical_links']:
            MSG = '[RSA:init_graph] processing link: {:s}'
            LOGGER.debug(MSG.format(str(link)))

        for n in self.nodes_dict:
            self.g.add_vertex(n)
        for l in self.links_dict["optical_links"]:
            #if debug:
            #    print(l)
            [s, d] = l["name"].split('-')
            ps = l["optical_details"]["src_port"]
            pd = l["optical_details"]["dst_port"]
            self.g.add_edge(s, d, ps, pd, 1)
            src_ep_id = link['link_endpoint_ids'][ 0]
            src_node_uuid = src_ep_id['device_id']['device_uuid']['uuid']
            src_node_name = self.node_key__to__node_name[src_node_uuid]

        print("INFO: Graph initiated.2")
        if debug:
            dst_ep_id = link['link_endpoint_ids'][-1]
            dst_node_uuid = dst_ep_id['device_id']['device_uuid']['uuid']
            dst_node_name = self.node_key__to__node_name[dst_node_uuid]

            src_port = link['optical_details']['src_port']
            dst_port = link['optical_details']['dst_port']

            link_name = '{:s}-{:s}'.format(src_node_name, dst_node_name)
            self.link_key__to__src_dst_node_names[link_name] = (src_node_name, dst_node_name)

            self.g.add_edge(src_node_name, dst_node_name, src_port, dst_port, 1)

        LOGGER.info('[RSA:init_graph] Graph initiated')
        self.g.printGraph()

    def compute_path(self, src, dst):
        path = shortest_path(self.g, self.g.get_vertex(src), self.g.get_vertex(dst))
        print("INFO: Path from {} to {} with distance: {}".format(src, dst, self.g.get_vertex(dst).get_distance()))
        if debug:
            print(f"compute_path shortest_path {path}")

        MSG = '[RSA:compute_path] Path from {:s} to {:s} with distance {:f}'
        LOGGER.info(MSG.format(src, dst, float(self.g.get_vertex(dst).get_distance())))

        MSG = '[RSA:compute_path]   Path: {:s}'
        LOGGER.debug(MSG.format(str(path)))

        links = []
        for i in range(0, len(path) - 1):
            s = path[i]
@@ -155,10 +164,18 @@ class RSA():
    def compute_disjoint_path(self, src, dst, path1=None):
        if path1 is None:
            path1 = shortest_path(self.g, self.g.get_vertex(src), self.g.get_vertex(dst))

        MSG = '[RSA:compute_disjoint_path] Path1: {:s}'
        LOGGER.info(MSG.format(str(path1)))

        path = disjoint_path(self.g, src, dst, path1, False)
        print("INFO: Path from {} to {} with distance: {}".format(src, dst, self.g.get_vertex(dst).get_distance()))
        if debug:
            print(path)

        MSG = '[RSA:compute_disjoint_path] Path from {:s} to {:s} with distance {:f}'
        LOGGER.info(MSG.format(src, dst, float(self.g.get_vertex(dst).get_distance())))

        MSG = '[RSA:compute_disjoint_path]   Path: {:s}'
        LOGGER.debug(MSG.format(str(path)))

        links = []
        for i in range(0, len(path) - 1):
            s = path[i]
@@ -195,13 +212,13 @@ class RSA():
        s_slots = {}
        add = ""
        drop = ""
        src_1, dst_1 = links[0].split('-')
        src_2, dst_2 = links[-1].split('-')
        src_1, dst_1 = self.link_key__to__src_dst_node_names[links[ 0]]
        src_2, dst_2 = self.link_key__to__src_dst_node_names[links[-1]]
        if self.nodes_dict[src_1]["type"] == "OC-TP":
            add = links[0]
        if self.nodes_dict[dst_2]["type"] == "OC-TP":
            drop = links[-1]
        found = 0

        for l in links:
            c_slots[l] = []
            l_slots[l] = []
+13 −2
Original line number Diff line number Diff line
@@ -16,7 +16,9 @@
# https://networkx.org/documentation/stable/index.html
# https://networkx.org/documentation/stable/reference/algorithms/shortest_paths.html

import sys
import logging

LOGGER = logging.getLogger(__name__)

class Vertex:
    def __init__(self, node):
@@ -99,11 +101,20 @@ class Graph:
            self.get_vertex(n).reset_vertex()

    def printGraph(self):
        MSG = ', '.join([
            'src_node={:s}', 'dst_node={:s}',
            'src_port={:s}', 'dst_port={:s}',
            'weight_src_to_dst={:d}', 'weight_dst_to_src={:d}'
        ])

        for v in self:
            for w in v.get_connections():
                vid = v.get_id()
                wid = w.get_id()
                print ('( %s , %s, %s, %s, %s, %s)'  % ( vid, wid, v.get_port(w), w.get_port(v), v.get_weight(w), w.get_weight(v)))
                LOGGER.debug(MSG.format(
                    vid, wid, v.get_port(w), w.get_port(v),
                    v.get_weight(w), w.get_weight(v)
                ))

    def add_vertex(self, node):
        self.num_vertices = self.num_vertices + 1