enhance log message errors when fails at starting
[osm/RO.git] / osm_ro / nfvo.py
index 4c61cb4..3e59285 100644 (file)
@@ -27,8 +27,8 @@ NFVO engine, implementing all the methods for the creation, deletion and managem
 __author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
 __date__ ="$16-sep-2014 22:05:01$"
 
-import imp
-#import json
+import imp
+# import json
 import yaml
 import utils
 import vim_thread
@@ -128,14 +128,16 @@ def start_service(mydb):
         #TODO: log_level_of should not be needed. To be modified in ovim
         'log_level_of': 'DEBUG'
     }
-    ovim = ovim_module.ovim(ovim_configuration)
-    ovim.start_service()
-
-    from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
-    select_ = ('type','d.config as config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name',
-                   'dt.uuid as datacenter_tenant_id','dt.vim_tenant_name as vim_tenant_name','dt.vim_tenant_id as vim_tenant_id',
-                   'user','passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
     try:
+        ovim = ovim_module.ovim(ovim_configuration)
+        ovim.start_service()
+
+        from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
+                'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
+        select_ = ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
+                   'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
+                   'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
+                   'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
         vims = mydb.get_rows(FROM=from_, SELECT=select_)
         for vim in vims:
             extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
@@ -148,12 +150,14 @@ def start_service(mydb):
                 module_info=None
                 try:
                     module = "vimconn_" + vim["type"]
-                    module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
-                    vim_conn = imp.load_module(vim["type"], *module_info)
+                    pkg = __import__("osm_ro." + module)
+                    vim_conn = getattr(pkg, module)
+                    # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
+                    # vim_conn = imp.load_module(vim["type"], *module_info)
                     vimconn_imported[vim["type"]] = vim_conn
                 except (IOError, ImportError) as e:
-                    if module_info and module_info[0]:
-                        file.close(module_info[0])
+                    if module_info and module_info[0]:
+                    #    file.close(module_info[0])
                     raise NfvoException("Unknown vim type '{}'. Cannot open file '{}.py'; {}: {}".format(
                         vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
 
@@ -170,14 +174,25 @@ def start_service(mydb):
                     config=extra, persistent_info=vim_persistent_info[thread_id]
                 )
             except Exception as e:
-                raise NfvoException("Error at VIM  {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), HTTP_Internal_Server_Error)
-            thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['vim_tenant_id'], vim['vim_tenant_name'], vim['vim_tenant_id'])
+                raise NfvoException("Error at VIM  {}; {}: {}".format(vim["type"], type(e).__name__, e),
+                                    HTTP_Internal_Server_Error)
+            thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['vim_tenant_id'], vim['vim_tenant_name'],
+                                                vim['vim_tenant_id'])
             new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, vim['datacenter_name'],
                                                vim['datacenter_tenant_id'], db=db, db_lock=db_lock, ovim=ovim)
             new_thread.start()
             vim_threads["running"][thread_id] = new_thread
     except db_base_Exception as e:
         raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
+    except ovim_module.ovimException as e:
+        message = str(e)
+        if message[:22] == "DATABASE wrong version":
+            message = "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
+                      "at host {dbhost}".format(
+                            msg=message[22:-3], dbname=global_config["db_ovim_name"],
+                            dbuser=global_config["db_ovim_user"], dbpass=global_config["db_ovim_passwd"],
+                            ver=message[-3:-1], dbhost=global_config["db_ovim_host"])
+        raise NfvoException(message, HTTP_Bad_Request)
 
 
 def stop_service():
@@ -192,6 +207,10 @@ def stop_service():
         for thread in global_config["console_thread"]:
             thread.terminate = True
 
+def get_version():
+    return  ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config["version"],
+                                                                        global_config["version_date"] ))
+
 
 def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
     '''Obtain flavorList
@@ -270,12 +289,14 @@ def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, da
                 module_info=None
                 try:
                     module = "vimconn_" + vim["type"]
-                    module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
-                    vim_conn = imp.load_module(vim["type"], *module_info)
+                    pkg = __import__("osm_ro." + module)
+                    vim_conn = getattr(pkg, module)
+                    # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
+                    # vim_conn = imp.load_module(vim["type"], *module_info)
                     vimconn_imported[vim["type"]] = vim_conn
                 except (IOError, ImportError) as e:
-                    if module_info and module_info[0]:
-                        file.close(module_info[0])
+                    if module_info and module_info[0]:
+                        file.close(module_info[0])
                     raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
                                             vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
 
@@ -2751,10 +2772,12 @@ def new_datacenter(mydb, datacenter_descriptor):
     module_info = None
     try:
         module = "vimconn_" + datacenter_type
-        module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
+        pkg = __import__("osm_ro." + module)
+        vim_conn = getattr(pkg, module)
+        # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
     except (IOError, ImportError):
-        if module_info and module_info[0]:
-            file.close(module_info[0])
+        if module_info and module_info[0]:
+        #    file.close(module_info[0])
         raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}'.py not installed".format(datacenter_type, module), HTTP_Bad_Request)
 
     datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True)
@@ -2801,7 +2824,7 @@ def delete_datacenter(mydb, datacenter):
 
 def associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter, vim_tenant_id=None, vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
     #get datacenter info
-    datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter)
+    datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username, vim_passwd=vim_password)
     datacenter_name = myvim["name"]
 
     create_vim_tenant = True if not vim_tenant_id and not vim_tenant_name else False
@@ -2855,18 +2878,22 @@ def associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter, vim_tenant_id=
         datacenter_tenants_dict["uuid"] = id_
 
     #fill tenants_datacenters table
-    tenants_datacenter_dict["datacenter_tenant_id"]=datacenter_tenants_dict["uuid"]
+    datacenter_tenant_id = datacenter_tenants_dict["uuid"]
+    tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
     mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
     # create thread
     datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_dict['uuid'], datacenter_id)  # reload data
     thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
-    new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, datacenter_name, db=db, db_lock=db_lock, ovim=ovim)
+    new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, datacenter_name, datacenter_tenant_id,
+                                       db=db, db_lock=db_lock, ovim=ovim)
     new_thread.start()
     thread_id = datacenter_tenants_dict["uuid"]
     vim_threads["running"][thread_id] = new_thread
     return datacenter_id
 
-def edit_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=None, vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
+
+def edit_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=None, vim_tenant_name=None,
+                              vim_username=None, vim_password=None, config=None):
     #Obtain the data of this datacenter_tenant_id
     vim_data = mydb.get_rows(
         SELECT=("datacenter_tenants.vim_tenant_name", "datacenter_tenants.vim_tenant_id", "datacenter_tenants.user",