Merge "Created new class NeutronException."
[snaps.git] / snaps / openstack / utils / neutron_utils.py
index aaa0903..d93faa0 100644 (file)
@@ -18,7 +18,8 @@ from neutronclient.common.exceptions import NotFound
 from neutronclient.neutron.client import Client
 
 from snaps.domain.network import (
-    Port, SecurityGroup, SecurityGroupRule, Router, InterfaceRouter)
+    Port, SecurityGroup, SecurityGroupRule, Router, InterfaceRouter, Subnet,
+    Network)
 from snaps.domain.vm_inst import FloatingIp
 from snaps.openstack.utils import keystone_utils
 
@@ -50,26 +51,26 @@ def create_network(neutron, os_creds, network_settings):
     :param network_settings: A dictionary containing the network configuration
                              and is responsible for creating the network
                             request JSON body
-    :return: the network object
+    :return: a SNAPS-OO Network domain object
     """
     if neutron and network_settings:
         logger.info('Creating network with name ' + network_settings.name)
         json_body = network_settings.dict_for_neutron(os_creds)
-        return neutron.create_network(body=json_body)
+        os_network = neutron.create_network(body=json_body)
+        return Network(**os_network['network'])
     else:
-        logger.error("Failed to create network")
-        raise Exception
+        raise NeutronException('Failded to create network')
 
 
 def delete_network(neutron, network):
     """
     Deletes a network for OpenStack
     :param neutron: the client
-    :param network: the network object
+    :param network: a SNAPS-OO Network domain object
     """
     if neutron and network:
-        logger.info('Deleting network with name ' + network['network']['name'])
-        neutron.delete_network(network['network']['id'])
+        logger.info('Deleting network with name ' + network.name)
+        neutron.delete_network(network.id)
 
 
 def get_network(neutron, network_name, project_id=None):
@@ -79,7 +80,7 @@ def get_network(neutron, network_name, project_id=None):
     :param neutron: the client
     :param network_name: the name of the network to retrieve
     :param project_id: the id of the network's project
-    :return:
+    :return: a SNAPS-OO Network domain object
     """
     net_filter = dict()
     if network_name:
@@ -91,10 +92,7 @@ def get_network(neutron, network_name, project_id=None):
     for network, netInsts in networks.items():
         for inst in netInsts:
             if inst.get('name') == network_name:
-                if project_id and inst.get('project_id') == project_id:
-                    return {'network': inst}
-                else:
-                    return {'network': inst}
+                return Network(**inst)
     return None
 
 
@@ -103,13 +101,13 @@ def get_network_by_id(neutron, network_id):
     Returns the network object (dictionary) with the given ID
     :param neutron: the client
     :param network_id: the id of the network to retrieve
-    :return:
+    :return: a SNAPS-OO Network domain object
     """
     networks = neutron.list_networks(**{'id': network_id})
     for network, netInsts in networks.items():
         for inst in netInsts:
             if inst.get('id') == network_id:
-                return {'network': inst}
+                return Network(**inst)
     return None
 
 
@@ -122,28 +120,27 @@ def create_subnet(neutron, subnet_settings, os_creds, network=None):
                             and is responsible for creating the subnet request
                             JSON body
     :param os_creds: the OpenStack credentials
-    :return: the subnet object
+    :return: a SNAPS-OO Subnet domain object
     """
     if neutron and network and subnet_settings:
         json_body = {'subnets': [subnet_settings.dict_for_neutron(
             os_creds, network=network)]}
         logger.info('Creating subnet with name ' + subnet_settings.name)
         subnets = neutron.create_subnet(body=json_body)
-        return {'subnet': subnets['subnets'][0]}
+        return Subnet(**subnets['subnets'][0])
     else:
-        logger.error("Failed to create subnet.")
-        raise Exception
+        raise NeutronException('Failed to create subnet')
 
 
 def delete_subnet(neutron, subnet):
     """
     Deletes a network subnet for OpenStack
     :param neutron: the client
-    :param subnet: the subnet object
+    :param subnet: a SNAPS-OO Subnet domain object
     """
     if neutron and subnet:
-        logger.info('Deleting subnet with name ' + subnet['subnet']['name'])
-        neutron.delete_subnet(subnet['subnet']['id'])
+        logger.info('Deleting subnet with name ' + subnet.name)
+        neutron.delete_subnet(subnet.id)
 
 
 def get_subnet_by_name(neutron, subnet_name):
@@ -151,13 +148,13 @@ def get_subnet_by_name(neutron, subnet_name):
     Returns the first subnet object (dictionary) found with a given name
     :param neutron: the client
     :param subnet_name: the name of the network to retrieve
-    :return:
+    :return: a SNAPS-OO Subnet domain object
     """
     subnets = neutron.list_subnets(**{'name': subnet_name})
     for subnet, subnetInst in subnets.items():
         for inst in subnetInst:
-            if inst.get('name') == subnet_name:
-                return {'subnet': inst}
+            if inst['name'] == subnet_name:
+                return Subnet(**inst)
     return None
 
 
@@ -178,7 +175,7 @@ def create_router(neutron, os_creds, router_settings):
         return Router(**os_router['router'])
     else:
         logger.error("Failed to create router.")
-        raise Exception
+        raise NeutronException('Failed to create router')
 
 
 def delete_router(neutron, router):
@@ -218,8 +215,9 @@ def add_interface_router(neutron, router, subnet=None, port=None):
     :return: the interface router object
     """
     if subnet and port:
-        raise Exception('Cannot add interface to the router. Both subnet and '
-                        'port were sent in. Either or please.')
+        raise NeutronException(
+            'Cannot add interface to the router. Both subnet and '
+            'port were sent in. Either or please.')
 
     if neutron and router and (router or subnet):
         logger.info('Adding interface to router with name ' + router.name)
@@ -227,8 +225,9 @@ def add_interface_router(neutron, router, subnet=None, port=None):
             router=router.id, body=__create_port_json_body(subnet, port))
         return InterfaceRouter(**os_intf_router)
     else:
-        raise Exception('Unable to create interface router as neutron client,'
-                        ' router or subnet were not created')
+        raise NeutronException(
+            'Unable to create interface router as neutron client,'
+            ' router or subnet were not created')
 
 
 def remove_interface_router(neutron, router, subnet=None, port=None):
@@ -264,12 +263,14 @@ def __create_port_json_body(subnet=None, port=None):
     :return: the dict
     """
     if subnet and port:
-        raise Exception('Cannot create JSON body with both subnet and port')
+        raise NeutronException(
+            'Cannot create JSON body with both subnet and port')
     if not subnet and not port:
-        raise Exception('Cannot create JSON body without subnet or port')
+        raise NeutronException(
+            'Cannot create JSON body without subnet or port')
 
     if subnet:
-        return {"subnet_id": subnet['subnet']['id']}
+        return {"subnet_id": subnet.id}
     else:
         return {"port_id": port.id}
 
@@ -297,7 +298,6 @@ def delete_port(neutron, port):
     Removes an OpenStack port
     :param neutron: the client
     :param port: the SNAPS-OO Port domain object
-    :return:
     """
     logger.info('Deleting port with name ' + port.name)
     neutron.delete_port(port.id)
@@ -308,7 +308,7 @@ def get_port_by_name(neutron, port_name):
     Returns the first port object (dictionary) found with a given name
     :param neutron: the client
     :param port_name: the name of the port to retrieve
-    :return:
+    :return: a SNAPS-OO Port domain object
     """
     ports = neutron.list_ports(**{'name': port_name})
     for port in ports['ports']:
@@ -324,7 +324,7 @@ def create_security_group(neutron, keystone, sec_grp_settings):
     :param neutron: the Neutron client
     :param keystone: the Keystone client
     :param sec_grp_settings: the security group settings
-    :return: the security group object
+    :return: a SNAPS-OO SecurityGroup domain object
     """
     logger.info('Creating security group with name - %s',
                 sec_grp_settings.name)
@@ -352,6 +352,7 @@ def get_security_group(neutron, name):
     Returns the first security group object of the given name else None
     :param neutron: the client
     :param name: the name of security group object to retrieve
+    :return: a SNAPS-OO SecurityGroup domain object or None if not found
     """
     logger.info('Retrieving security group with name - ' + name)
 
@@ -369,6 +370,7 @@ def get_security_group_by_id(neutron, sec_grp_id):
     Returns the first security group object of the given name else None
     :param neutron: the client
     :param sec_grp_id: the id of the security group to retrieve
+    :return: a SNAPS-OO SecurityGroup domain object or None if not found
     """
     logger.info('Retrieving security group with ID - ' + sec_grp_id)
 
@@ -386,7 +388,7 @@ def create_security_group_rule(neutron, sec_grp_rule_settings):
     Creates a security group object in OpenStack
     :param neutron: the client
     :param sec_grp_rule_settings: the security group rule settings
-    :return: the security group object
+    :return: a SNAPS-OO SecurityGroupRule domain object
     """
     logger.info('Creating security group to security group - %s',
                 sec_grp_rule_settings.sec_grp_name)
@@ -410,7 +412,7 @@ def get_rules_by_security_group(neutron, sec_grp):
     """
     Retrieves all of the rules for a given security group
     :param neutron: the client
-    :param sec_grp: the SNAPS SecurityGroup object
+    :param sec_grp: a list of SNAPS SecurityGroupRule domain objects
     """
     logger.info('Retrieving security group rules associate with the '
                 'security group - %s', sec_grp.name)
@@ -429,6 +431,7 @@ def get_rule_by_id(neutron, sec_grp, rule_id):
     :param neutron: the client
     :param sec_grp: the SNAPS SecurityGroup domain object
     :param rule_id: the rule's ID
+    :param sec_grp: a SNAPS SecurityGroupRule domain object
     """
     rules = neutron.list_security_group_rules(
         **{'security_group_id': sec_grp.id})
@@ -443,12 +446,12 @@ def get_external_networks(neutron):
     Returns a list of external OpenStack network object/dict for all external
     networks
     :param neutron: the client
-    :return: a list of external networks (empty list if none configured)
+    :return: a list of external networks of Type SNAPS-OO domain class Network
     """
     out = list()
     for network in neutron.list_networks(
             **{'router:external': True})['networks']:
-        out.append({'network': network})
+        out.append(Network(**network))
     return out
 
 
@@ -480,13 +483,13 @@ def create_floating_ip(neutron, ext_net_name):
     if ext_net:
         fip = neutron.create_floatingip(
             body={'floatingip':
-                  {'floating_network_id': ext_net['network']['id']}})
+                  {'floating_network_id': ext_net.id}})
 
         return FloatingIp(inst_id=fip['floatingip']['id'],
                           ip=fip['floatingip']['floating_ip_address'])
     else:
-        raise Exception('Cannot create floating IP, '
-                        'external network not found')
+        raise NeutronException(
+            'Cannot create floating IP, external network not found')
 
 
 def get_floating_ip(neutron, floating_ip):
@@ -499,13 +502,13 @@ def get_floating_ip(neutron, floating_ip):
     """
     logger.debug('Attempting to retrieve existing floating ip with IP - %s',
                  floating_ip.ip)
-    os_fip = get_os_floating_ip(neutron, floating_ip)
+    os_fip = __get_os_floating_ip(neutron, floating_ip)
     if os_fip:
         return FloatingIp(
             inst_id=os_fip['id'], ip=os_fip['floating_ip_address'])
 
 
-def get_os_floating_ip(neutron, floating_ip):
+def __get_os_floating_ip(neutron, floating_ip):
     """
     Returns an OpenStack floating IP object
     parameter
@@ -532,3 +535,9 @@ def delete_floating_ip(neutron, floating_ip):
     logger.debug('Attempting to delete existing floating ip with IP - %s',
                  floating_ip.ip)
     return neutron.delete_floatingip(floating_ip.id)
+
+
+class NeutronException(Exception):
+    """
+    Exception when calls to the Keystone client cannot be served properly
+    """