2to3 conversion for osm_ro
[osm/RO.git] / osm_ro / vimconn_openstack.py
index e3d3334..44178a8 100644 (file)
@@ -35,14 +35,13 @@ 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$"
 
-import vimconn
+from . import vimconn
 import json
 import logging
 import netaddr
 import time
 import yaml
 import random
 import json
 import logging
 import netaddr
 import time
 import yaml
 import random
-import sys
 import re
 import copy
 
 import re
 import copy
 
@@ -56,12 +55,10 @@ 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 requests.exceptions import ConnectionError
 from neutronclient.neutron import client as neClient
 from neutronclient.common import exceptions as neExceptions
 from requests.exceptions import ConnectionError
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
 
 
 """contain the openstack virtual machine status to openmano status"""
 
 
 """contain the openstack virtual machine status to openmano status"""
@@ -386,7 +383,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):
@@ -399,7 +396,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):
@@ -635,7 +632,6 @@ class vimconnector(vimconn.vimconnector):
         except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
             self._format_exception(e)
 
         except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
             self._format_exception(e)
 
-
     def new_flavor(self, flavor_data, change_name_if_used=True):
         '''Adds a tenant flavor to openstack VIM
         if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
     def new_flavor(self, flavor_data, change_name_if_used=True):
         '''Adds a tenant flavor to openstack VIM
         if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
@@ -784,7 +780,7 @@ class vimconnector(vimconn.vimconnector):
                 new_image_nova.metadata.setdefault('location',image_dict['location'])
                 metadata_to_load = image_dict.get('metadata')
                 if metadata_to_load:
                 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).iteritems():
+                    for k,v in yaml.load(metadata_to_load).items():
                         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:
@@ -848,41 +844,6 @@ class vimconnector(vimconn.vimconnector):
         except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
             self._format_exception(e)
 
         except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
             self._format_exception(e)
 
-    @staticmethod
-    def _create_mimemultipart(content_list):
-        """Creates a MIMEmultipart text combining the content_list
-        :param content_list: list of text scripts to be combined
-        :return: str of the created MIMEmultipart. If the list is empty returns None, if the list contains only one
-        element MIMEmultipart is not created and this content is returned
-        """
-        if not content_list:
-            return None
-        elif len(content_list) == 1:
-            return content_list[0]
-        combined_message = MIMEMultipart()
-        for content in content_list:
-            if content.startswith('#include'):
-                format = 'text/x-include-url'
-            elif content.startswith('#include-once'):
-                format = 'text/x-include-once-url'
-            elif content.startswith('#!'):
-                format = 'text/x-shellscript'
-            elif content.startswith('#cloud-config'):
-                format = 'text/cloud-config'
-            elif content.startswith('#cloud-config-archive'):
-                format = 'text/cloud-config-archive'
-            elif content.startswith('#upstart-job'):
-                format = 'text/upstart-job'
-            elif content.startswith('#part-handler'):
-                format = 'text/part-handler'
-            elif content.startswith('#cloud-boothook'):
-                format = 'text/cloud-boothook'
-            else:  # by default
-                format = 'text/x-shellscript'
-            sub_message = MIMEText(content, format, sys.getdefaultencoding())
-            combined_message.attach(sub_message)
-        return combined_message.as_string()
-
     def __wait_for_vm(self, vm_id, status):
         """wait until vm is in the desired status and return True.
         If the VM gets in ERROR status, return false.
     def __wait_for_vm(self, vm_id, status):
         """wait until vm is in the desired status and return True.
         If the VM gets in ERROR status, return false.
@@ -1091,58 +1052,7 @@ class vimconnector(vimconn.vimconnector):
             if type(security_groups) is str:
                 security_groups = ( security_groups, )
             #cloud config
             if type(security_groups) is str:
                 security_groups = ( security_groups, )
             #cloud config
-            userdata=None
-            config_drive = None
-            userdata_list = []
-            if isinstance(cloud_config, dict):
-                if cloud_config.get("user-data"):
-                    if isinstance(cloud_config["user-data"], str):
-                        userdata_list.append(cloud_config["user-data"])
-                    else:
-                        for u in cloud_config["user-data"]:
-                            userdata_list.append(u)
-                if cloud_config.get("boot-data-drive") != None:
-                    config_drive = cloud_config["boot-data-drive"]
-                if cloud_config.get("config-files") or cloud_config.get("users") or cloud_config.get("key-pairs"):
-                    userdata_dict={}
-                    #default user
-                    if cloud_config.get("key-pairs"):
-                        userdata_dict["ssh-authorized-keys"] = cloud_config["key-pairs"]
-                        userdata_dict["users"] = [{"default": None, "ssh-authorized-keys": cloud_config["key-pairs"] }]
-                    if cloud_config.get("users"):
-                        if "users" not in userdata_dict:
-                            userdata_dict["users"] = [ "default" ]
-                        for user in cloud_config["users"]:
-                            user_info = {
-                                "name" : user["name"],
-                                "sudo": "ALL = (ALL)NOPASSWD:ALL"
-                            }
-                            if "user-info" in user:
-                                user_info["gecos"] = user["user-info"]
-                            if user.get("key-pairs"):
-                                user_info["ssh-authorized-keys"] = user["key-pairs"]
-                            userdata_dict["users"].append(user_info)
-
-                    if cloud_config.get("config-files"):
-                        userdata_dict["write_files"] = []
-                        for file in cloud_config["config-files"]:
-                            file_info = {
-                                "path" : file["dest"],
-                                "content": file["content"]
-                            }
-                            if file.get("encoding"):
-                                file_info["encoding"] = file["encoding"]
-                            if file.get("permissions"):
-                                file_info["permissions"] = file["permissions"]
-                            if file.get("owner"):
-                                file_info["owner"] = file["owner"]
-                            userdata_dict["write_files"].append(file_info)
-                    userdata_list.append("#cloud-config\n" + yaml.safe_dump(userdata_dict, indent=4,
-                                                                              default_flow_style=False))
-                    userdata = self._create_mimemultipart(userdata_list)
-                self.logger.debug("userdata: %s", userdata)
-            elif isinstance(cloud_config, str):
-                userdata = cloud_config
+            config_drive, userdata = self._create_user_data(cloud_config)
 
             #Create additional volumes in case these are present in disk_list
             base_disk_index = ord('b')
 
             #Create additional volumes in case these are present in disk_list
             base_disk_index = ord('b')
@@ -1163,7 +1073,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.itervalues():
+                    for volume_id in block_device_mapping.values():
                         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:
@@ -1173,7 +1083,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.itervalues():
+                    for volume_id in block_device_mapping.values():
                         self.cinder.volumes.delete(volume_id)
 
                     #delete ports we just created
                         self.cinder.volumes.delete(volume_id)
 
                     #delete ports we just created
@@ -1277,7 +1187,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.itervalues():
+                for volume_id in block_device_mapping.values():
                     self.cinder.volumes.delete(volume_id)
 
             # Delete the VM
                     self.cinder.volumes.delete(volume_id)
 
             # Delete the VM
@@ -1594,8 +1504,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 = map(int, vlanID_range.replace(" ", "").split("-"))
-                for vlanID in xrange(start_vlanid, end_vlanid + 1):
+                start_vlanid , end_vlanid = list(map(int, vlanID_range.replace(" ", "").split("-")))
+                for vlanID in range(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:
@@ -1620,7 +1530,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 = map(int,vlan_range.split("-"))
+            start_vlanid , end_vlanid = list(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 "\
@@ -1691,7 +1601,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):
@@ -1715,7 +1625,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):
@@ -1744,7 +1654,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):