(bug 351) fix getting datacenter uuid from name at instantiation. 26/5526/1
authortierno <alfonso.tiernosepulveda@telefonica.com>
Thu, 5 Oct 2017 10:41:44 +0000 (12:41 +0200)
committertierno <alfonso.tiernosepulveda@telefonica.com>
Thu, 5 Oct 2017 10:59:24 +0000 (12:59 +0200)
Fix instance without scenario issues

Change-Id: I1f6e171405a31848f5d15df1cc94dddd782bb9a0
Signed-off-by: tierno <alfonso.tiernosepulveda@telefonica.com>
openmano
openmanod
osm_ro/nfvo.py
osm_ro/nfvo_db.py

index 6af5ea5..8f5d7cc 100755 (executable)
--- a/openmano
+++ b/openmano
@@ -28,8 +28,8 @@ openmano client used to interact with openmano-server (openmanod)
 """
 __author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes"
 __date__ = "$09-oct-2014 09:09:48$"
-__version__ = "0.4.20-r530"
-version_date = "Sep 2017"
+__version__ = "0.4.21-r531"
+version_date = "Oct 2017"
 
 from argcomplete.completers import FilesCompleter
 import os
@@ -133,24 +133,24 @@ def _print_verbose(mano_response, verbose_level=0):
                 uuid = ""
             if not name:
                 name = ""
-            myoutput = "%s %s" %(uuid.ljust(38),name.ljust(20))
+            myoutput = "{:38} {:20}".format(uuid, name)
             if content.get("status"):
-                myoutput += " " + content['status'].ljust(20)
+                myoutput += " {:20}".format(content['status'])
             elif "enabled" in content and not content["enabled"]:
                 myoutput += " enabled=False".ljust(20)
             if verbose_level >=1:
                 if content.get('created_at'):
-                    myoutput += " " + content['created_at'].ljust(20)
+                    myoutput += " {:20}".format(content['created_at'])
                 if content.get('sdn_attached_ports'):
                     #myoutput += " " + str(content['sdn_attached_ports']).ljust(20)
                     myoutput += "\nsdn_attached_ports:\n" + yaml.safe_dump(content['sdn_attached_ports'], indent=4, default_flow_style=False)
                 if verbose_level >=2:
                     new_line='\n'
                     if content.get('type'):
-                        myoutput += new_line + "  Type: " + content['type'].ljust(29)
+                        myoutput += new_line + "  Type: {:29}".format(content['type'])
                         new_line=''
                     if content.get('description'):
-                        myoutput += new_line + "  Description: " + content['description'].ljust(20)
+                        myoutput += new_line + "  Description: {:20}".format(content['description'])
             print myoutput
     else:
         print content['error']['description']
@@ -783,11 +783,11 @@ def instance_create(args):
         return result
 
     if mano_response.status_code == 200:
-        myoutput = "%s %s" %(content['uuid'].ljust(38),content['name'].ljust(20))
+        myoutput = "{:38} {:20}".format(content['uuid'], content['name'])
         if args.verbose >=1:
-            myoutput = "%s %s" %(myoutput, content['created_at'].ljust(20))
+            myoutput = "{} {:20}".format(myoutput, content['created_at'])
         if args.verbose >=2:
-            myoutput = "%s %s %s" %(myoutput, content['description'].ljust(30))
+            myoutput = "{} {:30}".format(myoutput, content['description'])
         print myoutput
     else:
         print content['error']['description']
@@ -821,9 +821,9 @@ def instance_scenario_list(args):
                 print "No scenario instances were found."
                 return result
             for instance in content['instances']:
-                myoutput = "%s %s" %(instance['uuid'].ljust(38),instance['name'].ljust(20))
+                myoutput = "{:38} {:20}".format(instance['uuid'], instance['name'])
                 if args.verbose >=1:
-                    myoutput = "%s %s" %(myoutput, instance['created_at'].ljust(20))
+                    myoutput = "{} {:20}".format(myoutput, instance['created_at'])
                 print myoutput
                 if args.verbose >=2:
                     print "Description: %s" %instance['description']
@@ -832,31 +832,32 @@ def instance_scenario_list(args):
                 print yaml.safe_dump(content, indent=4, default_flow_style=False)
                 return result
             instance = content
-            print "%s %s %s" %(instance['uuid'].ljust(38),instance['name'].ljust(20),instance['created_at'].ljust(20))
-            print "Description: %s" %instance['description']
-            print "Template scenario id: %s" %instance['scenario_id']
-            print "Template scenario name: %s" %instance['scenario_name']
-            print "---------------------------------------"
-            print "VNF instances: %d" %len(instance['vnfs'])
+            print ("{:38} {:20} {:20}".format(instance['uuid'],instance['name'],instance['created_at']))
+            print ("Description: %s" %instance['description'])
+            print ("Template scenario id: {}".format(instance['scenario_id']))
+            print ("Template scenario name: {}".format(instance['scenario_name']))
+            print ("---------------------------------------")
+            print ("VNF instances: {}".format(len(instance['vnfs'])))
             for vnf in instance['vnfs']:
                 #print "    %s %s Template vnf name: %s Template vnf id: %s" %(vnf['uuid'].ljust(38), vnf['name'].ljust(20), vnf['vnf_name'].ljust(20), vnf['vnf_id'].ljust(38))
-                print "    %s %s Template vnf id: %s" %(vnf['uuid'].ljust(38), vnf['vnf_name'].ljust(20), vnf['vnf_id'].ljust(38))
+                print ("    {:38} {:20} Template vnf id: {:38}".format(vnf['uuid'], vnf['vnf_name'], vnf['vnf_id']))
             if len(instance['nets'])>0:
                 print "---------------------------------------"
                 print "Internal nets:"
                 for net in instance['nets']:
                     if net['created']:
-                        print "    %s %s VIM ID: %s" %(net['uuid'].ljust(38), net['status'].ljust(12), net['vim_net_id'])
+                        print ("    {:38} {:12} VIM ID: {}".format(net['uuid'], net['status'], net['vim_net_id']))
                 print "---------------------------------------"
                 print "External nets:"
                 for net in instance['nets']:
                     if not net['created']:
-                        print "    %s %s VIM ID: %s" %(net['uuid'].ljust(38), net['status'].ljust(12), net['vim_net_id'])
-            print "---------------------------------------"
-            print "VM instances:"
+                        print ("    {:38} {:12} VIM ID: {}".format(net['uuid'], net['status'], net['vim_net_id']))
+            print ("---------------------------------------")
+            print ("VM instances:")
             for vnf in instance['vnfs']:
                 for vm in vnf['vms']:
-                    print "    %s %s %s %s VIM ID: %s" %(vm['uuid'].ljust(38), vnf['vnf_name'].ljust(20), vm['name'].ljust(20), vm['status'].ljust(12), vm['vim_vm_id'])
+                    print ("    {:38} {:20} {:20} {:12} VIM ID: {}".format(vm['uuid'], vnf['vnf_name'], vm['name'],
+                                                                           vm['status'], vm['vim_vm_id']))
     else:
         print content['error']['description']
         if args.verbose:
@@ -937,7 +938,7 @@ def instance_scenario_action(args):
             print yaml.safe_dump(content, indent=4, default_flow_style=False)
             return result
         for uuid,c in content.iteritems():
-            print "%s %s %s" %(uuid.ljust(38), c['name'].ljust(20),c['description'].ljust(20))
+            print ("{:38} {:20} {:20}".format(uuid, c['name'], c['description']))
     else:
         print content['error']['description']
     return result
index 244ba4d..22f4d02 100755 (executable)
--- a/openmanod
+++ b/openmanod
@@ -48,7 +48,7 @@ import osm_ro
 
 __author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes"
 __date__ = "$26-aug-2014 11:09:29$"
-__version__ = "0.5.27-r537"
+__version__ = "0.5.28-r538"
 version_date = "Oct 2017"
 database_version = 27      # expected database schema version
 
index 4ed6613..d5de61f 100644 (file)
@@ -2531,6 +2531,28 @@ def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_i
         raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
 
 
+def get_datacenter_uuid(mydb, tenant_id, datacenter_id_name):
+    WHERE_dict={}
+    if utils.check_valid_uuid(datacenter_id_name):
+        WHERE_dict['d.uuid'] = datacenter_id_name
+    else:
+        WHERE_dict['d.name'] = datacenter_id_name
+
+    if tenant_id:
+        WHERE_dict['nfvo_tenant_id'] = tenant_id
+        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"
+    else:
+        from_ = 'datacenters as d'
+    vimaccounts = mydb.get_rows(FROM=from_, SELECT=("d.uuid as uuid",), WHERE=WHERE_dict )
+    if len(vimaccounts) == 0:
+        raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
+    elif len(vimaccounts)>1:
+        #print "nfvo.datacenter_action() error. Several datacenters found"
+        raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
+    return vimaccounts[0]["uuid"]
+
+
 def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
     datacenter_id = None
     datacenter_name = None
@@ -2637,6 +2659,7 @@ def create_instance(mydb, tenant_id, instance_dict):
             site_without_datacenter_field = False
             for site in net_instance_desc["sites"]:
                 if site.get("datacenter"):
+                    site["datacenter"] = get_datacenter_uuid(mydb, tenant_id, site["datacenter"])
                     if site["datacenter"] not in myvims:
                         # Add this datacenter to myvims
                         d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
@@ -2660,6 +2683,7 @@ def create_instance(mydb, tenant_id, instance_dict):
                 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request)
             if "datacenter" in vnf_instance_desc:
                 # Add this datacenter to myvims
+                vnf_instance_desc["datacenter"] = get_datacenter_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
                 if vnf_instance_desc["datacenter"] not in myvims:
                     d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
                     myvims[d] = v
index 79ba7d7..f47ad16 100644 (file)
@@ -906,35 +906,39 @@ class nfvo_db(db_base.db_base):
                 with self.con:
                     self.cur = self.con.cursor(mdb.cursors.DictCursor)
                     # instance table
-                    where_list=[]
-                    if tenant_id is not None: where_list.append( "inst.tenant_id='" + tenant_id +"'" )
+                    where_list = []
+                    if tenant_id:
+                        where_list.append("inst.tenant_id='{}'".format(tenant_id))
                     if db_base._check_valid_uuid(instance_id):
-                        where_list.append( "inst.uuid='" + instance_id +"'" )
+                        where_list.append("inst.uuid='{}'".format(instance_id))
                     else:
-                        where_list.append( "inst.name='" + instance_id +"'" )
+                        where_list.append("inst.name='{}'".format(instance_id))
                     where_text = " AND ".join(where_list)
-                    cmd = "SELECT inst.uuid as uuid,inst.name as name,inst.scenario_id as scenario_id, datacenter_id" +\
-                                " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" \
-                                " ,inst.description as description,inst.created_at as created_at" +\
-                                " ,inst.cloud_config as 'cloud_config'" +\
-                            " FROM instance_scenarios as inst join scenarios as s on inst.scenario_id=s.uuid"+\
+                    cmd = "SELECT inst.uuid as uuid, inst.name as name, inst.scenario_id as scenario_id, datacenter_id"\
+                                " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" \
+                                " ,inst.description as description, inst.created_at as created_at" \
+                                " ,inst.cloud_config as cloud_config" \
+                            " FROM instance_scenarios as inst left join scenarios as s on inst.scenario_id=s.uuid" \
                             " WHERE " + where_text
                     self.logger.debug(cmd)
                     self.cur.execute(cmd)
                     rows = self.cur.fetchall()
                     
-                    if self.cur.rowcount==0:
+                    if self.cur.rowcount == 0:
                         raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Not_Found)
-                    elif self.cur.rowcount>1:
-                        raise db_base.db_base_Exception("More than one instance found where " + where_text, db_base.HTTP_Bad_Request)
+                    elif self.cur.rowcount > 1:
+                        raise db_base.db_base_Exception("More than one instance found where " + where_text,
+                                                        db_base.HTTP_Bad_Request)
                     instance_dict = rows[0]
                     if instance_dict["cloud_config"]:
                         instance_dict["cloud-config"] = yaml.load(instance_dict["cloud_config"])
                     del instance_dict["cloud_config"]
                     
-                    #instance_vnfs
-                    cmd = "SELECT iv.uuid as uuid,sv.vnf_id as vnf_id,sv.name as vnf_name, sce_vnf_id, datacenter_id, datacenter_tenant_id, v.mgmt_access"\
-                            " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid join vnfs as v on iv.vnf_id=v.uuid" \
+                    # instance_vnfs
+                    cmd = "SELECT iv.uuid as uuid, iv.vnf_id as vnf_id, sv.name as vnf_name, sce_vnf_id, datacenter_id"\
+                                " ,datacenter_tenant_id, v.mgmt_access "\
+                            " FROM instance_vnfs as iv left join sce_vnfs as sv "\
+                                "on iv.sce_vnf_id=sv.uuid join vnfs as v on iv.vnf_id=v.uuid" \
                             " WHERE iv.instance_scenario_id='{}'" \
                             " ORDER BY iv.created_at ".format(instance_dict['uuid'])
                     self.logger.debug(cmd)
@@ -951,7 +955,7 @@ class nfvo_db(db_base.db_base):
                         vnf['vms'] = self.cur.fetchall()
                         for vm in vnf['vms']:
                             vm_manage_iface_list=[]
-                            #instance_interfaces
+                            # instance_interfaces
                             cmd = "SELECT vim_interface_id, instance_net_id, internal_name,external_name, mac_address,"\
                                   " ii.ip_address as ip_address, vim_info, i.type as type, sdn_port_id"\
                                   " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid"\