More Py3 conversion work python3
authorAdam Israel <adam.israel@canonical.com>
Mon, 8 Jan 2018 18:43:40 +0000 (18:43 +0000)
committerAdam Israel <adam.israel@canonical.com>
Mon, 8 Jan 2018 18:43:40 +0000 (18:43 +0000)
22 files changed:
Makefile
openmanod
osm_ro/db_base.py
osm_ro/httpserver.py
osm_ro/nfvo.py
osm_ro/nfvo_db.py
osm_ro/openmanoclient.py
osm_ro/utils.py
osm_ro/vim_thread.py
osm_ro/vimconn.py
osm_ro/vimconn_aws.py
osm_ro/vimconn_openstack.py
osm_ro/vimconn_openvim.py
osm_ro/vimconn_vmware.py
osm_ro/vmware_utils/OVF_converter/format_converter/command_progress.py
osm_ro/vmware_utils/OVF_converter/format_converter/converter.py
osm_ro/vmware_utils/OVF_converter/format_converter/ovf_converter_cli.py
osm_ro/vmwarecli.py
osm_ro/vmwarerecli.py
requirements.txt
setup.py
tox.ini

index d312845..55864f2 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -43,11 +43,11 @@ connectors: prepare
        # python-novaclient is required for that
        rm -f build/osm_ro/openmanolinkervimconn.py
        cd build/osm_ro; for i in `ls vimconn_*.py |sed "s/\.py//"` ; do echo "import $$i" >> openmanolinkervimconn.py; done
        # python-novaclient is required for that
        rm -f build/osm_ro/openmanolinkervimconn.py
        cd build/osm_ro; for i in `ls vimconn_*.py |sed "s/\.py//"` ; do echo "import $$i" >> openmanolinkervimconn.py; done
-       python build/osm_ro/openmanolinkervimconn.py
+       python3 build/osm_ro/openmanolinkervimconn.py 2>&1
        rm -f build/osm_ro/openmanolinkervimconn.py
 
 build: connectors prepare
        rm -f build/osm_ro/openmanolinkervimconn.py
 
 build: connectors prepare
-       python -m py_compile build/osm_ro/*.py
+       python3 -m py_compile build/osm_ro/*.py
 #      cd build && tox -e flake8
 
 lib-openvim:
 #      cd build && tox -e flake8
 
 lib-openvim:
@@ -65,11 +65,11 @@ osm-im:
 
 package: prepare
 #      apt-get install -y python-stdeb
 
 package: prepare
 #      apt-get install -y python-stdeb
-       cd build && python setup.py --command-packages=stdeb.command sdist_dsc --with-python2=True
+       cd build && python3 setup.py --command-packages=stdeb.command sdist_dsc --with-python2=True
        cd build && cp osm_ro/scripts/python-osm-ro.postinst deb_dist/osm-ro*/debian/
        cd build/deb_dist/osm-ro* && dpkg-buildpackage -rfakeroot -uc -us
        mkdir -p .build
        cd build && cp osm_ro/scripts/python-osm-ro.postinst deb_dist/osm-ro*/debian/
        cd build/deb_dist/osm-ro* && dpkg-buildpackage -rfakeroot -uc -us
        mkdir -p .build
-       cp build/deb_dist/python-*.deb .build/
+       cp build/deb_dist/python3-*.deb .build/
 
 snap:
        echo "Nothing to be done yet"
 
 snap:
        echo "Nothing to be done yet"
@@ -103,5 +103,3 @@ run-docker:
 
 stop-docker:
        docker-compose -f docker/openmano-compose.yml down
 
 stop-docker:
        docker-compose -f docker/openmano-compose.yml down
-
-
index 145fd24..149e924 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$"
 
 __author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes"
 __date__ = "$26-aug-2014 11:09:29$"
-__version__ = "0.5.36-r546"
+__version__ = "0.5.37-r547"
 version_date = "Oct 2017"
 database_version = 27      # expected database schema version
 
 version_date = "Oct 2017"
 database_version = 27      # expected database schema version
 
index 42e072b..c8e5eb1 100644 (file)
@@ -29,7 +29,7 @@ __date__ ="$4-Apr-2016 10:05:01$"
 
 import MySQLdb as mdb
 import uuid as myUuid
 
 import MySQLdb as mdb
 import uuid as myUuid
-from . import  utils as af
+import  utils as af
 import json
 #import yaml
 import time
 import json
 #import yaml
 import time
@@ -65,7 +65,7 @@ def _convert_datetime2str(var):
     It enters recursively in the dict var finding this kind of variables
     '''
     if type(var) is dict:
     It enters recursively in the dict var finding this kind of variables
     '''
     if type(var) is dict:
-        for k,v in list(var.items()):
+        for k,v in var.items():
             if type(v) is datetime.datetime:
                 var[k]= v.strftime('%Y-%m-%dT%H:%M:%S')
             elif type(v) is dict or type(v) is list or type(v) is tuple: 
             if type(v) is datetime.datetime:
                 var[k]= v.strftime('%Y-%m-%dT%H:%M:%S')
             elif type(v) is dict or type(v) is list or type(v) is tuple: 
@@ -85,7 +85,7 @@ def _convert_bandwidth(data, reverse=False, logger=None):
         None
     '''
     if type(data) is dict:
         None
     '''
     if type(data) is dict:
-        for k in list(data.keys()):
+        for k in data.keys():
             if type(data[k]) is dict or type(data[k]) is tuple or type(data[k]) is list:
                 _convert_bandwidth(data[k], reverse, logger)
         if "bandwidth" in data:
             if type(data[k]) is dict or type(data[k]) is tuple or type(data[k]) is list:
                 _convert_bandwidth(data[k], reverse, logger)
         if "bandwidth" in data:
@@ -120,7 +120,7 @@ def _convert_str2boolean(data, items):
         None
     '''
     if type(data) is dict:
         None
     '''
     if type(data) is dict:
-        for k in list(data.keys()):
+        for k in data.keys():
             if type(data[k]) is dict or type(data[k]) is tuple or type(data[k]) is list:
                 _convert_str2boolean(data[k], items)
             if k in items:
             if type(data[k]) is dict or type(data[k]) is tuple or type(data[k]) is list:
                 _convert_str2boolean(data[k], items)
             if k in items:
@@ -320,7 +320,7 @@ class db_base():
     
     def __remove_quotes(self, data):
         '''remove single quotes ' of any string content of data dictionary'''
     
     def __remove_quotes(self, data):
         '''remove single quotes ' of any string content of data dictionary'''
-        for k,v in list(data.items()):
+        for k,v in data.items():
             if type(v) == str:
                 if "'" in v: 
                     data[k] = data[k].replace("'","_")
             if type(v) == str:
                 if "'" in v: 
                     data[k] = data[k].replace("'","_")
@@ -334,11 +334,11 @@ class db_base():
         Return: the number of updated rows, exception if error
         '''
                 #gettting uuid 
         Return: the number of updated rows, exception if error
         '''
                 #gettting uuid 
-        values = ",".join(map(self.__tuple2db_format_set, iter(UPDATE.items()) ))
+        values = ",".join(map(self.__tuple2db_format_set, UPDATE.iteritems() ))
         if modified_time:
             values += ",modified_at={:f}".format(modified_time)
         cmd= "UPDATE " + table +" SET " + values +\
         if modified_time:
             values += ",modified_at={:f}".format(modified_time)
         cmd= "UPDATE " + table +" SET " + values +\
-            " WHERE " + " and ".join(map(self.__tuple2db_format_where, iter(WHERE.items()) ))
+            " WHERE " + " and ".join(map(self.__tuple2db_format_where, WHERE.iteritems() ))
         self.logger.debug(cmd)
         self.cur.execute(cmd) 
         return self.cur.rowcount
         self.logger.debug(cmd)
         self.cur.execute(cmd) 
         return self.cur.rowcount
@@ -400,7 +400,7 @@ class db_base():
             self.cur.execute(cmd)
         #insertion
         cmd= "INSERT INTO " + table +" SET " + \
             self.cur.execute(cmd)
         #insertion
         cmd= "INSERT INTO " + table +" SET " + \
-            ",".join(map(self.__tuple2db_format_set, iter(INSERT.items()) )) 
+            ",".join(map(self.__tuple2db_format_set, INSERT.iteritems() )) 
         if created_time:
             cmd += ",created_at=%f" % created_time
         if confidential_data:
         if created_time:
             cmd += ",created_at=%f" % created_time
         if confidential_data:
@@ -501,11 +501,11 @@ class db_base():
         #print 'from_', from_
         if 'WHERE' in sql_dict and len(sql_dict['WHERE']) > 0:
             w=sql_dict['WHERE']
         #print 'from_', from_
         if 'WHERE' in sql_dict and len(sql_dict['WHERE']) > 0:
             w=sql_dict['WHERE']
-            where_ = "WHERE " + " AND ".join(map(self.__tuple2db_format_where, iter(w.items()))) 
+            where_ = "WHERE " + " AND ".join(map(self.__tuple2db_format_where, w.iteritems())) 
         else: where_ = ""
         if 'WHERE_NOT' in sql_dict and len(sql_dict['WHERE_NOT']) > 0: 
             w=sql_dict['WHERE_NOT']
         else: where_ = ""
         if 'WHERE_NOT' in sql_dict and len(sql_dict['WHERE_NOT']) > 0: 
             w=sql_dict['WHERE_NOT']
-            where_2 = " AND ".join(map(self.__tuple2db_format_where_not, iter(w.items())))
+            where_2 = " AND ".join(map(self.__tuple2db_format_where_not, w.iteritems()))
             if len(where_)==0:   where_ = "WHERE " + where_2
             else:                where_ = where_ + " AND " + where_2
         #print 'where_', where_
             if len(where_)==0:   where_ = "WHERE " + where_2
             else:                where_ = where_ + " AND " + where_2
         #print 'where_', where_
@@ -563,14 +563,14 @@ class db_base():
         where_or = ""
         w=sql_dict.get('WHERE')
         if w:
         where_or = ""
         w=sql_dict.get('WHERE')
         if w:
-            where_and = " AND ".join(map(self.__tuple2db_format_where, iter(w.items()) ))
+            where_and = " AND ".join(map(self.__tuple2db_format_where, w.iteritems() ))
         w=sql_dict.get('WHERE_NOT')
         if w: 
             if where_and: where_and += " AND "
         w=sql_dict.get('WHERE_NOT')
         if w: 
             if where_and: where_and += " AND "
-            where_and += " AND ".join(map(self.__tuple2db_format_where_not, iter(w.items()) ) )
+            where_and += " AND ".join(map(self.__tuple2db_format_where_not, w.iteritems() ) )
         w=sql_dict.get('WHERE_OR')
         if w:
         w=sql_dict.get('WHERE_OR')
         if w:
-            where_or =  " OR ".join(map(self.__tuple2db_format_where, iter(w.items()) ))
+            where_or =  " OR ".join(map(self.__tuple2db_format_where, w.iteritems() ))
         if where_and and where_or:
             if sql_dict.get("WHERE_AND_OR") == "AND":
                 where_ = "WHERE " + where_and + " AND (" + where_or + ")"
         if where_and and where_or:
             if sql_dict.get("WHERE_AND_OR") == "AND":
                 where_ = "WHERE " + where_and + " AND (" + where_or + ")"
@@ -619,7 +619,7 @@ class db_base():
         what = 'uuid' if af.check_valid_uuid(uuid_name) else 'name'
         cmd =  " SELECT * FROM {} WHERE {}='{}'".format(table, what, uuid_name)
         if WHERE_OR:
         what = 'uuid' if af.check_valid_uuid(uuid_name) else 'name'
         cmd =  " SELECT * FROM {} WHERE {}='{}'".format(table, what, uuid_name)
         if WHERE_OR:
-            where_or =  " OR ".join(map(self.__tuple2db_format_where, iter(WHERE_OR.items()) ))
+            where_or =  " OR ".join(map(self.__tuple2db_format_where, WHERE_OR.iteritems() ))
             if WHERE_AND_OR == "AND":
                 cmd += " AND (" + where_or + ")"
             else:
             if WHERE_AND_OR == "AND":
                 cmd += " AND (" + where_or + ")"
             else:
@@ -657,7 +657,7 @@ class db_base():
                     rows = self.cur.fetchall()
                     return self.cur.rowcount, rows
             except (mdb.Error, AttributeError) as e:
                     rows = self.cur.fetchall()
                     return self.cur.rowcount, rows
             except (mdb.Error, AttributeError) as e:
-                print("nfvo_db.get_uuid DB Exception %d: %s" % (e.args[0], e.args[1]))
+                print "nfvo_db.get_uuid DB Exception %d: %s" % (e.args[0], e.args[1])
                 r,c = self._format_error(e)
                 if r!=-HTTP_Request_Timeout or retry_==1: return r,c
 
                 r,c = self._format_error(e)
                 if r!=-HTTP_Request_Timeout or retry_==1: return r,c
 
index 1f08c46..b043267 100644 (file)
@@ -37,7 +37,7 @@ import time
 import logging
 
 from jsonschema import validate as js_v, exceptions as js_e
 import logging
 
 from jsonschema import validate as js_v, exceptions as js_e
-from .openmano_schemas import vnfd_schema_v01, vnfd_schema_v02, \
+from openmano_schemas import vnfd_schema_v01, vnfd_schema_v02, \
                             nsd_schema_v01, nsd_schema_v02, nsd_schema_v03, scenario_edit_schema, \
                             scenario_action_schema, instance_scenario_action_schema, instance_scenario_create_schema_v01, \
                             tenant_schema, tenant_edit_schema,\
                             nsd_schema_v01, nsd_schema_v02, nsd_schema_v03, scenario_edit_schema, \
                             scenario_action_schema, instance_scenario_action_schema, instance_scenario_create_schema_v01, \
                             tenant_schema, tenant_edit_schema,\
@@ -45,9 +45,9 @@ from .openmano_schemas import vnfd_schema_v01, vnfd_schema_v02, \
                             object_schema, netmap_new_schema, netmap_edit_schema, sdn_controller_schema, sdn_controller_edit_schema, \
                             sdn_port_mapping_schema, sdn_external_port_schema
 
                             object_schema, netmap_new_schema, netmap_edit_schema, sdn_controller_schema, sdn_controller_edit_schema, \
                             sdn_port_mapping_schema, sdn_external_port_schema
 
-from . import nfvo
-from . import utils
-from .db_base import db_base_Exception
+import nfvo
+import utils
+from db_base import db_base_Exception
 from functools import wraps
 
 global mydb
 from functools import wraps
 
 global mydb
@@ -67,7 +67,7 @@ HTTP_Internal_Server_Error= 500
 
 def delete_nulls(var):
     if type(var) is dict:
 
 def delete_nulls(var):
     if type(var) is dict:
-        for k in list(var.keys()):
+        for k in var.keys():
             if var[k] is None: del var[k]
             elif type(var[k]) is dict or type(var[k]) is list or type(var[k]) is tuple: 
                 if delete_nulls(var[k]): del var[k]
             if var[k] is None: del var[k]
             elif type(var[k]) is dict or type(var[k]) is list or type(var[k]) is tuple: 
                 if delete_nulls(var[k]): del var[k]
@@ -83,7 +83,7 @@ def convert_datetime2str(var):
     It enters recursively in the dict var finding this kind of variables
     '''
     if type(var) is dict:
     It enters recursively in the dict var finding this kind of variables
     '''
     if type(var) is dict:
-        for k,v in list(var.items()):
+        for k,v in var.items():
             if type(v) is float and k in ("created_at", "modified_at"):
                 var[k] = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(v) )
             elif type(v) is dict or type(v) is list or type(v) is tuple: 
             if type(v) is float and k in ("created_at", "modified_at"):
                 var[k] = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(v) )
             elif type(v) is dict or type(v) is list or type(v) is tuple: 
@@ -166,10 +166,10 @@ def change_keys_http2db(data, http_db, reverse=False):
             change_keys_http2db(d, http_db, reverse)
     elif type(data) is dict or type(data) is bottle.FormsDict:
         if reverse:
             change_keys_http2db(d, http_db, reverse)
     elif type(data) is dict or type(data) is bottle.FormsDict:
         if reverse:
-            for k,v in list(http_db.items()):
+            for k,v in http_db.items():
                 if v in data: data[k]=data.pop(v)
         else:
                 if v in data: data[k]=data.pop(v)
         else:
-            for k,v in list(http_db.items()):
+            for k,v in http_db.items():
                 if k in data: data[v]=data.pop(k)
 
 def format_out(data):
                 if k in data: data[v]=data.pop(k)
 
 def format_out(data):
@@ -767,7 +767,7 @@ def http_getnetmap_datacenter_id(tenant_id, datacenter_id, netmap_id=None):
         if netmap_id and len(netmaps)==1:
             data={'netmap' : netmaps[0]}
         elif netmap_id and len(netmaps)==0:
         if netmap_id and len(netmaps)==1:
             data={'netmap' : netmaps[0]}
         elif netmap_id and len(netmaps)==0:
-            bottle.abort(HTTP_Not_Found, "No netmap found with " + " and ".join([str(x[0])+": "+str(x[1]) for x in iter(where_.items())]) )
+            bottle.abort(HTTP_Not_Found, "No netmap found with " + " and ".join(map(lambda x: str(x[0])+": "+str(x[1]), where_.iteritems())) )
             return 
         else:
             data={'netmaps' : netmaps}
             return 
         else:
             data={'netmaps' : netmaps}
@@ -799,7 +799,7 @@ def http_delnetmap_datacenter_id(tenant_id, datacenter_id, netmap_id=None):
         #change_keys_http2db(content, http2db_tenant, reverse=True)
         deleted = mydb.delete_row(FROM='datacenter_nets', WHERE= where_) 
         if deleted == 0 and netmap_id:
         #change_keys_http2db(content, http2db_tenant, reverse=True)
         deleted = mydb.delete_row(FROM='datacenter_nets', WHERE= where_) 
         if deleted == 0 and netmap_id:
-            bottle.abort(HTTP_Not_Found, "No netmap found with " + " and ".join([str(x[0])+": "+str(x[1]) for x in iter(where_.items())]) )
+            bottle.abort(HTTP_Not_Found, "No netmap found with " + " and ".join(map(lambda x: str(x[0])+": "+str(x[1]), where_.iteritems())) )
         if netmap_id:
             return format_out({"result": "netmap %s deleted" % netmap_id})
         else:
         if netmap_id:
             return format_out({"result": "netmap %s deleted" % netmap_id})
         else:
index 8a1d949..bd5b5d6 100644 (file)
@@ -30,18 +30,18 @@ __date__ ="$16-sep-2014 22:05:01$"
 # import imp
 # import json
 import yaml
 # import imp
 # import json
 import yaml
-from . import utils
-from . import vim_thread
-from .db_base import HTTP_Unauthorized, HTTP_Bad_Request, HTTP_Internal_Server_Error, HTTP_Not_Found,\
+import utils
+import vim_thread
+from db_base import HTTP_Unauthorized, HTTP_Bad_Request, HTTP_Internal_Server_Error, HTTP_Not_Found,\
     HTTP_Conflict, HTTP_Method_Not_Allowed
     HTTP_Conflict, HTTP_Method_Not_Allowed
-from . import console_proxy_thread as cli
-from . import vimconn
+import console_proxy_thread as cli
+import vimconn
 import logging
 import collections
 from uuid import uuid4
 import logging
 import collections
 from uuid import uuid4
-from .db_base import db_base_Exception
+from db_base import db_base_Exception
 
 
-from . import nfvo_db
+import nfvo_db
 from threading import Lock
 import time as t
 from lib_osm_openvim import ovim as ovim_module
 from threading import Lock
 import time as t
 from lib_osm_openvim import ovim as ovim_module
@@ -212,7 +212,7 @@ def stop_service():
     global ovim, global_config
     if ovim:
         ovim.stop_service()
     global ovim, global_config
     if ovim:
         ovim.stop_service()
-    for thread_id,thread in list(vim_threads["running"].items()):
+    for thread_id,thread in vim_threads["running"].items():
         thread.insert_task("exit")
         vim_threads["deleting"][thread_id] = thread
     vim_threads["running"] = {}
         thread.insert_task("exit")
         vim_threads["deleting"][thread_id] = thread
     vim_threads["running"] = {}
@@ -518,7 +518,7 @@ def create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vi
             image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
             rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
     #create image at every vim
             image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
             rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
     #create image at every vim
-    for vim_id,vim in vims.items():
+    for vim_id,vim in vims.iteritems():
         datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
         image_created="false"
         #look at database
         datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
         image_created="false"
         #look at database
@@ -636,7 +636,7 @@ def create_or_use_flavor(mydb, vims, flavor_dict, rollback_list, only_create_at_
     if 'uuid' in flavor_dict:
         del flavor_dict['uuid']
     flavor_vim_id=None
     if 'uuid' in flavor_dict:
         del flavor_dict['uuid']
     flavor_vim_id=None
-    for vim_id,vim in list(vims.items()):
+    for vim_id,vim in vims.items():
         datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
         flavor_created="false"
         #look at database
         datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
         flavor_created="false"
         #look at database
@@ -809,7 +809,7 @@ def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
         vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd")
         if not vnfd_descriptor_list:
             vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd:vnfd")
         vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd")
         if not vnfd_descriptor_list:
             vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd:vnfd")
-        for vnfd_yang in myvnfd.vnfd_catalog.vnfd.values():
+        for vnfd_yang in myvnfd.vnfd_catalog.vnfd.itervalues():
             vnfd = vnfd_yang.get()
 
             # table vnf
             vnfd = vnfd_yang.get()
 
             # table vnf
@@ -833,7 +833,7 @@ def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
 
             # table nets (internal-vld)
             net_id2uuid = {}  # for mapping interface with network
 
             # table nets (internal-vld)
             net_id2uuid = {}  # for mapping interface with network
-            for vld in vnfd.get("internal-vld").values():
+            for vld in vnfd.get("internal-vld").itervalues():
                 net_uuid = str(uuid4())
                 uuid_list.append(net_uuid)
                 db_net = {
                 net_uuid = str(uuid4())
                 uuid_list.append(net_uuid)
                 db_net = {
@@ -849,7 +849,7 @@ def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
             # table vms (vdus)
             vdu_id2uuid = {}
             vdu_id2db_table_index = {}
             # table vms (vdus)
             vdu_id2uuid = {}
             vdu_id2db_table_index = {}
-            for vdu in vnfd.get("vdu").values():
+            for vdu in vnfd.get("vdu").itervalues():
                 vm_uuid = str(uuid4())
                 uuid_list.append(vm_uuid)
                 db_vm = {
                 vm_uuid = str(uuid4())
                 uuid_list.append(vm_uuid)
                 db_vm = {
@@ -928,7 +928,7 @@ def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
                                     epa_vcpu_set = True
                                 if len(numa_node["paired-threads"].get("paired-thread-ids")):
                                     numa["paired-threads-id"] = []
                                     epa_vcpu_set = True
                                 if len(numa_node["paired-threads"].get("paired-thread-ids")):
                                     numa["paired-threads-id"] = []
-                                    for pair in numa_node["paired-threads"]["paired-thread-ids"].values():
+                                    for pair in numa_node["paired-threads"]["paired-thread-ids"].itervalues():
                                         numa["paired-threads-id"].append(
                                             (str(pair["thread-a"]), str(pair["thread-b"]))
                                         )
                                         numa["paired-threads-id"].append(
                                             (str(pair["thread-a"]), str(pair["thread-b"]))
                                         )
@@ -983,7 +983,7 @@ def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
                             boot_data['boot-data-drive'] = True
                     if vdu["supplemental-boot-data"].get('config-file'):
                         om_cfgfile_list = list()
                             boot_data['boot-data-drive'] = True
                     if vdu["supplemental-boot-data"].get('config-file'):
                         om_cfgfile_list = list()
-                        for custom_config_file in vdu["supplemental-boot-data"]['config-file'].values():
+                        for custom_config_file in vdu["supplemental-boot-data"]['config-file'].itervalues():
                             # TODO Where this file content is present???
                             cfg_source = str(custom_config_file["source"])
                             om_cfgfile_list.append({"dest": custom_config_file["dest"],
                             # TODO Where this file content is present???
                             cfg_source = str(custom_config_file["source"])
                             om_cfgfile_list.append({"dest": custom_config_file["dest"],
@@ -999,7 +999,7 @@ def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
                 cp_name2iface_uuid = {}
                 cp_name2vm_uuid = {}
                 # for iface in chain(vdu.get("internal-interface").itervalues(), vdu.get("external-interface").itervalues()):
                 cp_name2iface_uuid = {}
                 cp_name2vm_uuid = {}
                 # for iface in chain(vdu.get("internal-interface").itervalues(), vdu.get("external-interface").itervalues()):
-                for iface in vdu.get("interface").values():
+                for iface in vdu.get("interface").itervalues():
                     iface_uuid = str(uuid4())
                     uuid_list.append(iface_uuid)
                     db_interface = {
                     iface_uuid = str(uuid4())
                     uuid_list.append(iface_uuid)
                     db_interface = {
@@ -1051,8 +1051,8 @@ def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
                                                 HTTP_Bad_Request)
                     elif iface.get("internal-connection-point-ref"):
                         try:
                                                 HTTP_Bad_Request)
                     elif iface.get("internal-connection-point-ref"):
                         try:
-                            for vld in vnfd.get("internal-vld").values():
-                                for cp in vld.get("internal-connection-point").values():
+                            for vld in vnfd.get("internal-vld").itervalues():
+                                for cp in vld.get("internal-connection-point").itervalues():
                                     if cp.get("id-ref") == iface.get("internal-connection-point-ref"):
                                         db_interface["net_id"] = net_id2uuid[vld.get("id")]
                                         for cp_descriptor in vnfd_descriptor["connection-point"]:
                                     if cp.get("id-ref") == iface.get("internal-connection-point-ref"):
                                         db_interface["net_id"] = net_id2uuid[vld.get("id")]
                                         for cp_descriptor in vnfd_descriptor["connection-point"]:
@@ -1075,9 +1075,9 @@ def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
                     db_interfaces.append(db_interface)
 
             # VNF affinity and antiaffinity
                     db_interfaces.append(db_interface)
 
             # VNF affinity and antiaffinity
-            for pg in vnfd.get("placement-groups").values():
+            for pg in vnfd.get("placement-groups").itervalues():
                 pg_name = get_str(pg, "name", 255)
                 pg_name = get_str(pg, "name", 255)
-                for vdu in pg.get("member-vdus").values():
+                for vdu in pg.get("member-vdus").itervalues():
                     vdu_id = get_str(vdu, "member-vdu-ref", 255)
                     if vdu_id not in vdu_id2db_table_index:
                         raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
                     vdu_id = get_str(vdu, "member-vdu-ref", 255)
                     if vdu_id not in vdu_id2db_table_index:
                         raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
@@ -1427,7 +1427,7 @@ def get_vnf_id(mydb, tenant_id, vnf_id):
 
     vnf_id = vnf["uuid"]
     filter_keys = ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
 
     vnf_id = vnf["uuid"]
     filter_keys = ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
-    filtered_content = dict( (k,v) for k,v in vnf.items() if k in filter_keys )
+    filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
     #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
     data={'vnf' : filtered_content}
     #GET VM
     #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
     data={'vnf' : filtered_content}
     #GET VM
@@ -1580,7 +1580,7 @@ def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
         return result, vims
     elif result == 0:
         return -HTTP_Not_Found, "datacenter '%s' not found" % datacenter_name
         return result, vims
     elif result == 0:
         return -HTTP_Not_Found, "datacenter '%s' not found" % datacenter_name
-    myvim = list(vims.values())[0]
+    myvim = vims.values()[0]
     result,servers =  myvim.get_hosts_info()
     if result < 0:
         return result, servers
     result,servers =  myvim.get_hosts_info()
     if result < 0:
         return result, servers
@@ -1595,7 +1595,7 @@ def get_hosts(mydb, nfvo_tenant_id):
     elif len(vims)>1:
         #print "nfvo.datacenter_action() error. Several datacenters found"
         raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
     elif len(vims)>1:
         #print "nfvo.datacenter_action() error. Several datacenters found"
         raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
-    myvim = list(vims.values())[0]
+    myvim = vims.values()[0]
     try:
         hosts =  myvim.get_hosts()
         logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
     try:
         hosts =  myvim.get_hosts()
         logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
@@ -1643,7 +1643,7 @@ def new_scenario(mydb, tenant_id, topo):
     vnfs={}
     other_nets={}  #external_networks, bridge_networks and data_networkds
     nodes = topo['topology']['nodes']
     vnfs={}
     other_nets={}  #external_networks, bridge_networks and data_networkds
     nodes = topo['topology']['nodes']
-    for k in list(nodes.keys()):
+    for k in nodes.keys():
         if nodes[k]['type'] == 'VNF':
             vnfs[k] = nodes[k]
             vnfs[k]['ifaces'] = {}
         if nodes[k]['type'] == 'VNF':
             vnfs[k] = nodes[k]
             vnfs[k]['ifaces'] = {}
@@ -1656,7 +1656,7 @@ def new_scenario(mydb, tenant_id, topo):
 
 
 #1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
 
 
 #1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
-    for name,vnf in list(vnfs.items()):
+    for name,vnf in vnfs.items():
         where={}
         where_or={"tenant_id": tenant_id, 'public': "true"}
         error_text = ""
         where={}
         where_or={"tenant_id": tenant_id, 'public': "true"}
         error_text = ""
@@ -1692,12 +1692,12 @@ def new_scenario(mydb, tenant_id, topo):
     conections = topo['topology']['connections']
     conections_list = []
     conections_list_name = []
     conections = topo['topology']['connections']
     conections_list = []
     conections_list_name = []
-    for k in list(conections.keys()):
+    for k in conections.keys():
         if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
         if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
-            ifaces_list = list(conections[k]['nodes'].items())
+            ifaces_list = conections[k]['nodes'].items()
         elif type(conections[k]['nodes'])==list: #list with dictionary
             ifaces_list=[]
         elif type(conections[k]['nodes'])==list: #list with dictionary
             ifaces_list=[]
-            conection_pair_list = [list(x.items()) for x in conections[k]['nodes']]
+            conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
             for k2 in conection_pair_list:
                 ifaces_list += k2
 
             for k2 in conection_pair_list:
                 ifaces_list += k2
 
@@ -1761,7 +1761,7 @@ def new_scenario(mydb, tenant_id, topo):
 #                    del con[index]
 #            del other_nets[k]
 #1.7: Check external_ports are present at database table datacenter_nets
 #                    del con[index]
 #            del other_nets[k]
 #1.7: Check external_ports are present at database table datacenter_nets
-    for k,net in list(other_nets.items()):
+    for k,net in other_nets.items():
         error_pos = "'topology':'nodes':'" + k + "'"
         if net['external']==False:
             if 'name' not in net:
         error_pos = "'topology':'nodes':'" + k + "'"
         if net['external']==False:
             if 'name' not in net:
@@ -1809,7 +1809,7 @@ def new_scenario(mydb, tenant_id, topo):
         #print "con", con
         for index in range(0,len(con)):
             #check if this is connected to a external net
         #print "con", con
         for index in range(0,len(con)):
             #check if this is connected to a external net
-            for net_key in list(other_nets.keys()):
+            for net_key in other_nets.keys():
                 if con[index][0]==net_key:
                     if other_net_index>=0:
                         error_text="There is some interface connected both to net '%s' and net '%s'" % (con[other_net_index][0], net_key)
                 if con[index][0]==net_key:
                     if other_net_index>=0:
                         error_text="There is some interface connected both to net '%s' and net '%s'" % (con[other_net_index][0], net_key)
@@ -1880,8 +1880,8 @@ def new_scenario(mydb, tenant_id, topo):
     #1.8.2 check all interfaces from all vnfs
     if len(mgmt_net)>0:
         add_mgmt_net = False
     #1.8.2 check all interfaces from all vnfs
     if len(mgmt_net)>0:
         add_mgmt_net = False
-        for vnf in list(vnfs.values()):
-            for iface in list(vnf['ifaces'].values()):
+        for vnf in vnfs.values():
+            for iface in vnf['ifaces'].values():
                 if iface['type']=='mgmt' and 'net_key' not in iface:
                     #iface not connected
                     iface['net_key'] = 'mgmt'
                 if iface['type']=='mgmt' and 'net_key' not in iface:
                     #iface not connected
                     iface['net_key'] = 'mgmt'
@@ -1922,7 +1922,7 @@ def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
         tenant_id=None
 
     # 1: Check that VNF are present at database table vnfs and update content into scenario dict
         tenant_id=None
 
     # 1: Check that VNF are present at database table vnfs and update content into scenario dict
-    for name,vnf in scenario["vnfs"].items():
+    for name,vnf in scenario["vnfs"].iteritems():
         where={}
         where_or={"tenant_id": tenant_id, 'public': "true"}
         error_text = ""
         where={}
         where_or={"tenant_id": tenant_id, 'public': "true"}
         error_text = ""
@@ -1956,7 +1956,7 @@ def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
         # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
 
     # 2: Insert net_key and ip_address at every vnf interface
         # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
 
     # 2: Insert net_key and ip_address at every vnf interface
-    for net_name, net in list(scenario["networks"].items()):
+    for net_name, net in scenario["networks"].items():
         net_type_bridge = False
         net_type_data = False
         for iface_dict in net["interfaces"]:
         net_type_bridge = False
         net_type_data = False
         for iface_dict in net["interfaces"]:
@@ -1966,7 +1966,7 @@ def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
             elif version == "0.3":
                 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
                 ip_address = iface_dict.get('ip_address', None)
             elif version == "0.3":
                 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
                 ip_address = iface_dict.get('ip_address', None)
-            for vnf, iface in list(temp_dict.items()):
+            for vnf, iface in temp_dict.items():
                 if vnf not in scenario["vnfs"]:
                     error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
                         net_name, vnf)
                 if vnf not in scenario["vnfs"]:
                     error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
                         net_name, vnf)
@@ -2054,7 +2054,7 @@ def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
         db_ip_profiles_index = 0
         uuid_list = []
         nsd_uuid_list = []
         db_ip_profiles_index = 0
         uuid_list = []
         nsd_uuid_list = []
-        for nsd_yang in mynsd.nsd_catalog.nsd.values():
+        for nsd_yang in mynsd.nsd_catalog.nsd.itervalues():
             nsd = nsd_yang.get()
 
             # table sceanrios
             nsd = nsd_yang.get()
 
             # table sceanrios
@@ -2076,7 +2076,7 @@ def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
             # table sce_vnfs (constituent-vnfd)
             vnf_index2scevnf_uuid = {}
             vnf_index2vnf_uuid = {}
             # table sce_vnfs (constituent-vnfd)
             vnf_index2scevnf_uuid = {}
             vnf_index2vnf_uuid = {}
-            for vnf in nsd.get("constituent-vnfd").values():
+            for vnf in nsd.get("constituent-vnfd").itervalues():
                 existing_vnf = mydb.get_rows(FROM="vnfs", WHERE={'osm_id': str(vnf["vnfd-id-ref"])[:255],
                                                                       'tenant_id': tenant_id})
                 if not existing_vnf:
                 existing_vnf = mydb.get_rows(FROM="vnfs", WHERE={'osm_id': str(vnf["vnfd-id-ref"])[:255],
                                                                       'tenant_id': tenant_id})
                 if not existing_vnf:
@@ -2100,7 +2100,7 @@ def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
 
             # table ip_profiles (ip-profiles)
             ip_profile_name2db_table_index = {}
 
             # table ip_profiles (ip-profiles)
             ip_profile_name2db_table_index = {}
-            for ip_profile in nsd.get("ip-profiles").values():
+            for ip_profile in nsd.get("ip-profiles").itervalues():
                 db_ip_profile = {
                     "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
                     "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
                 db_ip_profile = {
                     "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
                     "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
@@ -2110,7 +2110,7 @@ def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
                     "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
                 }
                 dns_list = []
                     "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
                 }
                 dns_list = []
-                for dns in ip_profile["ip-profile-params"]["dns-server"].values():
+                for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
                     dns_list.append(str(dns.get("address")))
                 db_ip_profile["dns_address"] = ";".join(dns_list)
                 if ip_profile["ip-profile-params"].get('security-group'):
                     dns_list.append(str(dns.get("address")))
                 db_ip_profile["dns_address"] = ";".join(dns_list)
                 if ip_profile["ip-profile-params"].get('security-group'):
@@ -2120,7 +2120,7 @@ def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
                 db_ip_profiles.append(db_ip_profile)
 
             # table sce_nets (internal-vld)
                 db_ip_profiles.append(db_ip_profile)
 
             # table sce_nets (internal-vld)
-            for vld in nsd.get("vld").values():
+            for vld in nsd.get("vld").itervalues():
                 sce_net_uuid = str(uuid4())
                 uuid_list.append(sce_net_uuid)
                 db_sce_net = {
                 sce_net_uuid = str(uuid4())
                 uuid_list.append(sce_net_uuid)
                 db_sce_net = {
@@ -2153,7 +2153,7 @@ def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
                     db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["sce_net_id"] = sce_net_uuid
 
                 # table sce_interfaces (vld:vnfd-connection-point-ref)
                     db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["sce_net_id"] = sce_net_uuid
 
                 # table sce_interfaces (vld:vnfd-connection-point-ref)
-                for iface in vld.get("vnfd-connection-point-ref").values():
+                for iface in vld.get("vnfd-connection-point-ref").itervalues():
                     vnf_index = int(iface['member-vnf-index-ref'])
                     # check correct parameters
                     if vnf_index not in vnf_index2vnf_uuid:
                     vnf_index = int(iface['member-vnf-index-ref'])
                     # check correct parameters
                     if vnf_index not in vnf_index2vnf_uuid:
@@ -2592,13 +2592,13 @@ def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extr
     elif len(vims)>1:
         #print "nfvo.datacenter_action() error. Several datacenters found"
         raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
     elif len(vims)>1:
         #print "nfvo.datacenter_action() error. Several datacenters found"
         raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
-    return list(vims.keys())[0], list(vims.values())[0]
+    return vims.keys()[0], vims.values()[0]
 
 
 def update(d, u):
     '''Takes dict d and updates it with the values in dict u.'''
     '''It merges all depth levels'''
 
 
 def update(d, u):
     '''Takes dict d and updates it with the values in dict u.'''
     '''It merges all depth levels'''
-    for k, v in u.items():
+    for k, v in u.iteritems():
         if isinstance(v, collections.Mapping):
             r = update(d.get(k, {}), v)
             d[k] = r
         if isinstance(v, collections.Mapping):
             r = update(d.get(k, {}), v)
             d[k] = r
@@ -2670,7 +2670,7 @@ def create_instance(mydb, tenant_id, instance_dict):
     #               yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
     try:
         # 0 check correct parameters
     #               yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
     try:
         # 0 check correct parameters
-        for net_name, net_instance_desc in instance_dict.get("networks", {}).items():
+        for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
             found = False
             for scenario_net in scenarioDict['nets']:
                 if net_name == scenario_net["name"]:
             found = False
             for scenario_net in scenarioDict['nets']:
                 if net_name == scenario_net["name"]:
@@ -2698,7 +2698,7 @@ def create_instance(mydb, tenant_id, instance_dict):
                     site_without_datacenter_field = True
                     site["datacenter"] = default_datacenter_id   # change name to id
 
                     site_without_datacenter_field = True
                     site["datacenter"] = default_datacenter_id   # change name to id
 
-        for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).items():
+        for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
             found = False
             for scenario_vnf in scenarioDict['vnfs']:
                 if vnf_name == scenario_vnf['name']:
             found = False
             for scenario_vnf in scenarioDict['vnfs']:
                 if vnf_name == scenario_vnf['name']:
@@ -2725,7 +2725,7 @@ def create_instance(mydb, tenant_id, instance_dict):
         # 0.2 merge instance information into scenario
         # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
         # However, this is not possible yet.
         # 0.2 merge instance information into scenario
         # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
         # However, this is not possible yet.
-        for net_name, net_instance_desc in instance_dict.get("networks",{}).items():
+        for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
             for scenario_net in scenarioDict['nets']:
                 if net_name == scenario_net["name"]:
                     if 'ip-profile' in net_instance_desc:
             for scenario_net in scenarioDict['nets']:
                 if net_name == scenario_net["name"]:
                     if 'ip-profile' in net_instance_desc:
@@ -3185,7 +3185,7 @@ def create_instance(mydb, tenant_id, instance_dict):
         logger.debug("create_instance done DB tables: %s",
                     yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
         mydb.new_rows(db_tables, uuid_list)
         logger.debug("create_instance done DB tables: %s",
                     yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
         mydb.new_rows(db_tables, uuid_list)
-        for myvim_thread_id in list(myvim_threads_id.values()):
+        for myvim_thread_id in myvim_threads_id.values():
             vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
 
         returned_instance = mydb.get_instance_scenario(instance_uuid)
             vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
 
         returned_instance = mydb.get_instance_scenario(instance_uuid)
@@ -3250,7 +3250,7 @@ def delete_instance(mydb, tenant_id, instance_id):
                                                                                         sce_vnf["datacenter_tenant_id"]))
                 myvims[datacenter_key] = None
             else:
                                                                                         sce_vnf["datacenter_tenant_id"]))
                 myvims[datacenter_key] = None
             else:
-                myvims[datacenter_key] = list(vims.values())[0]
+                myvims[datacenter_key] = vims.values()[0]
         myvim = myvims[datacenter_key]
         myvim_thread = myvim_threads[datacenter_key]
         for vm in sce_vnf['vms']:
         myvim = myvims[datacenter_key]
         myvim_thread = myvim_threads[datacenter_key]
         for vm in sce_vnf['vms']:
@@ -3302,7 +3302,7 @@ def delete_instance(mydb, tenant_id, instance_id):
                 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
                 myvims[datacenter_key] = None
             else:
                 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
                 myvims[datacenter_key] = None
             else:
-                myvims[datacenter_key] = list(vims.values())[0]
+                myvims[datacenter_key] = vims.values()[0]
         myvim = myvims[datacenter_key]
         myvim_thread = myvim_threads[datacenter_key]
 
         myvim = myvims[datacenter_key]
         myvim_thread = myvim_threads[datacenter_key]
 
@@ -3344,7 +3344,7 @@ def delete_instance(mydb, tenant_id, instance_id):
     logger.debug("delete_instance done DB tables: %s",
                  yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
     mydb.new_rows(db_tables, ())
     logger.debug("delete_instance done DB tables: %s",
                  yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
     mydb.new_rows(db_tables, ())
-    for myvim_thread_id in list(vimthread_affected.keys()):
+    for myvim_thread_id in vimthread_affected.keys():
         vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
 
     if len(error_msg) > 0:
         vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
 
     if len(error_msg) > 0:
@@ -3527,7 +3527,7 @@ def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
     vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
     if len(vims) == 0:
         raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
     vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
     if len(vims) == 0:
         raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
-    myvim = list(vims.values())[0]
+    myvim = vims.values()[0]
 
     if action_dict.get("create-vdu"):
         for vdu in action_dict["create-vdu"]:
 
     if action_dict.get("create-vdu"):
         for vdu in action_dict["create-vdu"]:
@@ -4199,12 +4199,12 @@ def vim_action_get(mydb, tenant_id, datacenter, item, name):
         if name and len(content)==1:
             return {item[:-1]: content[0]}
         elif name and len(content)==0:
         if name and len(content)==1:
             return {item[:-1]: content[0]}
         elif name and len(content)==0:
-            raise NfvoException("No {} found with ".format(item[:-1]) + " and ".join([str(x[0])+": "+str(x[1]) for x in iter(filter_dict.items())]),
+            raise NfvoException("No {} found with ".format(item[:-1]) + " and ".join(map(lambda x: str(x[0])+": "+str(x[1]), filter_dict.iteritems())),
                  datacenter)
         else:
             return {item: content}
     except vimconn.vimconnException as e:
                  datacenter)
         else:
             return {item: content}
     except vimconn.vimconnException as e:
-        print("vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e)))
+        print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
         raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
 
 
         raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
 
 
@@ -4217,7 +4217,7 @@ def vim_action_delete(mydb, tenant_id, datacenter, item, name):
     #get uuid name
     content = vim_action_get(mydb, tenant_id, datacenter, item, name)
     logger.debug("vim_action_delete vim response: " + str(content))
     #get uuid name
     content = vim_action_get(mydb, tenant_id, datacenter, item, name)
     logger.debug("vim_action_delete vim response: " + str(content))
-    items = list(content.values())[0]
+    items = content.values()[0]
     if type(items)==list and len(items)==0:
         raise NfvoException("Not found " + item, HTTP_Not_Found)
     elif type(items)==list and len(items)>1:
     if type(items)==list and len(items)==0:
         raise NfvoException("Not found " + item, HTTP_Not_Found)
     elif type(items)==list and len(items)>1:
index 25196dd..f47ad16 100644 (file)
@@ -27,7 +27,7 @@ NFVO DB engine. It implements all the methods to interact with the Openmano Data
 __author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
 __date__ ="$28-aug-2014 10:05:01$"
 
 __author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
 __date__ ="$28-aug-2014 10:05:01$"
 
-from . import db_base
+import db_base
 import MySQLdb as mdb
 import json
 import yaml
 import MySQLdb as mdb
 import json
 import yaml
@@ -66,7 +66,7 @@ class nfvo_db(db_base.db_base):
                     #print "Adding new vms to the NFVO database"
                     #For each vm, we must create the appropriate vm in the NFVO database.
                     vmDict = {}
                     #print "Adding new vms to the NFVO database"
                     #For each vm, we must create the appropriate vm in the NFVO database.
                     vmDict = {}
-                    for _,vm in VNFCDict.items():
+                    for _,vm in VNFCDict.iteritems():
                         #This code could make the name of the vms grow and grow.
                         #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name  
                         #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
                         #This code could make the name of the vms grow and grow.
                         #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name  
                         #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
@@ -218,7 +218,7 @@ class nfvo_db(db_base.db_base):
                     #print "Adding new vms to the NFVO database"
                     #For each vm, we must create the appropriate vm in the NFVO database.
                     vmDict = {}
                     #print "Adding new vms to the NFVO database"
                     #For each vm, we must create the appropriate vm in the NFVO database.
                     vmDict = {}
-                    for _,vm in VNFCDict.items():
+                    for _,vm in VNFCDict.iteritems():
                         #This code could make the name of the vms grow and grow.
                         #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name  
                         #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
                         #This code could make the name of the vms grow and grow.
                         #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name  
                         #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
@@ -389,7 +389,7 @@ class nfvo_db(db_base.db_base):
                     
                     scenario_uuid =  self._new_row_internal('scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
                     #sce_nets
                     
                     scenario_uuid =  self._new_row_internal('scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
                     #sce_nets
-                    for net in list(scenario_dict['nets'].values()):
+                    for net in scenario_dict['nets'].values():
                         net_dict={'scenario_id': scenario_uuid}
                         net_dict["name"] = net["name"]
                         net_dict["type"] = net["type"]
                         net_dict={'scenario_id': scenario_uuid}
                         net_dict["name"] = net["name"]
                         net_dict["type"] = net["type"]
@@ -418,7 +418,7 @@ class nfvo_db(db_base.db_base):
                             self._new_row_internal('ip_profiles', myIPProfileDict)
 
                     # sce_vnfs
                             self._new_row_internal('ip_profiles', myIPProfileDict)
 
                     # sce_vnfs
-                    for k, vnf in list(scenario_dict['vnfs'].items()):
+                    for k, vnf in scenario_dict['vnfs'].items():
                         INSERT_ = {'scenario_id': scenario_uuid,
                                    'name': k,
                                    'vnf_id': vnf['uuid'],
                         INSERT_ = {'scenario_id': scenario_uuid,
                                    'name': k,
                                    'vnf_id': vnf['uuid'],
@@ -433,7 +433,7 @@ class nfvo_db(db_base.db_base):
                                                               root_uuid=scenario_uuid, created_time=created_time)
                         vnf['scn_vnf_uuid']=scn_vnf_uuid
                         # sce_interfaces
                                                               root_uuid=scenario_uuid, created_time=created_time)
                         vnf['scn_vnf_uuid']=scn_vnf_uuid
                         # sce_interfaces
-                        for iface in list(vnf['ifaces'].values()):
+                        for iface in vnf['ifaces'].values():
                             # print 'iface', iface
                             if 'net_key' not in iface:
                                 continue
                             # print 'iface', iface
                             if 'net_key' not in iface:
                                 continue
@@ -488,7 +488,7 @@ class nfvo_db(db_base.db_base):
                         WHERE_={'tenant_id': tenant_id, 'uuid': scenario_uuid}
                         item_changed += self._update_rows('scenarios', UPDATE_, WHERE_, modified_time=modified_time)
                     #sce_nets
                         WHERE_={'tenant_id': tenant_id, 'uuid': scenario_uuid}
                         item_changed += self._update_rows('scenarios', UPDATE_, WHERE_, modified_time=modified_time)
                     #sce_nets
-                    for node_id, node in list(nodes.items()):
+                    for node_id, node in nodes.items():
                         if "graph" in node:
                             #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
                             #TODO, must be json because of the GUI, change to yaml
                         if "graph" in node:
                             #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
                             #TODO, must be json because of the GUI, change to yaml
@@ -759,7 +759,7 @@ class nfvo_db(db_base.db_base):
                 with self.con:
                     self.cur = self.con.cursor()
                     for table in tables:
                 with self.con:
                     self.cur = self.con.cursor()
                     for table in tables:
-                        for table_name, row_list in list(table.items()):
+                        for table_name, row_list in table.items():
                             index = 0
                             if isinstance(row_list, dict):
                                 row_list = (row_list, )  #create a list with the single value
                             index = 0
                             if isinstance(row_list, dict):
                                 row_list = (row_list, )  #create a list with the single value
@@ -810,7 +810,7 @@ class nfvo_db(db_base.db_base):
                             net["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id: net['vim_id']}
                         sce_net_id = net.get("uuid")
                         
                             net["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id: net['vim_id']}
                         sce_net_id = net.get("uuid")
                         
-                        for datacenter_site_id,vim_id in net["vim_id_sites"].items():
+                        for datacenter_site_id,vim_id in net["vim_id_sites"].iteritems():
                             INSERT_={'vim_net_id': vim_id, 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #,  'type': net['type']
                             INSERT_['datacenter_id'] = datacenter_site_id 
                             INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
                             INSERT_={'vim_net_id': vim_id, 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #,  'type': net['type']
                             INSERT_['datacenter_id'] = datacenter_site_id 
                             INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
index 07aead3..1566203 100644 (file)
@@ -40,7 +40,7 @@ version_date = "Oct 2017"
 if sys.version_info.major == 3:
     from urllib.parse import quote
 elif sys.version_info.major == 2:
 if sys.version_info.major == 3:
     from urllib.parse import quote
 elif sys.version_info.major == 2:
-    from urllib.parse import quote
+    from urllib import quote
 
 class OpenmanoException(Exception):
     '''Common Exception for all openmano client exceptions'''
 
 class OpenmanoException(Exception):
     '''Common Exception for all openmano client exceptions'''
index 20646a1..00f6f2d 100644 (file)
@@ -62,7 +62,7 @@ def format_in(http_response, schema):
         #print "Input data: ", str(client_data)
         return True, client_data
     except js_e.ValidationError as exc:
         #print "Input data: ", str(client_data)
         return True, client_data
     except js_e.ValidationError as exc:
-        print("validate_in error, jsonschema exception ", exc.message, "at", exc.path)
+        print "validate_in error, jsonschema exception ", exc.message, "at", exc.path
         return False, ("validate_in error, jsonschema exception ", exc.message, "at", exc.path)
 
 def remove_extra_items(data, schema):
         return False, ("validate_in error, jsonschema exception ", exc.message, "at", exc.path)
 
 def remove_extra_items(data, schema):
@@ -75,8 +75,8 @@ def remove_extra_items(data, schema):
         #TODO deal with patternProperties
         if 'properties' not in schema:
             return None
         #TODO deal with patternProperties
         if 'properties' not in schema:
             return None
-        for k in list(data.keys()):
-            if k not in list(schema['properties'].keys()):
+        for k in data.keys():
+            if k not in schema['properties'].keys():
                 del data[k]
                 deleted.append(k)
             else:
                 del data[k]
                 deleted.append(k)
             else:
@@ -102,7 +102,7 @@ def convert_bandwidth(data, reverse=False):
         None
     '''
     if type(data) is dict:
         None
     '''
     if type(data) is dict:
-        for k in list(data.keys()):
+        for k in data.keys():
             if type(data[k]) is dict or type(data[k]) is tuple or type(data[k]) is list:
                 convert_bandwidth(data[k], reverse)
         if "bandwidth" in data:
             if type(data[k]) is dict or type(data[k]) is tuple or type(data[k]) is list:
                 convert_bandwidth(data[k], reverse)
         if "bandwidth" in data:
@@ -119,7 +119,7 @@ def convert_bandwidth(data, reverse=False):
                     if value % 1000 == 0: data["bandwidth"]=str(value/1000) + " Gbps"
                     else: data["bandwidth"]=str(value) + " Mbps"
             except:
                     if value % 1000 == 0: data["bandwidth"]=str(value/1000) + " Gbps"
                     else: data["bandwidth"]=str(value) + " Mbps"
             except:
-                print("convert_bandwidth exception for type", type(data["bandwidth"]), " data", data["bandwidth"])
+                print "convert_bandwidth exception for type", type(data["bandwidth"]), " data", data["bandwidth"]
                 return
     if type(data) is tuple or type(data) is list:
         for k in data:
                 return
     if type(data) is tuple or type(data) is list:
         for k in data:
@@ -133,7 +133,7 @@ def convert_datetime2str(var):
     It enters recursively in the dict var finding this kind of variables
     '''
     if type(var) is dict:
     It enters recursively in the dict var finding this kind of variables
     '''
     if type(var) is dict:
-        for k,v in list(var.items()):
+        for k,v in var.items():
             if type(v) is datetime.datetime:
                 var[k]= v.strftime('%Y-%m-%dT%H:%M:%S')
             elif type(v) is dict or type(v) is list or type(v) is tuple: 
             if type(v) is datetime.datetime:
                 var[k]= v.strftime('%Y-%m-%dT%H:%M:%S')
             elif type(v) is dict or type(v) is list or type(v) is tuple: 
@@ -153,7 +153,7 @@ def convert_str2boolean(data, items):
         None
     '''
     if type(data) is dict:
         None
     '''
     if type(data) is dict:
-        for k in list(data.keys()):
+        for k in data.keys():
             if type(data[k]) is dict or type(data[k]) is tuple or type(data[k]) is list:
                 convert_str2boolean(data[k], items)
             if k in items:
             if type(data[k]) is dict or type(data[k]) is tuple or type(data[k]) is list:
                 convert_str2boolean(data[k], items)
             if k in items:
index 8ce029f..22a882e 100644 (file)
@@ -57,11 +57,11 @@ The task content are (M: stored at memory, D: stored at database):
 
 import threading
 import time
 
 import threading
 import time
-import queue
+import Queue
 import logging
 import logging
-from . import vimconn
+import vimconn
 import yaml
 import yaml
-from .db_base import db_base_Exception
+from db_base import db_base_Exception
 from lib_osm_openvim.ovim import ovimException
 
 __author__ = "Alfonso Tierno, Pablo Montes"
 from lib_osm_openvim.ovim import ovimException
 
 __author__ = "Alfonso Tierno, Pablo Montes"
@@ -116,7 +116,7 @@ class vim_thread(threading.Thread):
         self.db_lock = db_lock
 
         self.task_lock = task_lock
         self.db_lock = db_lock
 
         self.task_lock = task_lock
-        self.task_queue = queue.Queue(2000)
+        self.task_queue = Queue.Queue(2000)
 
         self.refresh_tasks = []
         """Contains time ordered task list for refreshing the status of VIM VMs and nets"""
 
         self.refresh_tasks = []
         """Contains time ordered task list for refreshing the status of VIM VMs and nets"""
@@ -206,7 +206,7 @@ class vim_thread(threading.Thread):
             try:
                 now = time.time()
                 vim_dict = self.vim.refresh_vms_status(vm_to_refresh_list)
             try:
                 now = time.time()
                 vim_dict = self.vim.refresh_vms_status(vm_to_refresh_list)
-                for vim_id, vim_info in list(vim_dict.items()):
+                for vim_id, vim_info in vim_dict.items():
                     # look for task
                     task_need_update = False
                     task = vm_to_refresh_dict[vim_id]
                     # look for task
                     task_need_update = False
                     task = vm_to_refresh_dict[vim_id]
@@ -309,7 +309,7 @@ class vim_thread(threading.Thread):
             try:
                 now = time.time()
                 vim_dict = self.vim.refresh_nets_status(net_to_refresh_list)
             try:
                 now = time.time()
                 vim_dict = self.vim.refresh_nets_status(net_to_refresh_list)
-                for vim_id, vim_info in list(vim_dict.items()):
+                for vim_id, vim_info in vim_dict.items():
                     # look for task
                     task = net_to_refresh_dict[vim_id]
                     self.logger.debug("get-net net_id=%s result=%s", task["vim_id"], str(vim_info))
                     # look for task
                     task = net_to_refresh_dict[vim_id]
                     self.logger.debug("get-net net_id=%s result=%s", task["vim_id"], str(vim_info))
@@ -557,7 +557,7 @@ class vim_thread(threading.Thread):
         try:
             self.task_queue.put(task, False)
             return None
         try:
             self.task_queue.put(task, False)
             return None
-        except queue.Full:
+        except Queue.Full:
             raise vimconn.vimconnException(self.name + ": timeout inserting a task")
 
     def del_task(self, task):
             raise vimconn.vimconnException(self.name + ": timeout inserting a task")
 
     def del_task(self, task):
@@ -688,7 +688,7 @@ class vim_thread(threading.Thread):
         vm_vim_id = task["vim_id"]
         interfaces = task["extra"].get("interfaces", ())
         try:
         vm_vim_id = task["vim_id"]
         interfaces = task["extra"].get("interfaces", ())
         try:
-            for iface in list(interfaces.values()):
+            for iface in interfaces.values():
                 if iface.get("sdn_port_id"):
                     try:
                         with self.db_lock:
                 if iface.get("sdn_port_id"):
                     try:
                         with self.db_lock:
index ba3b1e2..d892166 100644 (file)
@@ -28,25 +28,25 @@ vimconn implement an Abstract class for the vim connector plugins
 __author__="Alfonso Tierno, Igor D.C."
 __date__ ="$14-aug-2017 23:59:59$"
 
 __author__="Alfonso Tierno, Igor D.C."
 __date__ ="$14-aug-2017 23:59:59$"
 
+import io
 import logging
 import paramiko
 import socket
 import logging
 import paramiko
 import socket
-import io
 import yaml
 import sys
 from email.mime.multipart import MIMEMultipart
 from email.mime.text import MIMEText
 
 import yaml
 import sys
 from email.mime.multipart import MIMEMultipart
 from email.mime.text import MIMEText
 
-#Error variables 
+#Error variables
 HTTP_Bad_Request = 400
 HTTP_Bad_Request = 400
-HTTP_Unauthorized = 401 
-HTTP_Not_Found = 404 
-HTTP_Method_Not_Allowed = 405 
+HTTP_Unauthorized = 401
+HTTP_Not_Found = 404
+HTTP_Method_Not_Allowed = 405
 HTTP_Request_Timeout = 408
 HTTP_Conflict = 409
 HTTP_Not_Implemented = 501
 HTTP_Request_Timeout = 408
 HTTP_Conflict = 409
 HTTP_Not_Implemented = 501
-HTTP_Service_Unavailable = 503 
-HTTP_Internal_Server_Error = 500 
+HTTP_Service_Unavailable = 503
+HTTP_Internal_Server_Error = 500
 
 class vimconnException(Exception):
     """Common and base class Exception for all vimconnector exceptions"""
 
 class vimconnException(Exception):
     """Common and base class Exception for all vimconnector exceptions"""
@@ -58,7 +58,7 @@ class vimconnConnectionException(vimconnException):
     """Connectivity error with the VIM"""
     def __init__(self, message, http_code=HTTP_Service_Unavailable):
         vimconnException.__init__(self, message, http_code)
     """Connectivity error with the VIM"""
     def __init__(self, message, http_code=HTTP_Service_Unavailable):
         vimconnException.__init__(self, message, http_code)
-    
+
 class vimconnUnexpectedResponse(vimconnException):
     """Get an wrong response from VIM"""
     def __init__(self, message, http_code=HTTP_Service_Unavailable):
 class vimconnUnexpectedResponse(vimconnException):
     """Get an wrong response from VIM"""
     def __init__(self, message, http_code=HTTP_Service_Unavailable):
@@ -92,9 +92,9 @@ class vimconnNotImplemented(vimconnException):
 
 class vimconnector():
     """Abstract base class for all the VIM connector plugins
 
 class vimconnector():
     """Abstract base class for all the VIM connector plugins
-    These plugins must implement a vimconnector class derived from this 
+    These plugins must implement a vimconnector class derived from this
     and all these privated methods
     and all these privated methods
-    """ 
+    """
     def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None, log_level=None,
                  config={}, persitent_info={}):
         """Constructor of VIM
     def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None, log_level=None,
                  config={}, persitent_info={}):
         """Constructor of VIM
@@ -127,9 +127,9 @@ class vimconnector():
         self.logger = logging.getLogger('openmano.vim')
         if log_level:
             self.logger.setLevel( getattr(logging, log_level) )
         self.logger = logging.getLogger('openmano.vim')
         if log_level:
             self.logger.setLevel( getattr(logging, log_level) )
-        if not self.url_admin:  #try to use normal url 
+        if not self.url_admin:  #try to use normal url
             self.url_admin = self.url
             self.url_admin = self.url
-    
+
     def __getitem__(self,index):
         if index=='tenant_id':
             return self.tenant_id
     def __getitem__(self,index):
         if index=='tenant_id':
             return self.tenant_id
@@ -151,7 +151,7 @@ class vimconnector():
             return self.config
         else:
             raise KeyError("Invalid key '%s'" %str(index))
             return self.config
         else:
             raise KeyError("Invalid key '%s'" %str(index))
-        
+
     def __setitem__(self,index, value):
         if index=='tenant_id':
             self.tenant_id = value
     def __setitem__(self,index, value):
         if index=='tenant_id':
             self.tenant_id = value
@@ -429,7 +429,7 @@ class vimconnector():
                           - name: interface name
                             dedicated: yes|no|yes:sriov;  for PT, SRIOV or only one SRIOV for the physical NIC
                             bandwidth: X Gbps; requested guarantee bandwidth
                           - name: interface name
                             dedicated: yes|no|yes:sriov;  for PT, SRIOV or only one SRIOV for the physical NIC
                             bandwidth: X Gbps; requested guarantee bandwidth
-                            vpci: requested virtual PCI address   
+                            vpci: requested virtual PCI address
                 disk: disk size
                 is_public:
                  #TODO to concrete
                 disk: disk size
                 is_public:
                  #TODO to concrete
@@ -457,7 +457,7 @@ class vimconnector():
            Returns the image_id or raises a vimconnNotFoundException
         """
         raise vimconnNotImplemented( "Should have implemented this" )
            Returns the image_id or raises a vimconnNotFoundException
         """
         raise vimconnNotImplemented( "Should have implemented this" )
-        
+
     def get_image_list(self, filter_dict={}):
         """Obtain tenant images from VIM
         Filter_dict can be:
     def get_image_list(self, filter_dict={}):
         """Obtain tenant images from VIM
         Filter_dict can be:
@@ -522,11 +522,11 @@ class vimconnector():
         Returns the instance identifier or raises an exception on error
         """
         raise vimconnNotImplemented( "Should have implemented this" )
         Returns the instance identifier or raises an exception on error
         """
         raise vimconnNotImplemented( "Should have implemented this" )
-        
+
     def get_vminstance(self,vm_id):
         """Returns the VM instance information from VIM"""
         raise vimconnNotImplemented( "Should have implemented this" )
     def get_vminstance(self,vm_id):
         """Returns the VM instance information from VIM"""
         raise vimconnNotImplemented( "Should have implemented this" )
-        
+
     def delete_vminstance(self, vm_id):
         """Removes a VM instance from VIM
         Returns the instance identifier"""
     def delete_vminstance(self, vm_id):
         """Removes a VM instance from VIM
         Returns the instance identifier"""
@@ -539,14 +539,14 @@ class vimconnector():
                 vm_id:          #VIM id of this Virtual Machine
                     status:     #Mandatory. Text with one of:
                                 #  DELETED (not found at vim)
                 vm_id:          #VIM id of this Virtual Machine
                     status:     #Mandatory. Text with one of:
                                 #  DELETED (not found at vim)
-                                #  VIM_ERROR (Cannot connect to VIM, VIM response error, ...) 
+                                #  VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
                                 #  OTHER (Vim reported other status not understood)
                                 #  ERROR (VIM indicates an ERROR status)
                                 #  OTHER (Vim reported other status not understood)
                                 #  ERROR (VIM indicates an ERROR status)
-                                #  ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running), 
+                                #  ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
                                 #  BUILD (on building process), ERROR
                                 #  ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
                                 #
                                 #  BUILD (on building process), ERROR
                                 #  ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
                                 #
-                    error_msg:  #Text with VIM error message, if any. Or the VIM connection ERROR 
+                    error_msg:  #Text with VIM error message, if any. Or the VIM connection ERROR
                     vim_info:   #Text with plain information obtained from vim (yaml.safe_dump)
                     interfaces: list with interface info. Each item a dictionary with:
                         vim_info:         #Text with plain information obtained from vim (yaml.safe_dump)
                     vim_info:   #Text with plain information obtained from vim (yaml.safe_dump)
                     interfaces: list with interface info. Each item a dictionary with:
                         vim_info:         #Text with plain information obtained from vim (yaml.safe_dump)
@@ -559,25 +559,25 @@ class vimconnector():
                         vlan:             #physical VLAN used for VF
         """
         raise vimconnNotImplemented( "Should have implemented this" )
                         vlan:             #physical VLAN used for VF
         """
         raise vimconnNotImplemented( "Should have implemented this" )
-    
+
     def action_vminstance(self, vm_id, action_dict):
         """Send and action over a VM instance from VIM
         Returns the vm_id if the action was successfully sent to the VIM"""
         raise vimconnNotImplemented( "Should have implemented this" )
     def action_vminstance(self, vm_id, action_dict):
         """Send and action over a VM instance from VIM
         Returns the vm_id if the action was successfully sent to the VIM"""
         raise vimconnNotImplemented( "Should have implemented this" )
-    
+
     def get_vminstance_console(self, vm_id, console_type="vnc"):
         """
         Get a console for the virtual machine
         Params:
             vm_id: uuid of the VM
             console_type, can be:
     def get_vminstance_console(self, vm_id, console_type="vnc"):
         """
         Get a console for the virtual machine
         Params:
             vm_id: uuid of the VM
             console_type, can be:
-                "novnc" (by default), "xvpvnc" for VNC types, 
+                "novnc" (by default), "xvpvnc" for VNC types,
                 "rdp-html5" for RDP types, "spice-html5" for SPICE types
         Returns dict with the console parameters:
                 protocol: ssh, ftp, http, https, ...
                 "rdp-html5" for RDP types, "spice-html5" for SPICE types
         Returns dict with the console parameters:
                 protocol: ssh, ftp, http, https, ...
-                server:   usually ip address 
-                port:     the http, ssh, ... port 
-                suffix:   extra text, e.g. the http path and query string   
+                server:   usually ip address
+                port:     the http, ssh, ... port
+                suffix:   extra text, e.g. the http path and query string
         """
         raise vimconnNotImplemented( "Should have implemented this" )
 
         """
         raise vimconnNotImplemented( "Should have implemented this" )
 
@@ -840,17 +840,17 @@ class vimconnector():
     def get_processor_rankings(self):
         """Get the processor rankings in the VIM database"""
         raise vimconnNotImplemented( "Should have implemented this" )
     def get_processor_rankings(self):
         """Get the processor rankings in the VIM database"""
         raise vimconnNotImplemented( "Should have implemented this" )
-    
+
     def new_host(self, host_data):
         """Adds a new host to VIM"""
         """Returns status code of the VIM response"""
         raise vimconnNotImplemented( "Should have implemented this" )
     def new_host(self, host_data):
         """Adds a new host to VIM"""
         """Returns status code of the VIM response"""
         raise vimconnNotImplemented( "Should have implemented this" )
-    
+
     def new_external_port(self, port_data):
         """Adds a external port to VIM"""
         """Returns the port identifier"""
         raise vimconnNotImplemented( "Should have implemented this" )
     def new_external_port(self, port_data):
         """Adds a external port to VIM"""
         """Returns the port identifier"""
         raise vimconnNotImplemented( "Should have implemented this" )
-        
+
     def new_external_network(self,net_name,net_type):
         """Adds a external network to VIM (shared)"""
         """Returns the network identifier"""
     def new_external_network(self,net_name,net_type):
         """Adds a external network to VIM (shared)"""
         """Returns the network identifier"""
@@ -865,4 +865,3 @@ class vimconnector():
         """Adds a VM instance to VIM"""
         """Returns the instance identifier"""
         raise vimconnNotImplemented( "Should have implemented this" )
         """Adds a VM instance to VIM"""
         """Returns the instance identifier"""
         raise vimconnNotImplemented( "Should have implemented this" )
-
index 9b13030..3ccef44 100644 (file)
@@ -28,7 +28,7 @@ AWS-connector implements all the methods to interact with AWS using the BOTO cli
 __author__ = "Saboor Ahmad"
 __date__ = "10-Apr-2017"
 
 __author__ = "Saboor Ahmad"
 __date__ = "10-Apr-2017"
 
-from . import vimconn
+import vimconn
 import yaml
 import logging
 import netaddr
 import yaml
 import logging
 import netaddr
@@ -275,7 +275,7 @@ class vimconnector(vimconn.vimconnector):
             pub_subs = pub_split[:3]
             subnets = pub_subs + pri_subs
 
             pub_subs = pub_split[:3]
             subnets = pub_subs + pri_subs
 
-        return list(map(str, subnets))
+        return map(str, subnets)
 
     def new_network(self, net_name, net_type, ip_profile=None, shared=False, vlan=None):
         """Adds a tenant network to VIM
 
     def new_network(self, net_name, net_type, ip_profile=None, shared=False, vlan=None):
         """Adds a tenant network to VIM
@@ -470,7 +470,7 @@ class vimconnector(vimconn.vimconnector):
         self.logger.debug("Getting flavor id from data")
         try:
             flavor = None
         self.logger.debug("Getting flavor id from data")
         try:
             flavor = None
-            for key, values in self.flavor_info.items():
+            for key, values in self.flavor_info.iteritems():
                 if (values["ram"], values["cpus"], values["disk"]) == (
                 flavor_dict["ram"], flavor_dict["vcpus"], flavor_dict["disk"]):
                     flavor = (key, values)
                 if (values["ram"], values["cpus"], values["disk"]) == (
                 flavor_dict["ram"], flavor_dict["vcpus"], flavor_dict["disk"]):
                     flavor = (key, values)
index 44178a8..5183858 100644 (file)
@@ -35,7 +35,7 @@ to the VIM connector's SFC resources as follows:
 __author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C."
 __date__  = "$22-sep-2017 23:59:59$"
 
 __author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C."
 __date__  = "$22-sep-2017 23:59:59$"
 
-from . import vimconn
+import vimconn
 import json
 import logging
 import netaddr
 import json
 import logging
 import netaddr
@@ -55,6 +55,7 @@ from glanceclient import client as glClient
 import glanceclient.client as gl1Client
 import glanceclient.exc as gl1Exceptions
 from  cinderclient import client as cClient
 import glanceclient.client as gl1Client
 import glanceclient.exc as gl1Exceptions
 from  cinderclient import client as cClient
+#from httplib import HTTPException
 from http.client import HTTPException
 from neutronclient.neutron import client as neClient
 from neutronclient.common import exceptions as neExceptions
 from http.client import HTTPException
 from neutronclient.neutron import client as neClient
 from neutronclient.common import exceptions as neExceptions
@@ -156,21 +157,31 @@ class vimconnector(vimconn.vimconnector):
         '''Called before any operation, it check if credentials has changed
         Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
         '''
         '''Called before any operation, it check if credentials has changed
         Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
         '''
-        #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-) 
+        #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
         if self.session['reload_client']:
             if self.config.get('APIversion'):
                 self.api_version3 = self.config['APIversion'] == 'v3.3' or self.config['APIversion'] == '3'
             else:  # get from ending auth_url that end with v3 or with v2.0
         if self.session['reload_client']:
             if self.config.get('APIversion'):
                 self.api_version3 = self.config['APIversion'] == 'v3.3' or self.config['APIversion'] == '3'
             else:  # get from ending auth_url that end with v3 or with v2.0
-                self.api_version3 =  self.url.split("/")[-1] == "v3"
+                self.api_version3 =  self.url.endswith("/v3") or self.url.endswith("/v3/")
             self.session['api_version3'] = self.api_version3
             if self.api_version3:
             self.session['api_version3'] = self.api_version3
             if self.api_version3:
+                if self.config.get('project_domain_id') or self.config.get('project_domain_name'):
+                    project_domain_id_default = None
+                else:
+                    project_domain_id_default = 'default'
+                if self.config.get('user_domain_id') or self.config.get('user_domain_name'):
+                    user_domain_id_default = None
+                else:
+                    user_domain_id_default = 'default'
                 auth = v3.Password(auth_url=self.url,
                                    username=self.user,
                                    password=self.passwd,
                                    project_name=self.tenant_name,
                                    project_id=self.tenant_id,
                 auth = v3.Password(auth_url=self.url,
                                    username=self.user,
                                    password=self.passwd,
                                    project_name=self.tenant_name,
                                    project_id=self.tenant_id,
-                                   project_domain_id=self.config.get('project_domain_id', 'default'),
-                                   user_domain_id=self.config.get('user_domain_id', 'default'))
+                                   project_domain_id=self.config.get('project_domain_id', project_domain_id_default),
+                                   user_domain_id=self.config.get('user_domain_id', user_domain_id_default),
+                                   project_domain_name=self.config.get('project_domain_name'),
+                                   user_domain_name=self.config.get('user_domain_name'))
             else:
                 auth = v2.Password(auth_url=self.url,
                                    username=self.user,
             else:
                 auth = v2.Password(auth_url=self.url,
                                    username=self.user,
@@ -383,7 +394,7 @@ class vimconnector(vimconn.vimconnector):
             else:
                 project = self.keystone.tenants.create(tenant_name, tenant_description)
             return project.id
             else:
                 project = self.keystone.tenants.create(tenant_name, tenant_description)
             return project.id
-        except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
+        except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError)  as e:
             self._format_exception(e)
 
     def delete_tenant(self, tenant_id):
             self._format_exception(e)
 
     def delete_tenant(self, tenant_id):
@@ -396,7 +407,7 @@ class vimconnector(vimconn.vimconnector):
             else:
                 self.keystone.tenants.delete(tenant_id)
             return tenant_id
             else:
                 self.keystone.tenants.delete(tenant_id)
             return tenant_id
-        except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
+        except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError)  as e:
             self._format_exception(e)
 
     def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
             self._format_exception(e)
 
     def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
@@ -541,13 +552,13 @@ class vimconnector(vimconn.vimconnector):
                 net_id:         #VIM id of this network
                     status:     #Mandatory. Text with one of:
                                 #  DELETED (not found at vim)
                 net_id:         #VIM id of this network
                     status:     #Mandatory. Text with one of:
                                 #  DELETED (not found at vim)
-                                #  VIM_ERROR (Cannot connect to VIM, VIM response error, ...) 
+                                #  VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
                                 #  OTHER (Vim reported other status not understood)
                                 #  ERROR (VIM indicates an ERROR status)
                                 #  OTHER (Vim reported other status not understood)
                                 #  ERROR (VIM indicates an ERROR status)
-                                #  ACTIVE, INACTIVE, DOWN (admin down), 
+                                #  ACTIVE, INACTIVE, DOWN (admin down),
                                 #  BUILD (on building process)
                                 #
                                 #  BUILD (on building process)
                                 #
-                    error_msg:  #Text with VIM error message, if any. Or the VIM connection ERROR 
+                    error_msg:  #Text with VIM error message, if any. Or the VIM connection ERROR
                     vim_info:   #Text with plain information obtained from vim (yaml.safe_dump)
 
         '''
                     vim_info:   #Text with plain information obtained from vim (yaml.safe_dump)
 
         '''
@@ -698,7 +709,7 @@ class vimconnector(vimconn.vimconnector):
                             #         raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
                             #     #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
 
                             #         raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
                             #     #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
 
-                #create flavor                 
+                #create flavor
                 new_flavor=self.nova.flavors.create(name,
                                 ram,
                                 vcpus,
                 new_flavor=self.nova.flavors.create(name,
                                 ram,
                                 vcpus,
@@ -774,13 +785,13 @@ class vimconnector(vimconn.vimconnector):
                     with open(image_dict['location']) as fimage:
                         new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
                             container_format="bare", data=fimage, disk_format=disk_format)
                     with open(image_dict['location']) as fimage:
                         new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
                             container_format="bare", data=fimage, disk_format=disk_format)
-                #insert metadata. We cannot use 'new_image.properties.setdefault' 
+                #insert metadata. We cannot use 'new_image.properties.setdefault'
                 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
                 new_image_nova=self.nova.images.find(id=new_image.id)
                 new_image_nova.metadata.setdefault('location',image_dict['location'])
                 metadata_to_load = image_dict.get('metadata')
                 if metadata_to_load:
                 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
                 new_image_nova=self.nova.images.find(id=new_image.id)
                 new_image_nova.metadata.setdefault('location',image_dict['location'])
                 metadata_to_load = image_dict.get('metadata')
                 if metadata_to_load:
-                    for k,v in yaml.load(metadata_to_load).items():
+                    for k,v in yaml.load(metadata_to_load).iteritems():
                         new_image_nova.metadata.setdefault(k,v)
                 return new_image.id
             except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
                         new_image_nova.metadata.setdefault(k,v)
                 return new_image.id
             except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
@@ -831,15 +842,18 @@ class vimconnector(vimconn.vimconnector):
             filter_dict_os=filter_dict.copy()
             #First we filter by the available filter fields: name, id. The others are removed.
             filter_dict_os.pop('checksum',None)
             filter_dict_os=filter_dict.copy()
             #First we filter by the available filter fields: name, id. The others are removed.
             filter_dict_os.pop('checksum',None)
-            image_list=self.nova.images.findall(**filter_dict_os)
-            if len(image_list)==0:
+            image_list = self.nova.images.findall(**filter_dict_os)
+            if len(image_list) == 0:
                 return []
             #Then we filter by the rest of filter fields: checksum
             filtered_list = []
             for image in image_list:
                 return []
             #Then we filter by the rest of filter fields: checksum
             filtered_list = []
             for image in image_list:
-                image_class=self.glance.images.get(image.id)
-                if 'checksum' not in filter_dict or image_class['checksum']==filter_dict.get('checksum'):
-                    filtered_list.append(image_class.copy())
+                try:
+                    image_class = self.glance.images.get(image.id)
+                    if 'checksum' not in filter_dict or image_class['checksum']==filter_dict.get('checksum'):
+                        filtered_list.append(image_class.copy())
+                except gl1Exceptions.HTTPNotFound:
+                    pass
             return filtered_list
         except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
             self._format_exception(e)
             return filtered_list
         except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
             self._format_exception(e)
@@ -1073,7 +1087,7 @@ class vimconnector(vimconn.vimconnector):
                 elapsed_time = 0
                 while keep_waiting and elapsed_time < volume_timeout:
                     keep_waiting = False
                 elapsed_time = 0
                 while keep_waiting and elapsed_time < volume_timeout:
                     keep_waiting = False
-                    for volume_id in block_device_mapping.values():
+                    for volume_id in block_device_mapping.itervalues():
                         if self.cinder.volumes.get(volume_id).status != 'available':
                             keep_waiting = True
                     if keep_waiting:
                         if self.cinder.volumes.get(volume_id).status != 'available':
                             keep_waiting = True
                     if keep_waiting:
@@ -1083,7 +1097,7 @@ class vimconnector(vimconn.vimconnector):
                 #if we exceeded the timeout rollback
                 if elapsed_time >= volume_timeout:
                     #delete the volumes we just created
                 #if we exceeded the timeout rollback
                 if elapsed_time >= volume_timeout:
                     #delete the volumes we just created
-                    for volume_id in block_device_mapping.values():
+                    for volume_id in block_device_mapping.itervalues():
                         self.cinder.volumes.delete(volume_id)
 
                     #delete ports we just created
                         self.cinder.volumes.delete(volume_id)
 
                     #delete ports we just created
@@ -1187,7 +1201,7 @@ class vimconnector(vimconn.vimconnector):
         except Exception as e:
             # delete the volumes we just created
             if block_device_mapping:
         except Exception as e:
             # delete the volumes we just created
             if block_device_mapping:
-                for volume_id in block_device_mapping.values():
+                for volume_id in block_device_mapping.itervalues():
                     self.cinder.volumes.delete(volume_id)
 
             # Delete the VM
                     self.cinder.volumes.delete(volume_id)
 
             # Delete the VM
@@ -1218,13 +1232,13 @@ class vimconnector(vimconn.vimconnector):
         Params:
             vm_id: uuid of the VM
             console_type, can be:
         Params:
             vm_id: uuid of the VM
             console_type, can be:
-                "novnc" (by default), "xvpvnc" for VNC types, 
+                "novnc" (by default), "xvpvnc" for VNC types,
                 "rdp-html5" for RDP types, "spice-html5" for SPICE types
         Returns dict with the console parameters:
                 protocol: ssh, ftp, http, https, ...
                 "rdp-html5" for RDP types, "spice-html5" for SPICE types
         Returns dict with the console parameters:
                 protocol: ssh, ftp, http, https, ...
-                server:   usually ip address 
-                port:     the http, ssh, ... port 
-                suffix:   extra text, e.g. the http path and query string   
+                server:   usually ip address
+                port:     the http, ssh, ... port
+                suffix:   extra text, e.g. the http path and query string
         '''
         self.logger.debug("Getting VM CONSOLE from VIM")
         try:
         '''
         self.logger.debug("Getting VM CONSOLE from VIM")
         try:
@@ -1315,14 +1329,14 @@ class vimconnector(vimconn.vimconnector):
                 vm_id:          #VIM id of this Virtual Machine
                     status:     #Mandatory. Text with one of:
                                 #  DELETED (not found at vim)
                 vm_id:          #VIM id of this Virtual Machine
                     status:     #Mandatory. Text with one of:
                                 #  DELETED (not found at vim)
-                                #  VIM_ERROR (Cannot connect to VIM, VIM response error, ...) 
+                                #  VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
                                 #  OTHER (Vim reported other status not understood)
                                 #  ERROR (VIM indicates an ERROR status)
                                 #  OTHER (Vim reported other status not understood)
                                 #  ERROR (VIM indicates an ERROR status)
-                                #  ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running), 
+                                #  ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
                                 #  CREATING (on building process), ERROR
                                 #  ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
                                 #
                                 #  CREATING (on building process), ERROR
                                 #  ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
                                 #
-                    error_msg:  #Text with VIM error message, if any. Or the VIM connection ERROR 
+                    error_msg:  #Text with VIM error message, if any. Or the VIM connection ERROR
                     vim_info:   #Text with plain information obtained from vim (yaml.safe_dump)
                     interfaces:
                      -  vim_info:         #Text with plain information obtained from vim (yaml.safe_dump)
                     vim_info:   #Text with plain information obtained from vim (yaml.safe_dump)
                     interfaces:
                      -  vim_info:         #Text with plain information obtained from vim (yaml.safe_dump)
@@ -1365,13 +1379,13 @@ class vimconnector(vimconn.vimconnector):
                         interface["mac_address"] = port.get("mac_address")
                         interface["vim_net_id"] = port["network_id"]
                         interface["vim_interface_id"] = port["id"]
                         interface["mac_address"] = port.get("mac_address")
                         interface["vim_net_id"] = port["network_id"]
                         interface["vim_interface_id"] = port["id"]
-                        # check if OS-EXT-SRV-ATTR:host is there, 
+                        # check if OS-EXT-SRV-ATTR:host is there,
                         # in case of non-admin credentials, it will be missing
                         if vm_vim.get('OS-EXT-SRV-ATTR:host'):
                             interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host']
                         interface["pci"] = None
 
                         # in case of non-admin credentials, it will be missing
                         if vm_vim.get('OS-EXT-SRV-ATTR:host'):
                             interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host']
                         interface["pci"] = None
 
-                        # check if binding:profile is there, 
+                        # check if binding:profile is there,
                         # in case of non-admin credentials, it will be missing
                         if port.get('binding:profile'):
                             if port['binding:profile'].get('pci_slot'):
                         # in case of non-admin credentials, it will be missing
                         if port.get('binding:profile'):
                             if port['binding:profile'].get('pci_slot'):
@@ -1504,8 +1518,8 @@ class vimconnector(vimconn.vimconnector):
         #find unused VLAN ID
         for vlanID_range in self.config.get('dataplane_net_vlan_range'):
             try:
         #find unused VLAN ID
         for vlanID_range in self.config.get('dataplane_net_vlan_range'):
             try:
-                start_vlanid , end_vlanid = list(map(int, vlanID_range.replace(" ", "").split("-")))
-                for vlanID in range(start_vlanid, end_vlanid + 1):
+                start_vlanid , end_vlanid = map(int, vlanID_range.replace(" ", "").split("-"))
+                for vlanID in xrange(start_vlanid, end_vlanid + 1):
                     if vlanID not in used_vlanIDs:
                         return vlanID
             except Exception as exp:
                     if vlanID not in used_vlanIDs:
                         return vlanID
             except Exception as exp:
@@ -1530,7 +1544,7 @@ class vimconnector(vimconn.vimconnector):
                 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}.You must provide "\
                 "'dataplane_net_vlan_range' in format [start_ID - end_ID].".format(vlanID_range))
 
                 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}.You must provide "\
                 "'dataplane_net_vlan_range' in format [start_ID - end_ID].".format(vlanID_range))
 
-            start_vlanid , end_vlanid = list(map(int,vlan_range.split("-")))
+            start_vlanid , end_vlanid = map(int,vlan_range.split("-"))
             if start_vlanid <= 0 :
                 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\
                 "Start ID can not be zero. For VLAN "\
             if start_vlanid <= 0 :
                 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\
                 "Start ID can not be zero. For VLAN "\
@@ -1601,7 +1615,7 @@ class vimconnector(vimconn.vimconnector):
         #TODO insert exception vimconn.HTTP_Unauthorized
         #if reaching here is because an exception
         if self.debug:
         #TODO insert exception vimconn.HTTP_Unauthorized
         #if reaching here is because an exception
         if self.debug:
-            print(("delete_tenant " + error_text))
+            print("delete_tenant " + error_text)
         return error_value, error_text
 
     def get_hosts_info(self):
         return error_value, error_text
 
     def get_hosts_info(self):
@@ -1625,7 +1639,7 @@ class vimconnector(vimconn.vimconnector):
         #TODO insert exception vimconn.HTTP_Unauthorized
         #if reaching here is because an exception
         if self.debug:
         #TODO insert exception vimconn.HTTP_Unauthorized
         #if reaching here is because an exception
         if self.debug:
-            print(("get_hosts_info " + error_text))
+            print("get_hosts_info " + error_text)
         return error_value, error_text
 
     def get_hosts(self, vim_tenant):
         return error_value, error_text
 
     def get_hosts(self, vim_tenant):
@@ -1654,7 +1668,7 @@ class vimconnector(vimconn.vimconnector):
         #TODO insert exception vimconn.HTTP_Unauthorized
         #if reaching here is because an exception
         if self.debug:
         #TODO insert exception vimconn.HTTP_Unauthorized
         #if reaching here is because an exception
         if self.debug:
-            print(("get_hosts " + error_text))
+            print("get_hosts " + error_text)
         return error_value, error_text
 
     def new_classification(self, name, ctype, definition):
         return error_value, error_text
 
     def new_classification(self, name, ctype, definition):
index 08d5d98..32a69c9 100644 (file)
@@ -27,16 +27,19 @@ vimconnector implements all the methods to interact with openvim using the openv
 __author__="Alfonso Tierno, Gerardo Garcia"
 __date__ ="$26-aug-2014 11:09:29$"
 
 __author__="Alfonso Tierno, Gerardo Garcia"
 __date__ ="$26-aug-2014 11:09:29$"
 
-from . import vimconn
+import vimconn
 import requests
 import json
 import yaml
 import logging
 import requests
 import json
 import yaml
 import logging
-from .openmano_schemas import id_schema, name_schema, nameshort_schema, description_schema, \
+from openmano_schemas import id_schema, name_schema, nameshort_schema, description_schema, \
                             vlan1000_schema, integer0_schema
 from jsonschema import validate as js_v, exceptions as js_e
                             vlan1000_schema, integer0_schema
 from jsonschema import validate as js_v, exceptions as js_e
-from urllib.parse import quote
-
+try:
+    from urllib import quote  # Python 2.X
+except ImportError:
+    from urllib.parse import quote  # Python 3+
+    
 '''contain the openvim virtual machine status to openmano status'''
 vmStatus2manoFormat={'ACTIVE':'ACTIVE',
                      'PAUSED':'PAUSED',
 '''contain the openvim virtual machine status to openmano status'''
 vmStatus2manoFormat={'ACTIVE':'ACTIVE',
                      'PAUSED':'PAUSED',
@@ -334,14 +337,14 @@ class vimconnector(vimconn.vimconnector):
             self.tenant = tenant_id
 
     def __setitem__(self,index, value):
             self.tenant = tenant_id
 
     def __setitem__(self,index, value):
-        '''Set individuals parameters 
+        '''Set individuals parameters
         Throw TypeError, KeyError
         '''
         if index=='tenant_id':
             self.tenant = value
         elif index=='tenant_name':
             self.tenant = None
         Throw TypeError, KeyError
         '''
         if index=='tenant_id':
             self.tenant = value
         elif index=='tenant_name':
             self.tenant = None
-        vimconn.vimconnector.__setitem__(self,index, value)    
+        vimconn.vimconnector.__setitem__(self,index, value)
 
     def _get_my_tenant(self):
         '''Obtain uuid of my tenant from name
 
     def _get_my_tenant(self):
         '''Obtain uuid of my tenant from name
@@ -377,12 +380,12 @@ class vimconnector(vimconn.vimconnector):
         try:
             client_data = http_response.json()
             js_v(client_data, schema)
         try:
             client_data = http_response.json()
             js_v(client_data, schema)
-            #print "Input data: ", str(client_data)
+            #print("Input data: ", str(client_data))
             return True, client_data
         except js_e.ValidationError as exc:
             print("validate_in error, jsonschema exception ", exc.message, "at", exc.path)
             return False, ("validate_in error, jsonschema exception ", exc.message, "at", exc.path)
             return True, client_data
         except js_e.ValidationError as exc:
             print("validate_in error, jsonschema exception ", exc.message, "at", exc.path)
             return False, ("validate_in error, jsonschema exception ", exc.message, "at", exc.path)
-    
+
     def _remove_extra_items(self, data, schema):
         deleted=[]
         if type(data) is tuple or type(data) is list:
     def _remove_extra_items(self, data, schema):
         deleted=[]
         if type(data) is tuple or type(data) is list:
@@ -390,8 +393,8 @@ class vimconnector(vimconn.vimconnector):
                 a= self._remove_extra_items(d, schema['items'])
                 if a is not None: deleted.append(a)
         elif type(data) is dict:
                 a= self._remove_extra_items(d, schema['items'])
                 if a is not None: deleted.append(a)
         elif type(data) is dict:
-            for k in list(data.keys()):
-                if 'properties' not in schema or k not in list(schema['properties'].keys()):
+            for k in data.keys():
+                if 'properties' not in schema or k not in schema['properties'].keys():
                     del data[k]
                     deleted.append(k)
                 else:
                     del data[k]
                     deleted.append(k)
                 else:
@@ -400,11 +403,11 @@ class vimconnector(vimconn.vimconnector):
         if len(deleted) == 0: return None
         elif len(deleted) == 1: return deleted[0]
         else: return deleted
         if len(deleted) == 0: return None
         elif len(deleted) == 1: return deleted[0]
         else: return deleted
-        
+
     def _format_request_exception(self, request_exception):
         '''Transform a request exception into a vimconn exception'''
         if isinstance(request_exception, js_e.ValidationError):
     def _format_request_exception(self, request_exception):
         '''Transform a request exception into a vimconn exception'''
         if isinstance(request_exception, js_e.ValidationError):
-            raise vimconn.vimconnUnexpectedResponse("jsonschema exception '{}' at '{}'".format(request_exception.message, request_exception.path))            
+            raise vimconn.vimconnUnexpectedResponse("jsonschema exception '{}' at '{}'".format(request_exception.message, request_exception.path))
         elif isinstance(request_exception, requests.exceptions.HTTPError):
             raise vimconn.vimconnUnexpectedResponse(type(request_exception).__name__ + ": " + str(request_exception))
         else:
         elif isinstance(request_exception, requests.exceptions.HTTPError):
             raise vimconn.vimconnUnexpectedResponse(type(request_exception).__name__ + ": " + str(request_exception))
         else:
@@ -420,12 +423,12 @@ class vimconnector(vimconn.vimconnector):
             raise vimconn.vimconnNotFoundException(request_response.text)
         elif request_response.status_code == vimconn.HTTP_Conflict:
             raise vimconn.vimconnConflictException(request_response.text)
             raise vimconn.vimconnNotFoundException(request_response.text)
         elif request_response.status_code == vimconn.HTTP_Conflict:
             raise vimconn.vimconnConflictException(request_response.text)
-        else: 
+        else:
             raise vimconn.vimconnUnexpectedResponse("VIM HTTP_response {}, {}".format(request_response.status_code, str(request_response.text)))
 
     def new_tenant(self,tenant_name,tenant_description):
         '''Adds a new tenant to VIM with this name and description, returns the tenant identifier'''
             raise vimconn.vimconnUnexpectedResponse("VIM HTTP_response {}, {}".format(request_response.status_code, str(request_response.text)))
 
     def new_tenant(self,tenant_name,tenant_description):
         '''Adds a new tenant to VIM with this name and description, returns the tenant identifier'''
-        #print "VIMConnector: Adding a new tenant to VIM"
+        #print("VIMConnector: Adding a new tenant to VIM")
         payload_dict = {"tenant": {"name":tenant_name,"description": tenant_description, "enabled": True}}
         payload_req = json.dumps(payload_dict)
         try:
         payload_dict = {"tenant": {"name":tenant_name,"description": tenant_description, "enabled": True}}
         payload_req = json.dumps(payload_dict)
         try:
@@ -434,11 +437,11 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, new_tenant_response_schema)
             #r = self._remove_extra_items(response, new_tenant_response_schema)
             response = vim_response.json()
             js_v(response, new_tenant_response_schema)
             #r = self._remove_extra_items(response, new_tenant_response_schema)
-            #if r is not None: 
+            #if r is not None:
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             tenant_id = response['tenant']['id']
             return tenant_id
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             tenant_id = response['tenant']['id']
             return tenant_id
@@ -453,7 +456,7 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.delete(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.delete(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             return tenant_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
             return tenant_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
@@ -468,7 +471,7 @@ class vimconnector(vimconn.vimconnector):
         '''
         filterquery=[]
         filterquery_text=''
         '''
         filterquery=[]
         filterquery_text=''
-        for k,v in filter_dict.items():
+        for k,v in filter_dict.iteritems():
             filterquery.append(str(k)+'='+str(v))
         if len(filterquery)>0:
             filterquery_text='?'+ '&'.join(filterquery)
             filterquery.append(str(k)+'='+str(v))
         if len(filterquery)>0:
             filterquery_text='?'+ '&'.join(filterquery)
@@ -478,7 +481,7 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             return vim_response.json()["tenants"]
         except requests.exceptions.RequestException as e:
             self._format_request_exception(e)
             return vim_response.json()["tenants"]
         except requests.exceptions.RequestException as e:
             self._format_request_exception(e)
@@ -499,17 +502,17 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.post(url, headers = self.headers_req, data=json.dumps({"network": payload_req}) )
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.post(url, headers = self.headers_req, data=json.dumps({"network": payload_req}) )
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, new_network_response_schema)
             #r = self._remove_extra_items(response, new_network_response_schema)
             response = vim_response.json()
             js_v(response, new_network_response_schema)
             #r = self._remove_extra_items(response, new_network_response_schema)
-            #if r is not None: 
+            #if r is not None:
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             network_id = response['network']['id']
             return network_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             network_id = response['network']['id']
             return network_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
-        
+
     def get_network_list(self, filter_dict={}):
         '''Obtain tenant networks of VIM
         Filter_dict can be:
     def get_network_list(self, filter_dict={}):
         '''Obtain tenant networks of VIM
         Filter_dict can be:
@@ -528,7 +531,7 @@ class vimconnector(vimconn.vimconnector):
                 del filter_dict["tenant_id"]
             filterquery=[]
             filterquery_text=''
                 del filter_dict["tenant_id"]
             filterquery=[]
             filterquery_text=''
-            for k,v in filter_dict.items():
+            for k,v in filter_dict.iteritems():
                 filterquery.append(str(k)+'='+str(v))
             if len(filterquery)>0:
                 filterquery_text='?'+ '&'.join(filterquery)
                 filterquery.append(str(k)+'='+str(v))
             if len(filterquery)>0:
                 filterquery_text='?'+ '&'.join(filterquery)
@@ -537,7 +540,7 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             return response['networks']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             response = vim_response.json()
             return response['networks']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
@@ -551,12 +554,12 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             return response['network']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
             response = vim_response.json()
             return response['network']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
-            
+
     def delete_network(self, net_id):
         '''Deletes a tenant network from VIM'''
         '''Returns the network identifier'''
     def delete_network(self, net_id):
         '''Deletes a tenant network from VIM'''
         '''Returns the network identifier'''
@@ -567,7 +570,7 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.delete(url, headers=self.headers_req)
             self._check_http_request_response(vim_response)
             #self.logger.debug(vim_response.text)
             vim_response = requests.delete(url, headers=self.headers_req)
             self._check_http_request_response(vim_response)
             #self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             return net_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
             return net_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
@@ -581,16 +584,16 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, get_flavor_response_schema)
             r = self._remove_extra_items(response, get_flavor_response_schema)
             response = vim_response.json()
             js_v(response, get_flavor_response_schema)
             r = self._remove_extra_items(response, get_flavor_response_schema)
-            if r is not None: 
+            if r is not None:
                 self.logger.warn("Warning: remove extra items %s", str(r))
             return response['flavor']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
                 self.logger.warn("Warning: remove extra items %s", str(r))
             return response['flavor']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
-        
+
     def new_flavor(self, flavor_data):
         '''Adds a tenant flavor to VIM'''
         '''Returns the flavor identifier'''
     def new_flavor(self, flavor_data):
         '''Adds a tenant flavor to VIM'''
         '''Returns the flavor identifier'''
@@ -607,11 +610,11 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, new_flavor_response_schema)
             r = self._remove_extra_items(response, new_flavor_response_schema)
             response = vim_response.json()
             js_v(response, new_flavor_response_schema)
             r = self._remove_extra_items(response, new_flavor_response_schema)
-            if r is not None: 
+            if r is not None:
                 self.logger.warn("Warning: remove extra items %s", str(r))
             flavor_id = response['flavor']['id']
             return flavor_id
                 self.logger.warn("Warning: remove extra items %s", str(r))
             flavor_id = response['flavor']['id']
             return flavor_id
@@ -628,7 +631,7 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.delete(url, headers=self.headers_req)
             self._check_http_request_response(vim_response)
             #self.logger.debug(vim_response.text)
             vim_response = requests.delete(url, headers=self.headers_req)
             self._check_http_request_response(vim_response)
             #self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             return flavor_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
             return flavor_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
@@ -642,11 +645,11 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, get_image_response_schema)
             r = self._remove_extra_items(response, get_image_response_schema)
             response = vim_response.json()
             js_v(response, get_image_response_schema)
             r = self._remove_extra_items(response, get_image_response_schema)
-            if r is not None: 
+            if r is not None:
                 self.logger.warn("Warning: remove extra items %s", str(r))
             return response['image']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
                 self.logger.warn("Warning: remove extra items %s", str(r))
             return response['image']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
@@ -669,17 +672,17 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, new_image_response_schema)
             r = self._remove_extra_items(response, new_image_response_schema)
             response = vim_response.json()
             js_v(response, new_image_response_schema)
             r = self._remove_extra_items(response, new_image_response_schema)
-            if r is not None: 
+            if r is not None:
                 self.logger.warn("Warning: remove extra items %s", str(r))
             image_id = response['image']['id']
             return image_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
                 self.logger.warn("Warning: remove extra items %s", str(r))
             image_id = response['image']['id']
             return image_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
-            
+
     def delete_image(self, image_id):
         '''Deletes a tenant image from VIM'''
         '''Returns the deleted image_id'''
     def delete_image(self, image_id):
         '''Deletes a tenant image from VIM'''
         '''Returns the deleted image_id'''
@@ -690,7 +693,7 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.delete(url, headers=self.headers_req)
             self._check_http_request_response(vim_response)
             #self.logger.debug(vim_response.text)
             vim_response = requests.delete(url, headers=self.headers_req)
             self._check_http_request_response(vim_response)
             #self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             return image_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
             return image_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
@@ -704,11 +707,11 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.get(url)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.get(url)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, get_images_response_schema)
             #r = self._remove_extra_items(response, get_images_response_schema)
             response = vim_response.json()
             js_v(response, get_images_response_schema)
             #r = self._remove_extra_items(response, get_images_response_schema)
-            #if r is not None: 
+            #if r is not None:
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             if len(response['images'])==0:
                 raise vimconn.vimconnNotFoundException("Image not found at VIM with path '%s'", path)
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             if len(response['images'])==0:
                 raise vimconn.vimconnNotFoundException("Image not found at VIM with path '%s'", path)
@@ -733,7 +736,7 @@ class vimconnector(vimconn.vimconnector):
             self._get_my_tenant()
             filterquery=[]
             filterquery_text=''
             self._get_my_tenant()
             filterquery=[]
             filterquery_text=''
-            for k,v in filter_dict.items():
+            for k,v in filter_dict.iteritems():
                 filterquery.append(str(k)+'='+str(v))
             if len(filterquery)>0:
                 filterquery_text='?'+ '&'.join(filterquery)
                 filterquery.append(str(k)+'='+str(v))
             if len(filterquery)>0:
                 filterquery_text='?'+ '&'.join(filterquery)
@@ -742,7 +745,7 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             return response['images']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             response = vim_response.json()
             return response['images']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
@@ -763,25 +766,25 @@ class vimconnector(vimconn.vimconnector):
             print("new_vminstancefromJSON Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print(vim_response)
             print("new_vminstancefromJSON Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print(vim_response)
-        #print vim_response.status_code
+        #print(vim_response.status_code)
         if vim_response.status_code == 200:
         if vim_response.status_code == 200:
-            #print vim_response.json()
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(vim_response.json())
+            #print(json.dumps(vim_response.json(), indent=4))
             res,http_content = self._format_in(vim_response, new_image_response_schema)
             res,http_content = self._format_in(vim_response, new_image_response_schema)
-            #print http_content
+            #print(http_content)
             if res:
                 r = self._remove_extra_items(http_content, new_image_response_schema)
                 if r is not None: print("Warning: remove extra items ", r)
             if res:
                 r = self._remove_extra_items(http_content, new_image_response_schema)
                 if r is not None: print("Warning: remove extra items ", r)
-                #print http_content
+                #print(http_content)
                 vminstance_id = http_content['server']['id']
                 print("Tenant image id: ",vminstance_id)
                 return vim_response.status_code,vminstance_id
             else: return -vimconn.HTTP_Bad_Request,http_content
         else:
                 vminstance_id = http_content['server']['id']
                 print("Tenant image id: ",vminstance_id)
                 return vim_response.status_code,vminstance_id
             else: return -vimconn.HTTP_Bad_Request,http_content
         else:
-            #print vim_response.text
+            #print(vim_response.text)
             jsonerror = self._format_jsonerror(vim_response)
             text = 'Error in VIM "%s": not possible to add new vm instance. HTTP Response: %d. Error: %s' % (self.url, vim_response.status_code, jsonerror)
             jsonerror = self._format_jsonerror(vim_response)
             text = 'Error in VIM "%s": not possible to add new vm instance. HTTP Response: %d. Error: %s' % (self.url, vim_response.status_code, jsonerror)
-            #print text
+            #print(text)
             return -vim_response.status_code,text
 
     def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
             return -vim_response.status_code,text
 
     def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
@@ -795,7 +798,7 @@ class vimconnector(vimconn.vimconnector):
                 net_id: network uuid to connect
                 vpci: virtual vcpi to assign
                 model: interface model, virtio, e2000, ...
                 net_id: network uuid to connect
                 vpci: virtual vcpi to assign
                 model: interface model, virtio, e2000, ...
-                mac_address: 
+                mac_address:
                 use: 'data', 'bridge',  'mgmt'
                 type: 'virtual', 'PF', 'VF', 'VFnotShared'
                 vim_id: filled/added by this function
                 use: 'data', 'bridge',  'mgmt'
                 type: 'virtual', 'PF', 'VF', 'VFnotShared'
                 vim_id: filled/added by this function
@@ -807,9 +810,9 @@ class vimconnector(vimconn.vimconnector):
             self._get_my_tenant()
 #            net_list = []
 #            for k,v in net_dict.items():
             self._get_my_tenant()
 #            net_list = []
 #            for k,v in net_dict.items():
-#                print k,v
+#                print(k,v)
 #                net_list.append('{"name":"' + k + '", "uuid":"' + v + '"}')
 #                net_list.append('{"name":"' + k + '", "uuid":"' + v + '"}')
-#            net_list_string = ', '.join(net_list) 
+#            net_list_string = ', '.join(net_list)
             virtio_net_list=[]
             for net in net_list:
                 if not net.get("net_id"):
             virtio_net_list=[]
             for net in net_list:
                 if not net.get("net_id"):
@@ -835,11 +838,11 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, new_vminstance_response_schema)
             #r = self._remove_extra_items(response, new_vminstance_response_schema)
             response = vim_response.json()
             js_v(response, new_vminstance_response_schema)
             #r = self._remove_extra_items(response, new_vminstance_response_schema)
-            #if r is not None: 
+            #if r is not None:
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             vminstance_id = response['server']['id']
 
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             vminstance_id = response['server']['id']
 
@@ -862,21 +865,21 @@ class vimconnector(vimconn.vimconnector):
                         for iface in numa.get('interfaces',() ):
                             if net['name'] == iface['name']:
                                 net['vim_id'] = iface['iface_id']
                         for iface in numa.get('interfaces',() ):
                             if net['name'] == iface['name']:
                                 net['vim_id'] = iface['iface_id']
-                                #Code bellow is not needed, current openvim connect dataplane interfaces 
+                                #Code bellow is not needed, current openvim connect dataplane interfaces
                                 #if net.get("net_id"):
                                 ##connect dataplane interface
                                 #    result, port_id = self.connect_port_network(iface['iface_id'], net["net_id"])
                                 #    if result < 0:
                                 #        error_text = "Error attaching port %s to network %s: %s." % (iface['iface_id'], net["net_id"], port_id)
                                 #if net.get("net_id"):
                                 ##connect dataplane interface
                                 #    result, port_id = self.connect_port_network(iface['iface_id'], net["net_id"])
                                 #    if result < 0:
                                 #        error_text = "Error attaching port %s to network %s: %s." % (iface['iface_id'], net["net_id"], port_id)
-                                #        print "new_vminstance: " + error_text
+                                #        print("new_vminstance: " + error_text)
                                 #        self.delete_vminstance(vminstance_id)
                                 #        return result, error_text
                                 break
                                 #        self.delete_vminstance(vminstance_id)
                                 #        return result, error_text
                                 break
-        
+
             return vminstance_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
             return vminstance_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
-        
+
     def get_vminstance(self, vm_id):
         '''Returns the VM instance information from VIM'''
         try:
     def get_vminstance(self, vm_id):
         '''Returns the VM instance information from VIM'''
         try:
@@ -887,16 +890,16 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.get(url, headers = self.headers_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, new_vminstance_response_schema)
             #r = self._remove_extra_items(response, new_vminstance_response_schema)
             response = vim_response.json()
             js_v(response, new_vminstance_response_schema)
             #r = self._remove_extra_items(response, new_vminstance_response_schema)
-            #if r is not None: 
+            #if r is not None:
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             return response['server']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
             #    self.logger.warn("Warning: remove extra items %s", str(r))
             return response['server']
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
-        
+
     def delete_vminstance(self, vm_id):
         '''Removes a VM instance from VIM, returns the deleted vm_id'''
         try:
     def delete_vminstance(self, vm_id):
         '''Removes a VM instance from VIM, returns the deleted vm_id'''
         try:
@@ -906,7 +909,7 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.delete(url, headers=self.headers_req)
             self._check_http_request_response(vim_response)
             #self.logger.debug(vim_response.text)
             vim_response = requests.delete(url, headers=self.headers_req)
             self._check_http_request_response(vim_response)
             #self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             return vm_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
             return vm_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
@@ -920,7 +923,7 @@ class vimconnector(vimconn.vimconnector):
         vm_dict={}
         for vm_id in vm_list:
             vm={}
         vm_dict={}
         for vm_id in vm_list:
             vm={}
-            #print "VIMConnector refresh_tenant_vms and nets: Getting tenant VM instance information from VIM"
+            #print("VIMConnector refresh_tenant_vms and nets: Getting tenant VM instance information from VIM")
             try:
                 url = self.url+'/'+self.tenant+'/servers/'+ vm_id
                 self.logger.info("Getting vm GET %s", url)
             try:
                 url = self.url+'/'+self.tenant+'/servers/'+ vm_id
                 self.logger.info("Getting vm GET %s", url)
@@ -958,13 +961,13 @@ class vimconnector(vimconn.vimconnector):
                         if interface["ip_address"] == "0.0.0.0":
                             interface["ip_address"] = None
                         vm["interfaces"].append(interface)
                         if interface["ip_address"] == "0.0.0.0":
                             interface["ip_address"] = None
                         vm["interfaces"].append(interface)
-                        
+
                 except Exception as e:
                     self.logger.error("refresh_vms_and_nets. Port get %s: %s", type(e).__name__, str(e))
 
                 if vm['status'] == "ACTIVE" and not management_ip:
                     vm['status'] = "ACTIVE:NoMgmtIP"
                 except Exception as e:
                     self.logger.error("refresh_vms_and_nets. Port get %s: %s", type(e).__name__, str(e))
 
                 if vm['status'] == "ACTIVE" and not management_ip:
                     vm['status'] = "ACTIVE:NoMgmtIP"
-                    
+
             except vimconn.vimconnNotFoundException as e:
                 self.logger.error("Exception getting vm status: %s", str(e))
                 vm['status'] = "DELETED"
             except vimconn.vimconnNotFoundException as e:
                 self.logger.error("Exception getting vm status: %s", str(e))
                 vm['status'] = "DELETED"
@@ -983,13 +986,13 @@ class vimconnector(vimconn.vimconnector):
                 net_id:         #VIM id of this network
                     status:     #Mandatory. Text with one of:
                                 #  DELETED (not found at vim)
                 net_id:         #VIM id of this network
                     status:     #Mandatory. Text with one of:
                                 #  DELETED (not found at vim)
-                                #  VIM_ERROR (Cannot connect to VIM, VIM response error, ...) 
+                                #  VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
                                 #  OTHER (Vim reported other status not understood)
                                 #  ERROR (VIM indicates an ERROR status)
                                 #  OTHER (Vim reported other status not understood)
                                 #  ERROR (VIM indicates an ERROR status)
-                                #  ACTIVE, INACTIVE, DOWN (admin down), 
+                                #  ACTIVE, INACTIVE, DOWN (admin down),
                                 #  BUILD (on building process)
                                 #
                                 #  BUILD (on building process)
                                 #
-                    error_msg:  #Text with VIM error message, if any. Or the VIM connection ERROR 
+                    error_msg:  #Text with VIM error message, if any. Or the VIM connection ERROR
                     vim_info:   #Text with plain information obtained from vim (yaml.safe_dump)
 
         '''
                     vim_info:   #Text with plain information obtained from vim (yaml.safe_dump)
 
         '''
@@ -997,11 +1000,11 @@ class vimconnector(vimconn.vimconnector):
             self._get_my_tenant()
         except requests.exceptions.RequestException as e:
             self._format_request_exception(e)
             self._get_my_tenant()
         except requests.exceptions.RequestException as e:
             self._format_request_exception(e)
-        
+
         net_dict={}
         for net_id in net_list:
             net = {}
         net_dict={}
         for net_id in net_list:
             net = {}
-            #print "VIMConnector refresh_tenant_vms_and_nets: Getting tenant network from VIM (tenant: " + str(self.tenant) + "): "
+            #print("VIMConnector refresh_tenant_vms_and_nets: Getting tenant network from VIM (tenant: " + str(self.tenant) + "): ")
             try:
                 net_vim = self.get_network(net_id)
                 if net_vim['status'] in netStatus2manoFormat:
             try:
                 net_vim = self.get_network(net_id)
                 if net_vim['status'] in netStatus2manoFormat:
@@ -1009,7 +1012,7 @@ class vimconnector(vimconn.vimconnector):
                 else:
                     net["status"] = "OTHER"
                     net["error_msg"] = "VIM status reported " + net_vim['status']
                 else:
                     net["status"] = "OTHER"
                     net["error_msg"] = "VIM status reported " + net_vim['status']
-                    
+
                 if net["status"] == "ACTIVE" and not net_vim['admin_state_up']:
                     net["status"] = "DOWN"
                 if net_vim.get('last_error'):
                 if net["status"] == "ACTIVE" and not net_vim['admin_state_up']:
                     net["status"] = "DOWN"
                 if net_vim.get('last_error'):
@@ -1025,7 +1028,7 @@ class vimconnector(vimconn.vimconnector):
                 net['error_msg'] = str(e)
             net_dict[net_id] = net
         return net_dict
                 net['error_msg'] = str(e)
             net_dict[net_id] = net
         return net_dict
-    
+
     def action_vminstance(self, vm_id, action_dict):
         '''Send and action over a VM instance from VIM'''
         '''Returns the status'''
     def action_vminstance(self, vm_id, action_dict):
         '''Send and action over a VM instance from VIM'''
         '''Returns the status'''
@@ -1041,13 +1044,13 @@ class vimconnector(vimconn.vimconnector):
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
 
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
 
-#NOT USED METHODS in current version        
-  
+#NOT USED METHODS in current version
+
     def host_vim2gui(self, host, server_dict):
         '''Transform host dictionary from VIM format to GUI format,
         and append to the server_dict
         '''
     def host_vim2gui(self, host, server_dict):
         '''Transform host dictionary from VIM format to GUI format,
         and append to the server_dict
         '''
-        if type(server_dict) is not dict: 
+        if type(server_dict) is not dict:
             print('vimconnector.host_vim2gui() ERROR, param server_dict must be a dictionary')
             return
         RAD={}
             print('vimconnector.host_vim2gui() ERROR, param server_dict must be a dictionary')
             return
         RAD={}
@@ -1075,7 +1078,7 @@ class vimconnector(vimconn.vimconnector):
             for iface in numa['interfaces']:
                 RAD_item['ports'][ iface['pci'] ] = 'speed:'+str(iface['Mbps'])+'M'
                 occupation_item['ports'][ iface['pci'] ] = { 'occupied': str(100*iface['Mbps_consumed'] / iface['Mbps']) + "%" }
             for iface in numa['interfaces']:
                 RAD_item['ports'][ iface['pci'] ] = 'speed:'+str(iface['Mbps'])+'M'
                 occupation_item['ports'][ iface['pci'] ] = { 'occupied': str(100*iface['Mbps_consumed'] / iface['Mbps']) + "%" }
-                
+
             RAD[ numa['numa_socket'] ] = RAD_item
             occupation[ numa['numa_socket'] ] = occupation_item
         server_dict[ host['host']['name'] ] = {'RAD':RAD, 'occupation':occupation}
             RAD[ numa['numa_socket'] ] = RAD_item
             occupation[ numa['numa_socket'] ] = occupation_item
         server_dict[ host['host']['name'] ] = {'RAD':RAD, 'occupation':occupation}
@@ -1091,15 +1094,15 @@ class vimconnector(vimconn.vimconnector):
             print("get_hosts_info Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print("vim get", url, "response:",  vim_response.status_code, vim_response.json())
             print("get_hosts_info Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print("vim get", url, "response:",  vim_response.status_code, vim_response.json())
-        #print vim_response.status_code
-        #print json.dumps(vim_response.json(), indent=4)
+        #print(vim_response.status_code)
+        #print(json.dumps(vim_response.json(), indent=4))
         if vim_response.status_code != 200:
             #TODO: get error
             print('vimconnector.get_hosts_info error getting host list %d %s' %(vim_response.status_code, vim_response.json()))
             return -vim_response.status_code, "Error getting host list"
         if vim_response.status_code != 200:
             #TODO: get error
             print('vimconnector.get_hosts_info error getting host list %d %s' %(vim_response.status_code, vim_response.json()))
             return -vim_response.status_code, "Error getting host list"
-        
+
         res,hosts = self._format_in(vim_response, get_hosts_response_schema)
         res,hosts = self._format_in(vim_response, get_hosts_response_schema)
-            
+
         if res==False:
             print("vimconnector.get_hosts_info error parsing GET HOSTS vim response", hosts)
             return vimconn.HTTP_Internal_Server_Error, hosts
         if res==False:
             print("vimconnector.get_hosts_info error parsing GET HOSTS vim response", hosts)
             return vimconn.HTTP_Internal_Server_Error, hosts
@@ -1120,7 +1123,7 @@ class vimconnector(vimconn.vimconnector):
             if res==False:
                 print("vimconnector.get_hosts_info error parsing GET HOSTS/%s vim response" % host['id'], host_detail)
                 continue
             if res==False:
                 print("vimconnector.get_hosts_info error parsing GET HOSTS/%s vim response" % host['id'], host_detail)
                 continue
-            #print 'host id '+host['id'], json.dumps(host_detail, indent=4)
+            #print('host id '+host['id'], json.dumps(host_detail, indent=4))
             self.host_vim2gui(host_detail, hosts_dict)
         return 200, hosts_dict
 
             self.host_vim2gui(host_detail, hosts_dict)
         return 200, hosts_dict
 
@@ -1135,15 +1138,15 @@ class vimconnector(vimconn.vimconnector):
             print("get_hosts Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print("vim get", url, "response:",  vim_response.status_code, vim_response.json())
             print("get_hosts Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print("vim get", url, "response:",  vim_response.status_code, vim_response.json())
-        #print vim_response.status_code
-        #print json.dumps(vim_response.json(), indent=4)
+        #print(vim_response.status_code)
+        #print(json.dumps(vim_response.json(), indent=4))
         if vim_response.status_code != 200:
             #TODO: get error
             print('vimconnector.get_hosts error getting host list %d %s' %(vim_response.status_code, vim_response.json()))
             return -vim_response.status_code, "Error getting host list"
         if vim_response.status_code != 200:
             #TODO: get error
             print('vimconnector.get_hosts error getting host list %d %s' %(vim_response.status_code, vim_response.json()))
             return -vim_response.status_code, "Error getting host list"
-        
+
         res,hosts = self._format_in(vim_response, get_hosts_response_schema)
         res,hosts = self._format_in(vim_response, get_hosts_response_schema)
-            
+
         if res==False:
             print("vimconnector.get_host error parsing GET HOSTS vim response", hosts)
             return vimconn.HTTP_Internal_Server_Error, hosts
         if res==False:
             print("vimconnector.get_host error parsing GET HOSTS vim response", hosts)
             return vimconn.HTTP_Internal_Server_Error, hosts
@@ -1163,7 +1166,7 @@ class vimconnector(vimconn.vimconnector):
             if res==False:
                 print("vimconnector.get_host error parsing GET SERVERS/%s vim response" % host['id'], servers)
                 continue
             if res==False:
                 print("vimconnector.get_host error parsing GET SERVERS/%s vim response" % host['id'], servers)
                 continue
-            #print 'host id '+host['id'], json.dumps(host_detail, indent=4)
+            #print('host id '+host['id'], json.dumps(host_detail, indent=4))
             host['instances'] = servers['servers']
         return 200, hosts['hosts']
 
             host['instances'] = servers['servers']
         return 200, hosts['hosts']
 
@@ -1176,16 +1179,16 @@ class vimconnector(vimconn.vimconnector):
             print("get_processor_rankings Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print("vim get", url, "response:", vim_response.status_code, vim_response.json())
             print("get_processor_rankings Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print("vim get", url, "response:", vim_response.status_code, vim_response.json())
-        #print vim_response.status_code
-        #print json.dumps(vim_response.json(), indent=4)
+        #print(vim_response.status_code)
+        #print(json.dumps(vim_response.json(), indent=4))
         if vim_response.status_code != 200:
             #TODO: get error
             print('vimconnector.get_processor_rankings error getting processor rankings %d %s' %(vim_response.status_code, vim_response.json()))
             return -vim_response.status_code, "Error getting processor rankings"
         if vim_response.status_code != 200:
             #TODO: get error
             print('vimconnector.get_processor_rankings error getting processor rankings %d %s' %(vim_response.status_code, vim_response.json()))
             return -vim_response.status_code, "Error getting processor rankings"
-        
+
         res,rankings = self._format_in(vim_response, get_processor_rankings_response_schema)
         return res, rankings['rankings']
         res,rankings = self._format_in(vim_response, get_processor_rankings_response_schema)
         return res, rankings['rankings']
-    
+
     def new_host(self, host_data):
         '''Adds a new host to VIM'''
         '''Returns status code of the VIM response'''
     def new_host(self, host_data):
         '''Adds a new host to VIM'''
         '''Returns status code of the VIM response'''
@@ -1196,17 +1199,17 @@ class vimconnector(vimconn.vimconnector):
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
             self._check_http_request_response(vim_response)
             self.logger.debug(vim_response.text)
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(json.dumps(vim_response.json(), indent=4))
             response = vim_response.json()
             js_v(response, new_host_response_schema)
             r = self._remove_extra_items(response, new_host_response_schema)
             response = vim_response.json()
             js_v(response, new_host_response_schema)
             r = self._remove_extra_items(response, new_host_response_schema)
-            if r is not None: 
+            if r is not None:
                 self.logger.warn("Warning: remove extra items %s", str(r))
             host_id = response['host']['id']
             return host_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
                 self.logger.warn("Warning: remove extra items %s", str(r))
             host_id = response['host']['id']
             return host_id
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
-    
+
     def new_external_port(self, port_data):
         '''Adds a external port to VIM'''
         '''Returns the port identifier'''
     def new_external_port(self, port_data):
         '''Adds a external port to VIM'''
         '''Returns the port identifier'''
@@ -1219,33 +1222,33 @@ class vimconnector(vimconn.vimconnector):
             self.logger.error("new_external_port Exception: ", str(e))
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print(vim_response)
             self.logger.error("new_external_port Exception: ", str(e))
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print(vim_response)
-        #print vim_response.status_code
+        #print(vim_response.status_code)
         if vim_response.status_code == 200:
         if vim_response.status_code == 200:
-        #print vim_response.json()
-        #print json.dumps(vim_response.json(), indent=4)
+        #print(vim_response.json())
+        #print(json.dumps(vim_response.json(), indent=4))
             res, http_content = self._format_in(vim_response, new_port_response_schema)
             res, http_content = self._format_in(vim_response, new_port_response_schema)
-        #print http_content
+        #print(http_content)
             if res:
                 r = self._remove_extra_items(http_content, new_port_response_schema)
                 if r is not None: print("Warning: remove extra items ", r)
             if res:
                 r = self._remove_extra_items(http_content, new_port_response_schema)
                 if r is not None: print("Warning: remove extra items ", r)
-                #print http_content
+                #print(http_content)
                 port_id = http_content['port']['id']
                 print("Port id: ",port_id)
                 return vim_response.status_code,port_id
             else: return -vimconn.HTTP_Bad_Request,http_content
         else:
                 port_id = http_content['port']['id']
                 print("Port id: ",port_id)
                 return vim_response.status_code,port_id
             else: return -vimconn.HTTP_Bad_Request,http_content
         else:
-            #print vim_response.text
+            #print(vim_response.text)
             jsonerror = self._format_jsonerror(vim_response)
             text = 'Error in VIM "%s": not possible to add new external port. HTTP Response: %d. Error: %s' % (self.url_admin, vim_response.status_code, jsonerror)
             jsonerror = self._format_jsonerror(vim_response)
             text = 'Error in VIM "%s": not possible to add new external port. HTTP Response: %d. Error: %s' % (self.url_admin, vim_response.status_code, jsonerror)
-            #print text
+            #print(text)
             return -vim_response.status_code,text
             return -vim_response.status_code,text
-        
+
     def new_external_network(self,net_name,net_type):
         '''Adds a external network to VIM (shared)'''
         '''Returns the network identifier'''
         #TODO change to logging exception code policies
         print("VIMConnector: Adding external shared network to VIM (type " + net_type + "): "+ net_name)
     def new_external_network(self,net_name,net_type):
         '''Adds a external network to VIM (shared)'''
         '''Returns the network identifier'''
         #TODO change to logging exception code policies
         print("VIMConnector: Adding external shared network to VIM (type " + net_type + "): "+ net_name)
-        
+
         payload_req = '{"network":{"name": "' + net_name + '","shared":true,"type": "' + net_type + '"}}'
         try:
             vim_response = requests.post(self.url+'/networks', headers = self.headers_req, data=payload_req)
         payload_req = '{"network":{"name": "' + net_name + '","shared":true,"type": "' + net_type + '"}}'
         try:
             vim_response = requests.post(self.url+'/networks', headers = self.headers_req, data=payload_req)
@@ -1253,33 +1256,33 @@ class vimconnector(vimconn.vimconnector):
             self.logger.error( "new_external_network Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print(vim_response)
             self.logger.error( "new_external_network Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print(vim_response)
-        #print vim_response.status_code
+        #print(vim_response.status_code)
         if vim_response.status_code == 200:
         if vim_response.status_code == 200:
-            #print vim_response.json()
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(vim_response.json())
+            #print(json.dumps(vim_response.json(), indent=4))
             res,http_content = self._format_in(vim_response, new_network_response_schema)
             res,http_content = self._format_in(vim_response, new_network_response_schema)
-            #print http_content
+            #print(http_content)
             if res:
                 r = self._remove_extra_items(http_content, new_network_response_schema)
                 if r is not None: print("Warning: remove extra items ", r)
             if res:
                 r = self._remove_extra_items(http_content, new_network_response_schema)
                 if r is not None: print("Warning: remove extra items ", r)
-                #print http_content
+                #print(http_content)
                 network_id = http_content['network']['id']
                 print("Network id: ",network_id)
                 return vim_response.status_code,network_id
             else: return -vimconn.HTTP_Bad_Request,http_content
         else:
                 network_id = http_content['network']['id']
                 print("Network id: ",network_id)
                 return vim_response.status_code,network_id
             else: return -vimconn.HTTP_Bad_Request,http_content
         else:
-            #print vim_response.text
+            #print(vim_response.text)
             jsonerror = self._format_jsonerror(vim_response)
             text = 'Error in VIM "%s": not possible to add new external network. HTTP Response: %d. Error: %s' % (self.url, vim_response.status_code, jsonerror)
             jsonerror = self._format_jsonerror(vim_response)
             text = 'Error in VIM "%s": not possible to add new external network. HTTP Response: %d. Error: %s' % (self.url, vim_response.status_code, jsonerror)
-            #print text
+            #print(text)
             return -vim_response.status_code,text
             return -vim_response.status_code,text
-        
+
     def connect_port_network(self, port_id, network_id, admin=False):
         '''Connects a external port to a network'''
         '''Returns status code of the VIM response'''
         #TODO change to logging exception code policies
         print("VIMConnector: Connecting external port to network")
     def connect_port_network(self, port_id, network_id, admin=False):
         '''Connects a external port to a network'''
         '''Returns status code of the VIM response'''
         #TODO change to logging exception code policies
         print("VIMConnector: Connecting external port to network")
-        
+
         payload_req = '{"port":{"network_id":"' + network_id + '"}}'
         if admin:
             if self.url_admin==None:
         payload_req = '{"port":{"network_id":"' + network_id + '"}}'
         if admin:
             if self.url_admin==None:
@@ -1293,16 +1296,16 @@ class vimconnector(vimconn.vimconnector):
             print("connect_port_network Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print(vim_response)
             print("connect_port_network Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print(vim_response)
-        #print vim_response.status_code
+        #print(vim_response.status_code)
         if vim_response.status_code == 200:
         if vim_response.status_code == 200:
-            #print vim_response.json()
-            #print json.dumps(vim_response.json(), indent=4)
+            #print(vim_response.json())
+            #print(json.dumps(vim_response.json(), indent=4))
             res,http_content = self._format_in(vim_response, new_port_response_schema)
             res,http_content = self._format_in(vim_response, new_port_response_schema)
-            #print http_content
+            #print(http_content)
             if res:
                 r = self._remove_extra_items(http_content, new_port_response_schema)
                 if r is not None: print("Warning: remove extra items ", r)
             if res:
                 r = self._remove_extra_items(http_content, new_port_response_schema)
                 if r is not None: print("Warning: remove extra items ", r)
-                #print http_content
+                #print(http_content)
                 port_id = http_content['port']['id']
                 print("Port id: ",port_id)
                 return vim_response.status_code,port_id
                 port_id = http_content['port']['id']
                 print("Port id: ",port_id)
                 return vim_response.status_code,port_id
@@ -1313,5 +1316,3 @@ class vimconnector(vimconn.vimconnector):
             text = 'Error in VIM "%s": not possible to connect external port to network. HTTP Response: %d. Error: %s' % (self.url_admin, vim_response.status_code, jsonerror)
             print(text)
             return -vim_response.status_code,text
             text = 'Error in VIM "%s": not possible to connect external port to network. HTTP Response: %d. Error: %s' % (self.url_admin, vim_response.status_code, jsonerror)
             print(text)
             return -vim_response.status_code,text
-        
-
index 12581d6..f69487d 100644 (file)
@@ -27,7 +27,7 @@ mbayramov@vmware.com
 """
 from progressbar import Percentage, Bar, ETA, FileTransferSpeed, ProgressBar
 
 """
 from progressbar import Percentage, Bar, ETA, FileTransferSpeed, ProgressBar
 
-from . import vimconn
+import vimconn
 import os
 import traceback
 import itertools
 import os
 import traceback
 import itertools
@@ -42,7 +42,10 @@ from xml.etree import ElementTree as XmlElementTree
 from lxml import etree as lxmlElementTree
 
 import yaml
 from lxml import etree as lxmlElementTree
 
 import yaml
-from pyvcloud import Http
+
+#from pyvcloud import Http
+import http.client as Http
+
 from pyvcloud.vcloudair import VCA
 from pyvcloud.schema.vcd.v1_5.schemas.vcloud import sessionType, organizationType, \
     vAppType, organizationListType, vdcType, catalogType, queryRecordViewType, \
 from pyvcloud.vcloudair import VCA
 from pyvcloud.schema.vcd.v1_5.schemas.vcloud import sessionType, organizationType, \
     vAppType, organizationListType, vdcType, catalogType, queryRecordViewType, \
@@ -58,7 +61,7 @@ import logging
 import json
 import time
 import uuid
 import json
 import time
 import uuid
-import http.client
+import httplib
 import hashlib
 import socket
 import struct
 import hashlib
 import socket
 import struct
@@ -456,7 +459,7 @@ class vimconnector(vimconn.vimconnector):
                     raise vimconn.vimconnNotFoundException("Fail to get tenant {}".format(tenant_id))
 
                 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
                     raise vimconn.vimconnNotFoundException("Fail to get tenant {}".format(tenant_id))
 
                 lxmlroot_respond = lxmlElementTree.fromstring(response.content)
-                namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
+                namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
                 namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
                 vdc_remove_href = lxmlroot_respond.find("xmlns:Link[@rel='remove']",namespaces).attrib['href']
                 vdc_remove_href = vdc_remove_href + '?recursive=true&force=true'
                 namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
                 vdc_remove_href = lxmlroot_respond.find("xmlns:Link[@rel='remove']",namespaces).attrib['href']
                 vdc_remove_href = vdc_remove_href + '?recursive=true&force=true'
@@ -871,7 +874,7 @@ class vimconnector(vimconn.vimconnector):
             raise vimconn.vimconnNotFoundException("Fail to get image {}".format(image_id))
 
         lxmlroot_respond = lxmlElementTree.fromstring(response.content)
             raise vimconn.vimconnNotFoundException("Fail to get image {}".format(image_id))
 
         lxmlroot_respond = lxmlElementTree.fromstring(response.content)
-        namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
+        namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
         namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
 
         catalogItems_section = lxmlroot_respond.find("xmlns:CatalogItems",namespaces)
         namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
 
         catalogItems_section = lxmlroot_respond.find("xmlns:CatalogItems",namespaces)
@@ -894,7 +897,7 @@ class vimconnector(vimconn.vimconnector):
                                                                                     image_id))
 
             lxmlroot_respond = lxmlElementTree.fromstring(response.content)
                                                                                     image_id))
 
             lxmlroot_respond = lxmlElementTree.fromstring(response.content)
-            namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
+            namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
             namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
             catalogitem_remove_href = lxmlroot_respond.find("xmlns:Link[@rel='remove']",namespaces).attrib['href']
 
             namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
             catalogitem_remove_href = lxmlroot_respond.find("xmlns:Link[@rel='remove']",namespaces).attrib['href']
 
@@ -982,8 +985,8 @@ class vimconnector(vimconn.vimconnector):
             for catalog in vca.get_catalogs():
                 if catalog_name != catalog.name:
                     continue
             for catalog in vca.get_catalogs():
                 if catalog_name != catalog.name:
                     continue
-                link = [link for link in catalog.get_Link() if link.get_type() == "application/vnd.vmware.vcloud.media+xml" and
-                                           link.get_rel() == 'add']
+                link = filter(lambda link: link.get_type() == "application/vnd.vmware.vcloud.media+xml" and
+                                           link.get_rel() == 'add', catalog.get_Link())
                 assert len(link) == 1
                 data = """
                 <UploadVAppTemplateParams name="%s" xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"><Description>%s vApp Template</Description></UploadVAppTemplateParams>
                 assert len(link) == 1
                 data = """
                 <UploadVAppTemplateParams name="%s" xmlns="http://www.vmware.com/vcloud/v1.5" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"><Description>%s vApp Template</Description></UploadVAppTemplateParams>
@@ -1031,8 +1034,9 @@ class vimconnector(vimconn.vimconnector):
                     if response.status_code == requests.codes.ok:
                         media = mediaType.parseString(response.content, True)
                         number_of_files = len(media.get_Files().get_File())
                     if response.status_code == requests.codes.ok:
                         media = mediaType.parseString(response.content, True)
                         number_of_files = len(media.get_Files().get_File())
-                        for index in range(0, number_of_files):
-                            links_list = [link for link in media.get_Files().get_File()[index].get_Link() if link.get_rel() == 'upload:default']
+                        for index in xrange(0, number_of_files):
+                            links_list = filter(lambda link: link.get_rel() == 'upload:default',
+                                                media.get_Files().get_File()[index].get_Link())
                             for link in links_list:
                                 # we skip ovf since it already uploaded.
                                 if 'ovf' in link.get_href():
                             for link in links_list:
                                 # we skip ovf since it already uploaded.
                                 if 'ovf' in link.get_href():
@@ -1048,7 +1052,7 @@ class vimconnector(vimconn.vimconnector):
                                 hrefvmdk = link.get_href()
 
                                 if progress:
                                 hrefvmdk = link.get_href()
 
                                 if progress:
-                                    print(("Uploading file: {}".format(file_vmdk)))
+                                    print("Uploading file: {}".format(file_vmdk))
                                 if progress:
                                     widgets = ['Uploading file: ', Percentage(), ' ', Bar(), ' ', ETA(), ' ',
                                                FileTransferSpeed()]
                                 if progress:
                                     widgets = ['Uploading file: ', Percentage(), ' ', Bar(), ' ', ETA(), ' ',
                                                FileTransferSpeed()]
@@ -1302,7 +1306,8 @@ class vimconnector(vimconn.vimconnector):
             return None
         # UUID has following format https://host/api/vApp/vapp-30da58a3-e7c7-4d09-8f68-d4c8201169cf
         try:
             return None
         # UUID has following format https://host/api/vApp/vapp-30da58a3-e7c7-4d09-8f68-d4c8201169cf
         try:
-            refs = [ref for ref in vdc.ResourceEntities.ResourceEntity if ref.name == vapp_name and ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml']
+            refs = filter(lambda ref: ref.name == vapp_name and ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml',
+                          vdc.ResourceEntities.ResourceEntity)
             if len(refs) == 1:
                 return refs[0].href.split("vapp")[1][1:]
         except Exception as e:
             if len(refs) == 1:
                 return refs[0].href.split("vapp")[1][1:]
         except Exception as e:
@@ -1324,7 +1329,9 @@ class vimconnector(vimconn.vimconnector):
                 :param vapp_uuid:
         """
         try:
                 :param vapp_uuid:
         """
         try:
-            refs = [ref for ref in vdc.ResourceEntities.ResourceEntity if ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml']
+            refs = filter(lambda ref:
+                          ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml',
+                          vdc.ResourceEntities.ResourceEntity)
             for ref in refs:
                 vappid = ref.href.split("vapp")[1][1:]
                 # find vapp with respected vapp uuid
             for ref in refs:
                 vappid = ref.href.split("vapp")[1][1:]
                 # find vapp with respected vapp uuid
@@ -1348,7 +1355,8 @@ class vimconnector(vimconn.vimconnector):
         """
 
         try:
         """
 
         try:
-            refs = [ref for ref in vdc.ResourceEntities.ResourceEntity if ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml']
+            refs = filter(lambda ref: ref.type_ == 'application/vnd.vmware.vcloud.vApp+xml',
+                          vdc.ResourceEntities.ResourceEntity)
             for ref in refs:
                 # we care only about UUID the rest doesn't matter
                 vappid = ref.href.split("vapp")[1][1:]
             for ref in refs:
                 # we care only about UUID the rest doesn't matter
                 vappid = ref.href.split("vapp")[1][1:]
@@ -1484,7 +1492,7 @@ class vimconnector(vimconn.vimconnector):
 
         # client must provide at least one entry in net_list if not we report error
         #If net type is mgmt, then configure it as primary net & use its NIC index as primary NIC
 
         # client must provide at least one entry in net_list if not we report error
         #If net type is mgmt, then configure it as primary net & use its NIC index as primary NIC
-        #If no mgmt, then the 1st NN in netlist is considered as primary net. 
+        #If no mgmt, then the 1st NN in netlist is considered as primary net.
         primary_net = None
         primary_netname = None
         network_mode = 'bridged'
         primary_net = None
         primary_netname = None
         network_mode = 'bridged'
@@ -1651,7 +1659,7 @@ class vimconnector(vimconn.vimconnector):
                                   - NONE (No IP addressing mode specified.)"""
 
                 if primary_netname is not None:
                                   - NONE (No IP addressing mode specified.)"""
 
                 if primary_netname is not None:
-                    nets = [n for n in self.vca.get_networks(self.tenant_name) if n.name == interface_net_name]
+                    nets = filter(lambda n: n.name == interface_net_name, self.vca.get_networks(self.tenant_name))
                     if len(nets) == 1:
                         self.logger.info("new_vminstance(): Found requested network: {}".format(nets[0].name))
 
                     if len(nets) == 1:
                         self.logger.info("new_vminstance(): Found requested network: {}".format(nets[0].name))
 
@@ -1901,7 +1909,7 @@ class vimconnector(vimconn.vimconnector):
                         wait_time +=INTERVAL_TIME
 
                     if not undeployed:
                         wait_time +=INTERVAL_TIME
 
                     if not undeployed:
-                        self.logger.debug("delete_vminstance(): Failed to undeploy vApp {} ".format(vm__vim_uuid)) 
+                        self.logger.debug("delete_vminstance(): Failed to undeploy vApp {} ".format(vm__vim_uuid))
 
                 # delete vapp
                 self.logger.info("Start deletion of vApp {} ".format(vapp_name))
 
                 # delete vapp
                 self.logger.info("Start deletion of vApp {} ".format(vapp_name))
@@ -2170,7 +2178,7 @@ class vimconnector(vimconn.vimconnector):
                 result = self.vca.block_until_completed(power_task)
                 self.instance_actions_result("resume", result, vapp_name)
             elif "shutoff" in action_dict or "shutdown" in action_dict:
                 result = self.vca.block_until_completed(power_task)
                 self.instance_actions_result("resume", result, vapp_name)
             elif "shutoff" in action_dict or "shutdown" in action_dict:
-                action_name , value = list(action_dict.items())[0]
+                action_name , value = action_dict.items()[0]
                 self.logger.info("action_vminstance: {} vApp: {}".format(action_name, vapp_name))
                 power_off_task = the_vapp.undeploy(action='powerOff')
                 result = self.vca.block_until_completed(power_off_task)
                 self.logger.info("action_vminstance: {} vApp: {}".format(action_name, vapp_name))
                 power_off_task = the_vapp.undeploy(action='powerOff')
                 result = self.vca.block_until_completed(power_off_task)
@@ -2304,7 +2312,7 @@ class vimconnector(vimconn.vimconnector):
             org_dict = self.get_org(self.org_uuid)
             if org_dict and 'networks' in org_dict:
                 org_network_dict = org_dict['networks']
             org_dict = self.get_org(self.org_uuid)
             if org_dict and 'networks' in org_dict:
                 org_network_dict = org_dict['networks']
-                for net_uuid,net_name in org_network_dict.items():
+                for net_uuid,net_name in org_network_dict.iteritems():
                     if net_name == network_name:
                         return net_uuid
 
                     if net_name == network_name:
                         return net_uuid
 
@@ -2458,7 +2466,8 @@ class vimconnector(vimconn.vimconnector):
         vm_list_rest_call = ''.join(url_list)
 
         if not (not vca.vcloud_session or not vca.vcloud_session.organization):
         vm_list_rest_call = ''.join(url_list)
 
         if not (not vca.vcloud_session or not vca.vcloud_session.organization):
-            refs = [ref for ref in vca.vcloud_session.organization.Link if ref.name == vdc_name and ref.type_ == 'application/vnd.vmware.vcloud.vdc+xml']
+            refs = filter(lambda ref: ref.name == vdc_name and ref.type_ == 'application/vnd.vmware.vcloud.vdc+xml',
+                          vca.vcloud_session.organization.Link)
             if len(refs) == 1:
                 response = Http.get(url=vm_list_rest_call,
                                     headers=vca.vcloud_session.get_vcloud_headers(),
             if len(refs) == 1:
                 response = Http.get(url=vm_list_rest_call,
                                     headers=vca.vcloud_session.get_vcloud_headers(),
@@ -3393,7 +3402,7 @@ class vimconnector(vimconn.vimconnector):
             return None
         try:
             lxmlroot_respond = lxmlElementTree.fromstring(response.content)
             return None
         try:
             lxmlroot_respond = lxmlElementTree.fromstring(response.content)
-            namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
+            namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
             namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
 
             for item in lxmlroot_respond.iterfind('xmlns:Item',namespaces):
             namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
 
             for item in lxmlroot_respond.iterfind('xmlns:Item',namespaces):
@@ -4222,7 +4231,7 @@ class vimconnector(vimconn.vimconnector):
         try:
             #Find but type & max of instance IDs assigned to disks
             lxmlroot_respond = lxmlElementTree.fromstring(response.content)
         try:
             #Find but type & max of instance IDs assigned to disks
             lxmlroot_respond = lxmlElementTree.fromstring(response.content)
-            namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.items() if prefix}
+            namespaces = {prefix:uri for prefix,uri in lxmlroot_respond.nsmap.iteritems() if prefix}
             namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
             instance_id = 0
             for item in lxmlroot_respond.iterfind('xmlns:Item',namespaces):
             namespaces["xmlns"]= "http://www.vmware.com/vcloud/v1.5"
             instance_id = 0
             for item in lxmlroot_respond.iterfind('xmlns:Item',namespaces):
@@ -4498,7 +4507,7 @@ class vimconnector(vimconn.vimconnector):
             catalog = self.get_catalog_obj(image_id, catalogs)
             if catalog:
                 template_name = self.get_catalogbyid(image_id, catalogs)
             catalog = self.get_catalog_obj(image_id, catalogs)
             if catalog:
                 template_name = self.get_catalogbyid(image_id, catalogs)
-                catalog_items = [catalogItemRef for catalogItemRef in catalog.get_CatalogItems().get_CatalogItem() if catalogItemRef.get_name() == template_name]
+                catalog_items = filter(lambda catalogItemRef: catalogItemRef.get_name() == template_name, catalog.get_CatalogItems().get_CatalogItem())
                 if len(catalog_items) == 1:
                     response = Http.get(catalog_items[0].get_href(),
                                         headers=vca.vcloud_session.get_vcloud_headers(),
                 if len(catalog_items) == 1:
                     response = Http.get(catalog_items[0].get_href(),
                                         headers=vca.vcloud_session.get_vcloud_headers(),
@@ -4956,7 +4965,7 @@ class vimconnector(vimconn.vimconnector):
         if "used_vlanIDs" not in self.persistent_info:
                 self.persistent_info["used_vlanIDs"] = {}
         else:
         if "used_vlanIDs" not in self.persistent_info:
                 self.persistent_info["used_vlanIDs"] = {}
         else:
-            used_ids = list(self.persistent_info["used_vlanIDs"].values())
+            used_ids = self.persistent_info["used_vlanIDs"].values()
 
         for vlanID_range in self.config.get('vlanID_range'):
             start_vlanid , end_vlanid = vlanID_range.split("-")
 
         for vlanID_range in self.config.get('vlanID_range'):
             start_vlanid , end_vlanid = vlanID_range.split("-")
@@ -4964,7 +4973,7 @@ class vimconnector(vimconn.vimconnector):
                 raise vimconn.vimconnConflictException("Invalid vlan ID range {}".format(
                                                                         vlanID_range))
 
                 raise vimconn.vimconnConflictException("Invalid vlan ID range {}".format(
                                                                         vlanID_range))
 
-            for id in range(int(start_vlanid), int(end_vlanid) + 1):
+            for id in xrange(int(start_vlanid), int(end_vlanid) + 1):
                 if id not in used_ids:
                     vlan_id = id
                     self.persistent_info["used_vlanIDs"][network_name] = vlan_id
                 if id not in used_ids:
                     vlan_id = id
                     self.persistent_info["used_vlanIDs"][network_name] = vlan_id
@@ -5192,5 +5201,3 @@ class vimconnector(vimconn.vimconnector):
             vdc = self.vca.get_vdc(self.tenant_name)
 
         return vdc
             vdc = self.vca.get_vdc(self.tenant_name)
 
         return vdc
-
-
index 4e5898e..cbfb737 100644 (file)
@@ -49,7 +49,7 @@ class CommandProgressbar(object):
             Args  : None
             Return : None
         """
             Args  : None
             Return : None
         """
-        print('\b.', end=' ')
+        print '\b.',
         sys.stdout.flush()
 
     def start_progressbar(self):
         sys.stdout.flush()
 
     def start_progressbar(self):
index 43981ac..3c647a9 100644 (file)
@@ -27,7 +27,7 @@ import os
 import subprocess
 import yaml
 from lxml import etree as ET
 import subprocess
 import yaml
 from lxml import etree as ET
-from .command_progress import CommandProgressbar
+from command_progress import CommandProgressbar
 
 #file paths
 MODULE_DIR = os.path.dirname(__file__)
 
 #file paths
 MODULE_DIR = os.path.dirname(__file__)
@@ -288,7 +288,7 @@ class OVFConverter(object):
             root = OVF_tree.getroot()
 
             #Collect namespaces
             root = OVF_tree.getroot()
 
             #Collect namespaces
-            nsmap = {k:v for k,v in root.nsmap.items() if k}
+            nsmap = {k:v for k,v in root.nsmap.iteritems() if k}
             nsmap["xmlns"]= "http://schemas.dmtf.org/ovf/envelope/1"
 
             #Edit OVF template
             nsmap["xmlns"]= "http://schemas.dmtf.org/ovf/envelope/1"
 
             #Edit OVF template
@@ -370,7 +370,7 @@ class OVFConverter(object):
 
             if os.path.isfile(self.output_path):
                 logger.info("Successfully written output OVF at {}".format(self.output_path))
 
             if os.path.isfile(self.output_path):
                 logger.info("Successfully written output OVF at {}".format(self.output_path))
-                print(("Output OVF is at :  {}".format(self.output_path)))
+                print("Output OVF is at :  {}".format(self.output_path))
                 return self.output_path
             else:
                 error_msg = "ERROR: Error occurred while creating OVF file"
                 return self.output_path
             else:
                 error_msg = "ERROR: Error occurred while creating OVF file"
@@ -431,7 +431,7 @@ class OVFConverter(object):
         os_info = self.__read_yaml_file(OS_INFO_FILE_PATH)
         try:
             if self.os_type and os_info:
         os_info = self.__read_yaml_file(OS_INFO_FILE_PATH)
         try:
             if self.os_type and os_info:
-                for os_id , os_type in os_info.items():
+                for os_id , os_type in os_info.iteritems():
                     if self.os_type.lower() == os_type.lower():
                         osID = os_id
                         osType = os_type
                     if self.os_type.lower() == os_type.lower():
                         osID = os_id
                         osType = os_type
@@ -461,7 +461,7 @@ class OVFConverter(object):
         disk_controller_info = self.__read_yaml_file(DISK_CONTROLLER_INFO_FILE_PATH)
         try:
             if self.disk_controller and disk_controller_info:
         disk_controller_info = self.__read_yaml_file(DISK_CONTROLLER_INFO_FILE_PATH)
         try:
             if self.disk_controller and disk_controller_info:
-                for key , value in disk_controller_info.items():
+                for key , value in disk_controller_info.iteritems():
                     if self.disk_controller.lower() in key.lower():
                         disk_controller['controllerName'] = key
                         disk_controller['resourceType'] = str(value["ResourceType"])
                     if self.disk_controller.lower() in key.lower():
                         disk_controller['controllerName'] = key
                         disk_controller['resourceType'] = str(value["ResourceType"])
index 63e4a25..209c05d 100644 (file)
@@ -23,7 +23,7 @@
 ##
 
 import argparse
 ##
 
 import argparse
-from .converter import OVFConverter , get_version
+from converter import OVFConverter , get_version
 
 def execute_cli():
 
 
 def execute_cli():
 
index 89f7807..4583a65 100755 (executable)
@@ -67,13 +67,13 @@ import sys
 from pyvcloud import Http
 
 import logging
 from pyvcloud import Http
 
 import logging
-from . import vimconn
+import vimconn
 import time
 import uuid
 import urllib3
 import requests
 
 import time
 import uuid
 import urllib3
 import requests
 
-from .vimconn_vmware import vimconnector
+from vimconn_vmware import vimconnector
 from requests.packages.urllib3.exceptions import InsecureRequestWarning
 from prettytable import PrettyTable
 
 from requests.packages.urllib3.exceptions import InsecureRequestWarning
 from prettytable import PrettyTable
 
@@ -108,7 +108,7 @@ def delete_network_action(vca=None, network_uuid=None):
                             verify=vca.verify,
                             logger=vca.logger)
         if response.status_code == requests.codes.ok:
                             verify=vca.verify,
                             logger=vca.logger)
         if response.status_code == requests.codes.ok:
-            print(response.content)
+            print response.content
             return response.content
 
     return None
             return response.content
 
     return None
@@ -161,7 +161,7 @@ def print_vapp(vapp_dict=None):
 
         vm_table.add_row(entry)
 
 
         vm_table.add_row(entry)
 
-    print(vm_table)
+    print vm_table
 
 
 def print_org(org_dict=None):
 
 
 def print_org(org_dict=None):
@@ -182,7 +182,7 @@ def print_org(org_dict=None):
         entry = [k, org_dict[k]]
         org_table.add_row(entry)
 
         entry = [k, org_dict[k]]
         org_table.add_row(entry)
 
-    print(org_table)
+    print org_table
 
 
 def print_vm_list(vm_dict=None):
 
 
 def print_vm_list(vm_dict=None):
@@ -213,7 +213,7 @@ def print_vm_list(vm_dict=None):
             entry.append(vm_dict[k]['memoryMB'])
             entry.append(vm_dict[k]['status'])
             vm_table.add_row(entry)
             entry.append(vm_dict[k]['memoryMB'])
             entry.append(vm_dict[k]['status'])
             vm_table.add_row(entry)
-        print(vm_table)
+        print vm_table
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
         pass
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
         pass
@@ -232,14 +232,14 @@ def print_vdc_list(org_dict=None):
         return
     try:
         vdcs_dict = {}
         return
     try:
         vdcs_dict = {}
-        if 'vdcs' in org_dict:
+        if org_dict.has_key('vdcs'):
             vdcs_dict = org_dict['vdcs']
         vdc_table = PrettyTable(['vdc uuid', 'vdc name'])
         for k in vdcs_dict:
             entry = [k, vdcs_dict[k]]
             vdc_table.add_row(entry)
 
             vdcs_dict = org_dict['vdcs']
         vdc_table = PrettyTable(['vdc uuid', 'vdc name'])
         for k in vdcs_dict:
             entry = [k, vdcs_dict[k]]
             vdc_table.add_row(entry)
 
-        print(vdc_table)
+        print vdc_table
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
         logger.logger.debug(traceback.format_exc())
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
         logger.logger.debug(traceback.format_exc())
@@ -259,14 +259,14 @@ def print_network_list(org_dict=None):
         return
     try:
         network_dict = {}
         return
     try:
         network_dict = {}
-        if 'networks' in org_dict:
+        if org_dict.has_key('networks'):
             network_dict = org_dict['networks']
         network_table = PrettyTable(['network uuid', 'network name'])
         for k in network_dict:
             entry = [k, network_dict[k]]
             network_table.add_row(entry)
 
             network_dict = org_dict['networks']
         network_table = PrettyTable(['network uuid', 'network name'])
         for k in network_dict:
             entry = [k, network_dict[k]]
             network_table.add_row(entry)
 
-        print(network_table)
+        print network_table
 
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
 
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
@@ -290,7 +290,7 @@ def print_org_details(org_dict=None):
         print_vdc_list(org_dict=org_dict)
         print_network_list(org_dict=org_dict)
 
         print_vdc_list(org_dict=org_dict)
         print_network_list(org_dict=org_dict)
 
-        if 'catalogs' in org_dict:
+        if org_dict.has_key('catalogs'):
             catalogs_dict = org_dict['catalogs']
 
         catalog_table = PrettyTable(['catalog uuid', 'catalog name'])
             catalogs_dict = org_dict['catalogs']
 
         catalog_table = PrettyTable(['catalog uuid', 'catalog name'])
@@ -298,7 +298,7 @@ def print_org_details(org_dict=None):
             entry = [k, catalogs_dict[k]]
             catalog_table.add_row(entry)
 
             entry = [k, catalogs_dict[k]]
             catalog_table.add_row(entry)
 
-        print(catalog_table)
+        print catalog_table
 
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
 
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
@@ -368,10 +368,10 @@ def list_actions(vim=None, action=None, namespace=None):
 
 def print_network_details(network_dict=None):
     try:
 
 def print_network_details(network_dict=None):
     try:
-        network_table = PrettyTable(list(network_dict.keys()))
-        entry = [list(network_dict.values())]
+        network_table = PrettyTable(network_dict.keys())
+        entry = [network_dict.values()]
         network_table.add_row(entry[0])
         network_table.add_row(entry[0])
-        print(network_table)
+        print network_table
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
         logger.logger.debug(traceback.format_exc())
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
         logger.logger.debug(traceback.format_exc())
@@ -381,10 +381,10 @@ def osm_print(generic_dict=None):
 
     try:
         for element in generic_dict:
 
     try:
         for element in generic_dict:
-            table = PrettyTable(list(element.keys()))
-            entry = [list(element.values())]
+            table = PrettyTable(element.keys())
+            entry = [element.values()]
             table.add_row(entry[0])
             table.add_row(entry[0])
-        print(table)
+        print table
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
         logger.logger.debug(traceback.format_exc())
     except KeyError:
         logger.error("wrong key {}".format(KeyError.message))
         logger.logger.debug(traceback.format_exc())
@@ -430,13 +430,13 @@ def view_actions(vim=None, action=None, namespace=None):
             if not namespace.uuid:
                 vapp_uuid = vim.get_vappid(vdc=namespace.vcdvdc, vapp_name=namespace.vapp_name)
                 if vapp_uuid is None:
             if not namespace.uuid:
                 vapp_uuid = vim.get_vappid(vdc=namespace.vcdvdc, vapp_name=namespace.vapp_name)
                 if vapp_uuid is None:
-                    print(("Can't find vapp by given name {}".format(namespace.vapp_name)))
+                    print("Can't find vapp by given name {}".format(namespace.vapp_name))
                     return
 
                     return
 
-            print(" namespace {}".format(namespace))
+            print " namespace {}".format(namespace)
             if vapp_dict is not None and namespace.osm:
                 vm_info_dict = vim.get_vminstance(vim_vm_uuid=vapp_uuid)
             if vapp_dict is not None and namespace.osm:
                 vm_info_dict = vim.get_vminstance(vim_vm_uuid=vapp_uuid)
-                print(vm_info_dict)
+                print vm_info_dict
             if vapp_dict is not None and namespace.osm != True:
                 vapp_dict = vim.get_vapp(vdc_name=namespace.vcdvdc, vapp_name=vapp_uuid, isuuid=True)
                 print_vapp(vapp_dict=vapp_dict)
             if vapp_dict is not None and namespace.osm != True:
                 vapp_dict = vim.get_vapp(vdc_name=namespace.vcdvdc, vapp_name=vapp_uuid, isuuid=True)
                 print_vapp(vapp_dict=vapp_dict)
@@ -448,10 +448,10 @@ def view_actions(vim=None, action=None, namespace=None):
         # if request name based we need find UUID
         # TODO optimize it or move to external function
         if not namespace.uuid:
         # if request name based we need find UUID
         # TODO optimize it or move to external function
         if not namespace.uuid:
-            if 'networks' not in myorg:
-                print(("Network {} is undefined in vcloud director for org {} vdc {}".format(namespace.network_name,
+            if not myorg.has_key('networks'):
+                print("Network {} is undefined in vcloud director for org {} vdc {}".format(namespace.network_name,
                                                                                             vim.name,
                                                                                             vim.name,
-                                                                                            vim.tenant_name)))
+                                                                                            vim.tenant_name))
                 return
 
             my_org_net = myorg['networks']
                 return
 
             my_org_net = myorg['networks']
@@ -460,7 +460,7 @@ def view_actions(vim=None, action=None, namespace=None):
                     network_uuid = network
                     break
 
                     network_uuid = network
                     break
 
-        print(print_network_details(network_dict=vim.get_vcd_network(network_uuid=network_uuid)))
+        print print_network_details(network_dict=vim.get_vcd_network(network_uuid=network_uuid))
 
 
 def create_actions(vim=None, action=None, namespace=None):
 
 
 def create_actions(vim=None, action=None, namespace=None):
@@ -477,16 +477,16 @@ def create_actions(vim=None, action=None, namespace=None):
         logger.debug("Creating a network in vcloud director".format(namespace.network_name))
         network_uuid = vim.create_network(namespace.network_name)
         if network_uuid is not None:
         logger.debug("Creating a network in vcloud director".format(namespace.network_name))
         network_uuid = vim.create_network(namespace.network_name)
         if network_uuid is not None:
-            print(("Crated new network {} and uuid: {}".format(namespace.network_name, network_uuid)))
+            print ("Crated new network {} and uuid: {}".format(namespace.network_name, network_uuid))
         else:
         else:
-            print(("Failed create a new network {}".format(namespace.network_name)))
+            print ("Failed create a new network {}".format(namespace.network_name))
     elif action == 'vdc' or namespace.action == 'vdc':
         logger.debug("Creating a new vdc in vcloud director.".format(namespace.vdc_name))
         vdc_uuid = vim.create_vdc(namespace.vdc_name)
         if vdc_uuid is not None:
     elif action == 'vdc' or namespace.action == 'vdc':
         logger.debug("Creating a new vdc in vcloud director.".format(namespace.vdc_name))
         vdc_uuid = vim.create_vdc(namespace.vdc_name)
         if vdc_uuid is not None:
-            print(("Crated new vdc {} and uuid: {}".format(namespace.vdc_name, vdc_uuid)))
+            print ("Crated new vdc {} and uuid: {}".format(namespace.vdc_name, vdc_uuid))
         else:
         else:
-            print(("Failed create a new vdc {}".format(namespace.vdc_name)))
+            print ("Failed create a new vdc {}".format(namespace.vdc_name))
     else:
         return None
 
     else:
         return None
 
@@ -519,11 +519,11 @@ def upload_image(vim=None, image_file=None):
     try:
         catalog_uuid = vim.get_image_id_from_path(path=image_file, progress=True)
         if catalog_uuid is not None and validate_uuid4(catalog_uuid):
     try:
         catalog_uuid = vim.get_image_id_from_path(path=image_file, progress=True)
         if catalog_uuid is not None and validate_uuid4(catalog_uuid):
-            print(("Image uploaded and uuid {}".format(catalog_uuid)))
+            print("Image uploaded and uuid {}".format(catalog_uuid))
             return True
     except vimconn.vimconnException as upload_exception:
             return True
     except vimconn.vimconnException as upload_exception:
-        print(("Failed uploaded {} image".format(image_file)))
-        print(("Error Reason: {}".format(upload_exception.message)))
+        print("Failed uploaded {} image".format(image_file))
+        print("Error Reason: {}".format(upload_exception.message))
     return False
 
 
     return False
 
 
@@ -553,22 +553,22 @@ def boot_image(vim=None, image_name=None, vm_name=None):
             if vim_catalog is None:
                 return None
 
             if vim_catalog is None:
                 return None
 
-        print((" Booting {} image id {} ".format(vm_name, vim_catalog)))
+        print (" Booting {} image id {} ".format(vm_name, vim_catalog))
         vm_uuid = vim.new_vminstance(name=vm_name, image_id=vim_catalog)
         if vm_uuid is not None and validate_uuid4(vm_uuid):
         vm_uuid = vim.new_vminstance(name=vm_name, image_id=vim_catalog)
         if vm_uuid is not None and validate_uuid4(vm_uuid):
-            print(("Image booted and vm uuid {}".format(vm_uuid)))
+            print("Image booted and vm uuid {}".format(vm_uuid))
             vapp_dict = vim.get_vapp(vdc_name=namespace.vcdvdc, vapp_name=vm_uuid, isuuid=True)
             if vapp_dict is not None:
                 print_vapp(vapp_dict=vapp_dict)
         return True
     except vimconn.vimconnNotFoundException as notFound:
             vapp_dict = vim.get_vapp(vdc_name=namespace.vcdvdc, vapp_name=vm_uuid, isuuid=True)
             if vapp_dict is not None:
                 print_vapp(vapp_dict=vapp_dict)
         return True
     except vimconn.vimconnNotFoundException as notFound:
-        print(("Failed boot {} image".format(image_name)))
-        print((notFound.message))
+        print("Failed boot {} image".format(image_name))
+        print(notFound.message)
     except vimconn.vimconnException as vimconError:
     except vimconn.vimconnException as vimconError:
-        print(("Failed boot {} image".format(image_name)))
-        print((vimconError.message))
+        print("Failed boot {} image".format(image_name))
+        print(vimconError.message)
     except:
     except:
-        print(("Failed boot {} image".format(image_name)))
+        print("Failed boot {} image".format(image_name))
 
 
         return False
 
 
         return False
@@ -611,7 +611,7 @@ def vmwarecli(command=None, action=None, namespace=None):
 
     if namespace.vcdvdc is None:
         while True:
 
     if namespace.vcdvdc is None:
         while True:
-            vcduser = eval(input("Enter vcd username: "))
+            vcduser = input("Enter vcd username: ")
             if vcduser is not None and len(vcduser) > 0:
                 break
     else:
             if vcduser is not None and len(vcduser) > 0:
                 break
     else:
@@ -619,7 +619,7 @@ def vmwarecli(command=None, action=None, namespace=None):
 
     if namespace.vcdpassword is None:
         while True:
 
     if namespace.vcdpassword is None:
         while True:
-            vcdpasword = eval(input("Please enter vcd password: "))
+            vcdpasword = input("Please enter vcd password: ")
             if vcdpasword is not None and len(vcdpasword) > 0:
                 break
     else:
             if vcdpasword is not None and len(vcdpasword) > 0:
                 break
     else:
@@ -627,7 +627,7 @@ def vmwarecli(command=None, action=None, namespace=None):
 
     if namespace.vcdhost is None:
         while True:
 
     if namespace.vcdhost is None:
         while True:
-            vcdhost = eval(input("Please enter vcd host name or ip: "))
+            vcdhost = input("Please enter vcd host name or ip: ")
             if vcdhost is not None and len(vcdhost) > 0:
                 break
     else:
             if vcdhost is not None and len(vcdhost) > 0:
                 break
     else:
@@ -635,7 +635,7 @@ def vmwarecli(command=None, action=None, namespace=None):
 
     if namespace.vcdorg is None:
         while True:
 
     if namespace.vcdorg is None:
         while True:
-            vcdorg = eval(input("Please enter vcd organization name: "))
+            vcdorg = input("Please enter vcd organization name: ")
             if vcdorg is not None and len(vcdorg) > 0:
                 break
     else:
             if vcdorg is not None and len(vcdorg) > 0:
                 break
     else:
@@ -797,7 +797,7 @@ if __name__ == '__main__':
 
     namespace = parser.parse_args()
     # put command_line args to mapping
 
     namespace = parser.parse_args()
     # put command_line args to mapping
-    command_line_args = {k: v for k, v in list(vars(namespace).items()) if v}
+    command_line_args = {k: v for k, v in vars(namespace).items() if v}
 
     d = defaults.copy()
     d.update(os.environ)
 
     d = defaults.copy()
     d.update(os.environ)
index bbb5e29..1667ec6 100755 (executable)
@@ -66,13 +66,13 @@ import sys
 from pyvcloud import Http
 
 import logging
 from pyvcloud import Http
 
 import logging
-from . import vimconn
+import vimconn
 import time
 import uuid
 import urllib3
 import requests
 
 import time
 import uuid
 import urllib3
 import requests
 
-from .vimconn_vmware import vimconnector
+from vimconn_vmware import vimconnector
 from requests.packages.urllib3.exceptions import InsecureRequestWarning
 from prettytable import PrettyTable
 
 from requests.packages.urllib3.exceptions import InsecureRequestWarning
 from prettytable import PrettyTable
 
@@ -231,7 +231,7 @@ def print_vdc_list(org_dict=None):
         return
     try:
         vdcs_dict = {}
         return
     try:
         vdcs_dict = {}
-        if 'vdcs' in org_dict:
+        if org_dict.has_key('vdcs'):
             vdcs_dict = org_dict['vdcs']
         vdc_table = PrettyTable(['vdc uuid', 'vdc name'])
         for k in vdcs_dict:
             vdcs_dict = org_dict['vdcs']
         vdc_table = PrettyTable(['vdc uuid', 'vdc name'])
         for k in vdcs_dict:
@@ -258,7 +258,7 @@ def print_network_list(org_dict=None):
         return
     try:
         network_dict = {}
         return
     try:
         network_dict = {}
-        if 'networks' in org_dict:
+        if org_dict.has_key('networks'):
             network_dict = org_dict['networks']
         network_table = PrettyTable(['network uuid', 'network name'])
         for k in network_dict:
             network_dict = org_dict['networks']
         network_table = PrettyTable(['network uuid', 'network name'])
         for k in network_dict:
@@ -289,7 +289,7 @@ def print_org_details(org_dict=None):
         print_vdc_list(org_dict=org_dict)
         print_network_list(org_dict=org_dict)
 
         print_vdc_list(org_dict=org_dict)
         print_network_list(org_dict=org_dict)
 
-        if 'catalogs' in org_dict:
+        if org_dict.has_key('catalogs'):
             catalogs_dict = org_dict['catalogs']
 
         catalog_table = PrettyTable(['catalog uuid', 'catalog name'])
             catalogs_dict = org_dict['catalogs']
 
         catalog_table = PrettyTable(['catalog uuid', 'catalog name'])
@@ -367,8 +367,8 @@ def list_actions(vim=None, action=None, namespace=None):
 
 def print_network_details(network_dict=None):
     try:
 
 def print_network_details(network_dict=None):
     try:
-        network_table = PrettyTable(list(network_dict.keys()))
-        entry = [list(network_dict.values())]
+        network_table = PrettyTable(network_dict.keys())
+        entry = [network_dict.values()]
         network_table.add_row(entry[0])
         print(network_table)
     except KeyError:
         network_table.add_row(entry[0])
         print(network_table)
     except KeyError:
@@ -380,8 +380,8 @@ def osm_print(generic_dict=None):
 
     try:
         for element in generic_dict:
 
     try:
         for element in generic_dict:
-            table = PrettyTable(list(element.keys()))
-            entry = [list(element.values())]
+            table = PrettyTable(element.keys())
+            entry = [element.values()]
             table.add_row(entry[0])
         print(table)
     except KeyError:
             table.add_row(entry[0])
         print(table)
     except KeyError:
@@ -429,13 +429,13 @@ def view_actions(vim=None, action=None, namespace=None):
             if not namespace.uuid:
                 vapp_uuid = vim.get_vappid(vdc=namespace.vcdvdc, vapp_name=namespace.vapp_name)
                 if vapp_uuid is None:
             if not namespace.uuid:
                 vapp_uuid = vim.get_vappid(vdc=namespace.vcdvdc, vapp_name=namespace.vapp_name)
                 if vapp_uuid is None:
-                    print(("Can't find vapp by given name {}".format(namespace.vapp_name)))
+                    print("Can't find vapp by given name {}".format(namespace.vapp_name))
                     return
 
                     return
 
-            print(" namespace {}".format(namespace))
+            print " namespace {}".format(namespace)
             if vapp_dict is not None and namespace.osm:
                 vm_info_dict = vim.get_vminstance(vim_vm_uuid=vapp_uuid)
             if vapp_dict is not None and namespace.osm:
                 vm_info_dict = vim.get_vminstance(vim_vm_uuid=vapp_uuid)
-                print(vm_info_dict)
+                print vm_info_dict
             if vapp_dict is not None and namespace.osm != True:
                 vapp_dict = vim.get_vapp(vdc_name=namespace.vcdvdc, vapp_name=vapp_uuid, isuuid=True)
                 print_vapp(vapp_dict=vapp_dict)
             if vapp_dict is not None and namespace.osm != True:
                 vapp_dict = vim.get_vapp(vdc_name=namespace.vcdvdc, vapp_name=vapp_uuid, isuuid=True)
                 print_vapp(vapp_dict=vapp_dict)
@@ -447,10 +447,10 @@ def view_actions(vim=None, action=None, namespace=None):
         # if request name based we need find UUID
         # TODO optimize it or move to external function
         if not namespace.uuid:
         # if request name based we need find UUID
         # TODO optimize it or move to external function
         if not namespace.uuid:
-            if 'networks' not in myorg:
-                print(("Network {} is undefined in vcloud director for org {} vdc {}".format(namespace.network_name,
+            if not myorg.has_key('networks'):
+                print("Network {} is undefined in vcloud director for org {} vdc {}".format(namespace.network_name,
                                                                                             vim.name,
                                                                                             vim.name,
-                                                                                            vim.tenant_name)))
+                                                                                            vim.tenant_name))
                 return
 
             my_org_net = myorg['networks']
                 return
 
             my_org_net = myorg['networks']
@@ -459,7 +459,7 @@ def view_actions(vim=None, action=None, namespace=None):
                     network_uuid = network
                     break
 
                     network_uuid = network
                     break
 
-        print(print_network_details(network_dict=vim.get_vcd_network(network_uuid=network_uuid)))
+        print print_network_details(network_dict=vim.get_vcd_network(network_uuid=network_uuid))
 
 
 def create_actions(vim=None, action=None, namespace=None):
 
 
 def create_actions(vim=None, action=None, namespace=None):
@@ -476,16 +476,16 @@ def create_actions(vim=None, action=None, namespace=None):
         logger.debug("Creating a network in vcloud director".format(namespace.network_name))
         network_uuid = vim.create_network(namespace.network_name)
         if network_uuid is not None:
         logger.debug("Creating a network in vcloud director".format(namespace.network_name))
         network_uuid = vim.create_network(namespace.network_name)
         if network_uuid is not None:
-            print(("Crated new network {} and uuid: {}".format(namespace.network_name, network_uuid)))
+            print ("Crated new network {} and uuid: {}".format(namespace.network_name, network_uuid))
         else:
         else:
-            print(("Failed create a new network {}".format(namespace.network_name)))
+            print ("Failed create a new network {}".format(namespace.network_name))
     elif action == 'vdc' or namespace.action == 'vdc':
         logger.debug("Creating a new vdc in vcloud director.".format(namespace.vdc_name))
         vdc_uuid = vim.create_vdc(namespace.vdc_name)
         if vdc_uuid is not None:
     elif action == 'vdc' or namespace.action == 'vdc':
         logger.debug("Creating a new vdc in vcloud director.".format(namespace.vdc_name))
         vdc_uuid = vim.create_vdc(namespace.vdc_name)
         if vdc_uuid is not None:
-            print(("Crated new vdc {} and uuid: {}".format(namespace.vdc_name, vdc_uuid)))
+            print ("Crated new vdc {} and uuid: {}".format(namespace.vdc_name, vdc_uuid))
         else:
         else:
-            print(("Failed create a new vdc {}".format(namespace.vdc_name)))
+            print ("Failed create a new vdc {}".format(namespace.vdc_name))
     else:
         return None
 
     else:
         return None
 
@@ -518,11 +518,11 @@ def upload_image(vim=None, image_file=None):
     try:
         catalog_uuid = vim.get_image_id_from_path(path=image_file, progress=True)
         if catalog_uuid is not None and validate_uuid4(catalog_uuid):
     try:
         catalog_uuid = vim.get_image_id_from_path(path=image_file, progress=True)
         if catalog_uuid is not None and validate_uuid4(catalog_uuid):
-            print(("Image uploaded and uuid {}".format(catalog_uuid)))
+            print("Image uploaded and uuid {}".format(catalog_uuid))
             return True
     except vimconn.vimconnException as upload_exception:
             return True
     except vimconn.vimconnException as upload_exception:
-        print(("Failed uploaded {} image".format(image_file)))
-        print(("Error Reason: {}".format(upload_exception.message)))
+        print("Failed uploaded {} image".format(image_file))
+        print("Error Reason: {}".format(upload_exception.message))
     return False
 
 
     return False
 
 
@@ -552,22 +552,22 @@ def boot_image(vim=None, image_name=None, vm_name=None):
             if vim_catalog is None:
                 return None
 
             if vim_catalog is None:
                 return None
 
-        print((" Booting {} image id {} ".format(vm_name, vim_catalog)))
+        print (" Booting {} image id {} ".format(vm_name, vim_catalog))
         vm_uuid = vim.new_vminstance(name=vm_name, image_id=vim_catalog)
         if vm_uuid is not None and validate_uuid4(vm_uuid):
         vm_uuid = vim.new_vminstance(name=vm_name, image_id=vim_catalog)
         if vm_uuid is not None and validate_uuid4(vm_uuid):
-            print(("Image booted and vm uuid {}".format(vm_uuid)))
+            print("Image booted and vm uuid {}".format(vm_uuid))
             vapp_dict = vim.get_vapp(vdc_name=namespace.vcdvdc, vapp_name=vm_uuid, isuuid=True)
             if vapp_dict is not None:
                 print_vapp(vapp_dict=vapp_dict)
         return True
     except vimconn.vimconnNotFoundException as notFound:
             vapp_dict = vim.get_vapp(vdc_name=namespace.vcdvdc, vapp_name=vm_uuid, isuuid=True)
             if vapp_dict is not None:
                 print_vapp(vapp_dict=vapp_dict)
         return True
     except vimconn.vimconnNotFoundException as notFound:
-        print(("Failed boot {} image".format(image_name)))
-        print((notFound.message))
+        print("Failed boot {} image".format(image_name))
+        print(notFound.message)
     except vimconn.vimconnException as vimconError:
     except vimconn.vimconnException as vimconError:
-        print(("Failed boot {} image".format(image_name)))
-        print((vimconError.message))
+        print("Failed boot {} image".format(image_name))
+        print(vimconError.message)
     except:
     except:
-        print(("Failed boot {} image".format(image_name)))
+        print("Failed boot {} image".format(image_name))
 
 
         return False
 
 
         return False
@@ -610,7 +610,7 @@ def vmwarecli(command=None, action=None, namespace=None):
 
     if namespace.vcdvdc is None:
         while True:
 
     if namespace.vcdvdc is None:
         while True:
-            vcduser = eval(input("Enter vcd username: "))
+            vcduser = input("Enter vcd username: ")
             if vcduser is not None and len(vcduser) > 0:
                 break
     else:
             if vcduser is not None and len(vcduser) > 0:
                 break
     else:
@@ -618,7 +618,7 @@ def vmwarecli(command=None, action=None, namespace=None):
 
     if namespace.vcdpassword is None:
         while True:
 
     if namespace.vcdpassword is None:
         while True:
-            vcdpasword = eval(input("Please enter vcd password: "))
+            vcdpasword = input("Please enter vcd password: ")
             if vcdpasword is not None and len(vcdpasword) > 0:
                 break
     else:
             if vcdpasword is not None and len(vcdpasword) > 0:
                 break
     else:
@@ -626,7 +626,7 @@ def vmwarecli(command=None, action=None, namespace=None):
 
     if namespace.vcdhost is None:
         while True:
 
     if namespace.vcdhost is None:
         while True:
-            vcdhost = eval(input("Please enter vcd host name or ip: "))
+            vcdhost = input("Please enter vcd host name or ip: ")
             if vcdhost is not None and len(vcdhost) > 0:
                 break
     else:
             if vcdhost is not None and len(vcdhost) > 0:
                 break
     else:
@@ -634,7 +634,7 @@ def vmwarecli(command=None, action=None, namespace=None):
 
     if namespace.vcdorg is None:
         while True:
 
     if namespace.vcdorg is None:
         while True:
-            vcdorg = eval(input("Please enter vcd organization name: "))
+            vcdorg = input("Please enter vcd organization name: ")
             if vcdorg is not None and len(vcdorg) > 0:
                 break
     else:
             if vcdorg is not None and len(vcdorg) > 0:
                 break
     else:
@@ -796,7 +796,7 @@ if __name__ == '__main__':
 
     namespace = parser.parse_args()
     # put command_line args to mapping
 
     namespace = parser.parse_args()
     # put command_line args to mapping
-    command_line_args = {k: v for k, v in list(vars(namespace).items()) if v}
+    command_line_args = {k: v for k, v in vars(namespace).items() if v}
 
     d = defaults.copy()
     d.update(os.environ)
 
     d = defaults.copy()
     d.update(os.environ)
index 0d6c432..9c558e3 100644 (file)
@@ -1,20 +1 @@
-PyYAML
-bottle
-MySQL-python
-jsonschema
-paramiko
-argcomplete
-requests
-logutils
-python-openstackclient
-python-novaclient
-python-keystoneclient
-python-glanceclient
-python-neutronclient
-python-cinderclient
-pyvcloud
-pyvmomi
-progressbar
-prettytable
-boto
-
+.
index 4fa3273..030dd2d 100755 (executable)
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 #from distutils.core import setup
 #from distutils.command.install_data import install_data
 
 #from distutils.core import setup
 #from distutils.command.install_data import install_data
@@ -19,6 +19,7 @@ _requirements = [
     "bottle",
     #"mysqlclient",
     #"MySQLdb",
     "bottle",
     #"mysqlclient",
     #"MySQLdb",
+    "mysqlclient",
     "jsonschema",
     "paramiko",
     "argcomplete",
     "jsonschema",
     "paramiko",
     "argcomplete",
@@ -38,6 +39,16 @@ _requirements = [
     #"lib_osm_openvim",
     #"osm_im",
     "pycrypto",
     #"lib_osm_openvim",
     #"osm_im",
     "pycrypto",
+    "bcrypt",
+    "netaddr",
+    "pyparsing",
+    "iso8601",
+    "debtcollector",
+    "monotonic",
+    "stevedore",
+    "positional",
+    # vmware dependencies
+    "progressbar2",
 ]
 
 setup(name=_name,
 ]
 
 setup(name=_name,
@@ -66,4 +77,3 @@ setup(name=_name,
       setup_requires=['setuptools-version-command'],
       #test_suite='nose.collector',
       )
       setup_requires=['setuptools-version-command'],
       #test_suite='nose.collector',
       )
-
diff --git a/tox.ini b/tox.ini
index 025f4a0..6fd781f 100644 (file)
--- a/tox.ini
+++ b/tox.ini
@@ -1,6 +1,6 @@
 [tox]
 #envlist = py27,py3
 [tox]
 #envlist = py27,py3
-envlist = py27
+envlist = py3
 toxworkdir={homedir}/.tox
 
 [testenv]
 toxworkdir={homedir}/.tox
 
 [testenv]
@@ -9,14 +9,14 @@ deps=nose
 commands=nosetests
 
 [testenv:flake8]
 commands=nosetests
 
 [testenv:flake8]
-basepython = python
+basepython = python3
 deps = flake8
 commands =
     flake8 setup.py
 
 [testenv:build]
 deps = flake8
 commands =
     flake8 setup.py
 
 [testenv:build]
-basepython = python
+basepython = python3
 deps = stdeb
        setuptools-version-command
 deps = stdeb
        setuptools-version-command
-commands = python setup.py --command-packages=stdeb.command bdist_deb
+commands = python3 setup.py --command-packages=stdeb.command bdist_deb