Fixed bug that generated an error when adding a sdn-controller without user or passwo...
[osm/openvim.git] / ovim.py
diff --git a/ovim.py b/ovim.py
old mode 100644 (file)
new mode 100755 (executable)
index 6e8f8da..a1eaffa
--- a/ovim.py
+++ b/ovim.py
@@ -1,3 +1,4 @@
+#!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
 ##
@@ -28,17 +29,21 @@ Two thread will be launched, with normal and administrative permissions.
 
 __author__ = "Alfonso Tierno, Leonardo Mirabal"
 __date__ = "$06-Feb-2017 12:07:15$"
+__version__ = "0.5.10-r526"
+version_date = "Apr 2017"
+database_version = "0.17"      #expected database schema version
 
 import threading
 import vim_db
 import logging
-import threading
 import imp
 import host_thread as ht
 import dhcp_thread as dt
 import openflow_thread as oft
 from netaddr import IPNetwork
 from jsonschema import validate as js_v, exceptions as js_e
+import openflow_conn
+import argparse
 
 HTTP_Bad_Request =          400
 HTTP_Unauthorized =         401
@@ -90,16 +95,17 @@ class ovim():
 
     def __init__(self, configuration):
         self.config = configuration
-        self.logger = logging.getLogger(configuration["logger_name"])
+        self.logger_name = configuration.get("logger_name", "openvim")
+        self.logger = logging.getLogger(self.logger_name)
         self.db = None
-        self.db =   self._create_database_connection()
+        self.db = self._create_database_connection()
         self.db_lock = None
         self.db_of = None
         self.of_test_mode = False
 
     def _create_database_connection(self):
         db = vim_db.vim_db((self.config["network_vlan_range_start"], self.config["network_vlan_range_end"]),
-                           self.config['log_level_db']);
+                           self.logger_name + ".db", self.config.get('log_level_db'))
         if db.connect(self.config['db_host'], self.config['db_user'], self.config['db_passwd'],
                       self.config['db_name']) == -1:
             # self.logger.error("Cannot connect to database %s at %s@%s", self.config['db_name'], self.config['db_user'],
@@ -109,6 +115,18 @@ class ovim():
                                                                                 self.config['db_host']) )
         return db
 
+    @staticmethod
+    def get_version():
+        return __version__
+
+    @staticmethod
+    def get_version_date():
+        return version_date
+
+    @staticmethod
+    def get_database_version():
+        return database_version
+
     @staticmethod
     def _check_dhcp_data_integrity(network):
         """
@@ -149,16 +167,18 @@ class ovim():
         Start ovim services
         :return:
         """
+        global database_version
         # if self.running_info:
         #    return  #TODO service can be checked and rebuild broken threads
         r = self.db.get_db_version()
         if r[0] < 0:
             raise ovimException("DATABASE is not a VIM one or it is a '0.0' version. Try to upgrade to version '{}' with "\
-                                "'./database_utils/migrate_vim_db.sh'".format(self.config["database_version"]) )
-        elif r[1] != self.config["database_version"]:
+                                "'./database_utils/migrate_vim_db.sh'".format(database_version) )
+        elif r[1] != database_version:
             raise ovimException("DATABASE wrong version '{}'. Try to upgrade/downgrade to version '{}' with "\
-                                "'./database_utils/migrate_vim_db.sh'".format(r[1], self.config["database_version"]) )
-
+                                "'./database_utils/migrate_vim_db.sh'".format(r[1], database_version) )
+        self.logger.critical("Starting ovim server version: '{} {}' database version '{}'".format(
+            self.get_version(), self.get_version_date(), self.get_database_version()))
         # create database connection for openflow threads
         self.db_of = self._create_database_connection()
         self.config["db"] = self.db_of
@@ -326,8 +346,9 @@ class ovim():
 
         try:
             if self.of_test_mode:
-                return oft.of_test_connector({"name": db_config['type'], "dpid": db_config['dpid'],
-                                              "of_debug": self.config['log_level_of']})
+                return openflow_conn.OfTestConnector({"name": db_config['type'],
+                                                      "dpid": db_config['dpid'],
+                                                      "of_debug": self.config['log_level_of']})
             temp_dict = {}
 
             if db_config:
@@ -335,6 +356,8 @@ class ovim():
                 temp_dict['of_port'] = db_config['port']
                 temp_dict['of_dpid'] = db_config['dpid']
                 temp_dict['of_controller'] = db_config['type']
+                temp_dict['of_user'] = db_config.get('user')
+                temp_dict['of_password'] = db_config.get('password')
 
             temp_dict['of_debug'] = self.config['log_level_of']
 
@@ -374,10 +397,11 @@ class ovim():
         """
         # create openflow thread
 
-        if 'of_controller_nets_with_same_vlan' in self.config:
-            ofc_net_same_vlan = self.config['of_controller_nets_with_same_vlan']
-        else:
-            ofc_net_same_vlan = False
+        #if 'of_controller_nets_with_same_vlan' in self.config:
+        #    ofc_net_same_vlan = self.config['of_controller_nets_with_same_vlan']
+        #else:
+        #    ofc_net_same_vlan = False
+        ofc_net_same_vlan = False
 
         thread = oft.openflow_thread(ofc_uuid, of_conn, of_test=self.of_test_mode, db=self.db_of, db_lock=self.db_lock,
                                      pmp_with_same_vlan=ofc_net_same_vlan, debug=self.config['log_level_of'])
@@ -663,7 +687,8 @@ class ovim():
             if result > 0:
 
                 try:
-                    self.net_update_ofc_thread(network_id)
+                    if nbports:
+                        self.net_update_ofc_thread(network_id)
                 except ovimException as e:
                     raise ovimException("Error while launching openflow rules in network '{}' {}"
                                         .format(network_id, str(e)), HTTP_Internal_Server_Error)
@@ -884,9 +909,12 @@ class ovim():
         port_data['switch_mac'] = port_mapping_data[0]['switch_mac']
 
         # remove from compute_node, region and pci of_port_data to adapt to 'ports' structure
-        del port_data['compute_node']
-        del port_data['region']
-        del port_data['pci']
+        if 'region' in port_data:
+            del port_data['region']
+        if 'pci' in port_data:
+            del port_data['pci']
+        if 'compute_node' in port_data:
+            del port_data['compute_node']
 
         result, uuid = self.db.new_row('ports', port_data, True, True)
         if result > 0:
@@ -902,17 +930,17 @@ class ovim():
         else:
             raise ovimException(str(uuid), -result)
 
-    def net_update_ofc_thread(self, net_id, ofc_id=None):
+    def net_update_ofc_thread(self, net_id, ofc_id=None, switch_dpid=None):
         """
         Insert a update net task by net id or ofc_id for each ofc thread
         :param net_id: network id
         :param ofc_id: openflow controller id
+        :param switch_dpid: switch dpid
         :return:
         """
         if not net_id:
             raise ovimException("No net_id received", HTTP_Internal_Server_Error)
 
-        switch_dpid = None
         r = -1
         c = 'No valid ofc_id or switch_dpid received'
 
@@ -924,6 +952,8 @@ class ovim():
                     ofc_id = port['ofc_id']
                     switch_dpid = port['switch_dpid']
                     break
+        #TODO if not ofc_id: look at database table ofcs
+
 
         # If no ofc_id found it, default ofc_id is used.
         if not ofc_id and not switch_dpid:
@@ -960,7 +990,7 @@ class ovim():
             # change of net.
 
             try:
-                self.net_update_ofc_thread(network)
+                self.net_update_ofc_thread(network, ofc_id=ports[0]["ofc_id"], switch_dpid=ports[0]["switch_dpid"])
             except ovimException as e:
                 raise ovimException("Cannot insert a task for delete network '{}' {}".format(network, str(e)),
                                     HTTP_Internal_Server_Error)
@@ -1014,12 +1044,13 @@ class ovim():
         # insert in data base
         if result >= 0:
             result, content = self.db.update_rows('ports', port_data, WHERE={'uuid': port_id}, log=False)
+            port.update(port_data)
 
         # Insert task to complete actions
         if result > 0:
             for net_id in nets:
                 try:
-                    self.net_update_ofc_thread(net_id)
+                    self.net_update_ofc_thread(net_id, port["ofc_id"], switch_dpid=port["switch_dpid"])
                 except ovimException as e:
                     raise ovimException("Error updating network'{}' {}".format(net_id, str(e)),
                                         HTTP_Internal_Server_Error)
@@ -1337,4 +1368,15 @@ class ovim():
         controller_host.create_dhcp_interfaces(vlan, first_ip, dhcp_netmask)
         controller_host.launch_dhcp_server(vlan, ip_range, dhcp_netmask, dhcp_path, gateway)
 
+if __name__ == "__main__":
+
+    parser = argparse.ArgumentParser()
+    parser.add_argument("-v","--version", help="show ovim library version", action="store_true")
+    parser.add_argument("--database-version", help="show required database version", action="store_true")
+    args = parser.parse_args()
+    if args.version:
+        print ('openvimd version {} {}'.format(ovim.get_version(), ovim.get_version_date()))
+        print ('(c) Copyright Telefonica')
+    elif args.database_version:
+        print ('required database version: {}'.format(ovim.get_database_version()))