Fix bug installing openvim and db generation
[osm/openvim.git] / osm_openvim / ovim.py
index a4108b6..e7a8b49 100755 (executable)
 # contact with: nfvlabs@tid.es
 ##
 
-'''
+"""
 This is the thread for the http server North API. 
 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 imp
+# import imp
+import os.path
 import argparse
 from netaddr import IPNetwork
 from jsonschema import validate as js_v, exceptions as js_e
@@ -45,6 +40,11 @@ import dhcp_thread as dt
 import openflow_thread as oft
 import openflow_conn
 
+__author__ = "Alfonso Tierno, Leonardo Mirabal"
+__date__ = "$06-Feb-2017 12:07:15$"
+__version__ = "0.5.12-r528"
+version_date = "May 2017"
+database_version = 17      #needed database schema version
 
 HTTP_Bad_Request =          400
 HTTP_Unauthorized =         401
@@ -172,12 +172,20 @@ class ovim():
         # if self.running_info:
         #    return  #TODO service can be checked and rebuild broken threads
         r = self.db.get_db_version()
+        db_path = __file__
+        db_path = db_path[:db_path.rfind("/")]
+        if os.path.exists(db_path + "/database_utils/migrate_vim_db.sh"):
+            db_path += "/database_utils"
+        else:
+            db_path += "/../database_utils"
+
         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(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], database_version) )
+            raise ovimException("DATABASE is not valid. If you think it is corrupted, you can init it with"
+                                " '{db_path}/init_vim_db.sh' script".format(db_path=db_path))
+        elif r[0] != database_version:
+            raise ovimException("DATABASE wrong version '{current}'. Try to upgrade/downgrade to version '{target}'"
+                                " with '{db_path}/migrate_vim_db.sh {target}'".format(
+                                current=r[0], target=database_version,  db_path=db_path))
         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
@@ -371,27 +379,29 @@ class ovim():
                 module = temp_dict['of_controller']
 
             if module not in ovim.of_module:
-                module_info = imp.find_module(module)
-                of_conn_module = imp.load_module("OF_conn", *module_info)
-                ovim.of_module[module] = of_conn_module
+                for base in ("", "osm_openvim.", "lib_osm_openvim."):
+                    try:
+                        pkg = __import__(base + module)
+                        if base:
+                            of_conn_module = getattr(pkg, module)
+                        else:
+                            of_conn_module = pkg
+                        ovim.of_module[module] = of_conn_module
+                        self.logger.debug("Module load from {}".format(base + module))
+                        break
+                    except Exception as e:
+                        self.logger.warning("Module {} not found {}".format(base + module, e))
+                else:
+                    self.logger.error("Cannot open openflow controller module of type '%s'", module)
+                    raise ovimException("Cannot open openflow controller of type module '{}'"
+                                        "Revise it is installed".format(module),
+                                        HTTP_Internal_Server_Error)
             else:
                 of_conn_module = ovim.of_module[module]
-
-            try:
-                return of_conn_module.OF_conn(temp_dict)
-            except Exception as e:
-                self.logger.error("Cannot open the Openflow controller '%s': %s", type(e).__name__, str(e))
-                if module_info and module_info[0]:
-                    file.close(module_info[0])
-                raise ovimException("Cannot open the Openflow controller '{}': '{}'".format(type(e).__name__, str(e)),
-                                    HTTP_Internal_Server_Error)
-        except (IOError, ImportError) as e:
-            if module_info and module_info[0]:
-                file.close(module_info[0])
-            self.logger.error("Cannot open openflow controller module '%s'; %s: %s; revise 'of_controller' "
-                              "field of configuration file.", module, type(e).__name__, str(e))
-            raise ovimException("Cannot open openflow controller module '{}'; {}: {}; revise 'of_controller' "
-                                "field of configuration file.".format(module, type(e).__name__, str(e)),
+            return of_conn_module.OF_conn(temp_dict)
+        except Exception as e:
+            self.logger.error("Cannot open the Openflow controller '%s': %s", type(e).__name__, str(e))
+            raise ovimException("Cannot open the Openflow controller '{}': '{}'".format(type(e).__name__, str(e)),
                                 HTTP_Internal_Server_Error)
 
     def _create_ofc_thread(self, of_conn, ofc_uuid="Default"):